@weftlabs/cli 0.26.9 → 0.29.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 CHANGED
@@ -1,9 +1,11 @@
1
1
  # Weft CLI
2
2
 
3
3
  Use Weft from a shell or an autonomous agent. Application code should use the
4
- separate [`@weftlabs/sdk`](../typescript/README.md) package. The human-oriented
4
+ separate [`@weftlabs/sdk`](https://github.com/weftlabs/weft-sdk/blob/main/typescript/README.md) package. The human-oriented
5
5
  CLI guide is at [weftlabs.com/x402/cli](https://weftlabs.com/x402/cli).
6
6
 
7
+ The CLI moved from `weft-sdk` on 2026-10-04. The package name is still `@weftlabs/cli`.
8
+
7
9
  The CLI prints one versioned JSON object per command. It accepts credentials
8
10
  through `--api-key-stdin`, `WEFT_API_KEY`, or its protected local credential
9
11
  store; it rejects API keys in command arguments so they do not leak into shell
@@ -216,5 +218,5 @@ new bootstrap flows do not create OAuth credentials.
216
218
 
217
219
  See [`examples/agent-bootstrap.sh`](examples/agent-bootstrap.sh) for the same
218
220
  sequence as a script, and
219
- [`docs/operation-inventory.md`](../docs/operation-inventory.md) for commands,
221
+ [`docs/contract.md`](docs/contract.md) for commands,
220
222
  output envelopes, and stable exit codes.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/credentials.ts","../src/cli.ts","../src/results.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n chmod,\n mkdir,\n open,\n readFile,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nconst CREDENTIALS_FILE_MODE = 0o600;\nconst CREDENTIALS_DIR_MODE = 0o700;\nconst LOCK_RETRY_MS = 50;\nconst LOCK_TIMEOUT_MS = 10_000;\n\nexport interface BootstrapCredentials {\n base_url: string;\n id: string;\n status: string;\n capabilities: string[];\n expires_at: string | null;\n approval: {\n method: string;\n expires_in: number;\n interval: number;\n user_code?: string;\n };\n temporary_api_key: string;\n}\n\nexport interface LegacyBootstrapCredentials {\n version: 1;\n type: \"bootstrap\";\n base_url: string;\n bootstrap_id: string;\n temporary_api_key: string;\n device_code: string;\n client_id: string;\n expiry: string;\n polling_interval: number;\n}\n\nexport interface OAuthCredentials {\n version: 1;\n type: \"oauth\";\n base_url: string;\n client_id: string;\n access_token: string;\n refresh_token: string;\n token_type: string;\n scope: string;\n expiry: string;\n}\n\nexport type StoredCredentials =\n BootstrapCredentials | LegacyBootstrapCredentials | OAuthCredentials;\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isBootstrapCredentials(\n value: Record<string, unknown>,\n): BootstrapCredentials | undefined {\n if (\n typeof value.base_url === \"string\" &&\n typeof value.id === \"string\" &&\n typeof value.status === \"string\" &&\n Array.isArray(value.capabilities) &&\n value.capabilities.every((capability) => typeof capability === \"string\") &&\n (typeof value.expires_at === \"string\" || value.expires_at === null) &&\n isObject(value.approval) &&\n typeof value.approval.method === \"string\" &&\n typeof value.approval.expires_in === \"number\" &&\n typeof value.approval.interval === \"number\" &&\n (value.approval.user_code === undefined ||\n typeof value.approval.user_code === \"string\") &&\n typeof value.temporary_api_key === \"string\"\n ) {\n return value as BootstrapCredentials;\n }\n\n return undefined;\n}\n\nfunction isLegacyBootstrapCredentials(\n value: Record<string, unknown>,\n): LegacyBootstrapCredentials | undefined {\n if (\n value.version === 1 &&\n value.type === \"bootstrap\" &&\n typeof value.base_url === \"string\" &&\n typeof value.bootstrap_id === \"string\" &&\n typeof value.temporary_api_key === \"string\" &&\n typeof value.device_code === \"string\" &&\n typeof value.client_id === \"string\" &&\n typeof value.expiry === \"string\" &&\n typeof value.polling_interval === \"number\"\n ) {\n return value as LegacyBootstrapCredentials;\n }\n\n return undefined;\n}\n\nfunction isOAuthCredentials(\n value: Record<string, unknown>,\n): OAuthCredentials | undefined {\n if (\n value.type === \"oauth\" &&\n typeof value.version === \"number\" &&\n typeof value.base_url === \"string\" &&\n typeof value.client_id === \"string\" &&\n typeof value.access_token === \"string\" &&\n typeof value.refresh_token === \"string\" &&\n typeof value.token_type === \"string\" &&\n typeof value.scope === \"string\" &&\n typeof value.expiry === \"string\"\n ) {\n return value as OAuthCredentials;\n }\n\n return undefined;\n}\n\nexport function resolveCredentialsPath(\n env: Record<string, string | undefined>,\n): string | undefined {\n if (env.WEFT_CREDENTIALS_FILE) return env.WEFT_CREDENTIALS_FILE;\n if (env.XDG_CONFIG_HOME)\n return `${env.XDG_CONFIG_HOME}/weft/credentials.json`;\n const home = env.HOME || env.USERPROFILE;\n if (!home) return undefined;\n return `${home}/.config/weft/credentials.json`;\n}\n\nexport async function readStoredCredentials(\n env: Record<string, string | undefined>,\n): Promise<StoredCredentials | undefined> {\n const path = resolveCredentialsPath(env);\n if (!path) return undefined;\n try {\n const raw = await readFile(path, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n if (!isObject(parsed)) throw new Error(\"Stored credentials malformed\");\n return (\n isBootstrapCredentials(parsed) ??\n isLegacyBootstrapCredentials(parsed) ??\n isOAuthCredentials(parsed)\n );\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw error;\n }\n}\n\nexport async function writeStoredCredentials(\n env: Record<string, string | undefined>,\n credentials: StoredCredentials,\n): Promise<void> {\n await withCredentialsLock(env, () =>\n writeStoredCredentialsWhileLocked(env, credentials),\n );\n}\n\nexport async function writeStoredCredentialsWhileLocked(\n env: Record<string, string | undefined>,\n credentials: StoredCredentials,\n): Promise<void> {\n const path = resolveCredentialsPath(env);\n if (!path) {\n throw new Error(\"HOME, USERPROFILE, or WEFT_CREDENTIALS_FILE is required\");\n }\n const parent = dirname(path);\n await mkdir(parent, { recursive: true, mode: CREDENTIALS_DIR_MODE });\n await chmod(parent, CREDENTIALS_DIR_MODE);\n\n const tempPath = `${path}.${randomUUID()}.tmp`;\n try {\n await writeFile(tempPath, JSON.stringify(credentials), {\n mode: CREDENTIALS_FILE_MODE,\n });\n await rename(tempPath, path);\n await chmod(path, CREDENTIALS_FILE_MODE);\n } catch (error) {\n await rm(tempPath, { force: true });\n throw error;\n }\n}\n\nexport async function withCredentialsLock<T>(\n env: Record<string, string | undefined>,\n action: () => Promise<T>,\n): Promise<T> {\n const path = resolveCredentialsPath(env);\n if (!path) {\n throw new Error(\"HOME, USERPROFILE, or WEFT_CREDENTIALS_FILE is required\");\n }\n const lockPath = `${path}.lock`;\n const deadline = Date.now() + LOCK_TIMEOUT_MS;\n await mkdir(dirname(path), { recursive: true, mode: CREDENTIALS_DIR_MODE });\n\n for (;;) {\n try {\n const lock = await open(lockPath, \"wx\", CREDENTIALS_FILE_MODE);\n await lock.close();\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (Date.now() >= deadline) {\n throw new Error(\n `Timed out waiting for the credential lock; if no Weft CLI process is running, remove ${lockPath}`,\n );\n }\n await delay(LOCK_RETRY_MS);\n }\n }\n\n try {\n return await action();\n } finally {\n await rm(lockPath, { force: true });\n }\n}\n","import {\n readStoredCredentials,\n type BootstrapCredentials,\n type LegacyBootstrapCredentials,\n type OAuthCredentials,\n type StoredCredentials,\n withCredentialsLock,\n writeStoredCredentials,\n writeStoredCredentialsWhileLocked,\n} from \"./credentials\";\nimport { spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport {\n readableBody,\n reserveResultDirectory,\n writeResultFile,\n} from \"./results\";\nimport {\n type PaidFetchRequest,\n ResponseError,\n WeftClient,\n WeftError,\n} from \"@weftlabs/sdk\";\n\nexport const EXIT_SUCCESS = 0;\nexport const EXIT_USAGE = 2;\nexport const EXIT_AUTH = 3;\nexport const EXIT_API = 4;\nexport const EXIT_INTERNAL = 5;\n\ntype Command =\n | \"bootstrap\"\n | \"auth\"\n | \"skill\"\n | \"me\"\n | \"balance\"\n | \"search\"\n | \"fetch\"\n | \"purchases\";\n\nconst COMMANDS: Command[] = [\n \"bootstrap\",\n \"auth\",\n \"skill\",\n \"me\",\n \"balance\",\n \"search\",\n \"fetch\",\n \"purchases\",\n];\n\nconst WEFT_API_BASE = \"https://weft.network\";\nconst OAUTH_HOST_NAME = \"Weft CLI\";\nconst OAUTH_REFRESH_SKEW_MS = 60_000;\nconst PROCESS_OUTPUT_LIMIT = 8_192;\nconst SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst CORE_SKILL_NAMES = new Set([\"weft\", \"weft-setup\"]);\n\nconst COMMAND_HELP = {\n bootstrap: {\n description: \"Bootstrap an agent account\",\n usage: \"weft bootstrap --email <email> --agent-name <name> --reason <text>\",\n options: [\n \"--email <email>\",\n \"--agent-name <name>\",\n \"--reason <text>\",\n \"[--base-url <url>]\",\n ],\n },\n auth: {\n description: \"Check bootstrap status\",\n usage: \"weft auth status\",\n options: [\"status\"],\n },\n skill: {\n description: \"Install the core Weft Skill or one optional workflow Skill\",\n usage: \"weft skill install [name --agent <agent> [--global]]\",\n options: [\"install\", \"[name]\", \"--agent <agent>\", \"--global\"],\n },\n me: {\n description: \"Return the authenticated principal\",\n usage: \"weft me\",\n options: [],\n },\n balance: {\n description: \"Return wallet balance and spending policy\",\n usage: \"weft balance\",\n options: [],\n },\n search: {\n description: \"Search for payable resources\",\n usage: \"weft search <query> [--max-results <1..50>]\",\n options: [\"--max-results <1..50>\"],\n },\n fetch: {\n description: \"Fetch a URL within an explicit spending limit\",\n usage:\n \"weft fetch <url> --max-cost-usd <amount> [--method <method>] [--body <json>] [--header <name:value>]... [--idempotency-key <key>] [--raw]\",\n options: [\n \"--max-cost-usd <amount>\",\n \"--method <method>\",\n \"--body <json>\",\n \"--header <name:value> (repeatable)\",\n \"--idempotency-key <key>\",\n \"--raw\",\n ],\n },\n purchases: {\n description: \"List purchases or return one purchase by ID\",\n usage: \"weft purchases [id] [--page <number>] [--per-page <1..100>]\",\n options: [\"--page <number>\", \"--per-page <1..100>\"],\n },\n} satisfies Record<\n Command,\n { description: string; usage: string; options: string[] }\n>;\n\ninterface SkillInstallResult {\n status: \"ok\" | \"skipped\";\n reason?: string;\n installed: number;\n hosts: string[];\n warnings: string[];\n}\n\ntype SkillInstaller = (options?: {\n force?: boolean;\n silent?: boolean;\n}) => Promise<SkillInstallResult>;\n\n/**\n * The Skill installer ships as a plain script beside `dist/`, and reads the\n * packed Skill relative to its own location. The specifier is built at runtime\n * so the bundler leaves it external and that relative path stays correct in the\n * published package.\n */\nasync function loadSkillInstaller(): Promise<SkillInstaller> {\n const specifier = new URL(\"../scripts/install-skill.mjs\", import.meta.url)\n .href;\n const module = (await import(specifier)) as { installSkill: SkillInstaller };\n return module.installSkill;\n}\n\n/**\n * Best-effort Skill installation on any ordinary command. This is the safety\n * net for a user who never runs `weft skill install`, and it is what lets the\n * Skill appear in an agent host that was installed after the CLI. It is\n * idempotent, it stays silent, and it never fails the command the user asked\n * for.\n */\nasync function installSkillInBackground(): Promise<void> {\n try {\n const installSkill = await loadSkillInstaller();\n await installSkill({ silent: true });\n } catch {\n // Deliberately ignored — `weft skill install` is the surface that reports\n // installation problems.\n }\n}\n\ninterface BootstrapCreateResponse {\n data: Omit<BootstrapCredentials, \"base_url\">;\n}\n\ninterface BootstrapStatus {\n data: {\n id?: string;\n status: string;\n expires_at?: string | null;\n capabilities?: string[];\n approval?: BootstrapCredentials[\"approval\"];\n };\n}\n\ninterface OAuthTokenResponse {\n access_token: string;\n token_type: string;\n expires_in: number;\n refresh_token: string;\n scope: string;\n}\n\nconst GLOBAL_OPTIONS = [\"--api-key-stdin\", \"--base-url <url>\", \"--help\", \"-h\"];\n\nexport interface CliDependencies {\n env?: Record<string, string | undefined>;\n fetchApi?: typeof fetch;\n readStdin?: () => Promise<string>;\n writeOut?: (value: string) => void | Promise<void>;\n writeErr?: (value: string) => void;\n generateIdempotencyKey?: () => string;\n runProcess?: ProcessRunner;\n platform?: NodeJS.Platform;\n nodeExecutable?: string;\n npxCliPath?: string;\n}\n\ninterface ProcessResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\ntype ProcessRunner = (\n command: string,\n args: string[],\n) => Promise<ProcessResult>;\n\ninterface ParsedArgs {\n command: Command;\n apiKeyStdin: boolean;\n baseUrl?: string;\n positionals: string[];\n options: Map<string, string | true | string[]>;\n}\n\nclass CliError extends Error {\n constructor(\n readonly exitCode: number,\n readonly code: string,\n message: string,\n readonly details?: unknown,\n ) {\n super(message);\n }\n}\n\nfunction takeValue(\n args: string[],\n index: number,\n option: string,\n): [string, number] {\n const value = args[index + 1];\n if (value == null || value.startsWith(\"--\")) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n `${option} requires a value`,\n );\n }\n return [value, index + 1];\n}\n\nfunction appendBounded(current: string, chunk: Buffer | string): string {\n return `${current}${chunk.toString()}`.slice(-PROCESS_OUTPUT_LIMIT);\n}\n\nfunction defaultRunProcess(\n command: string,\n args: string[],\n): Promise<ProcessResult> {\n return new Promise((resolve) => {\n const child = spawn(command, args, {\n shell: false,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.on(\"data\", (chunk: Buffer) => {\n stdout = appendBounded(stdout, chunk);\n });\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderr = appendBounded(stderr, chunk);\n });\n child.on(\"error\", (error) => {\n resolve({\n exitCode: 1,\n stdout,\n stderr: appendBounded(stderr, error.message),\n });\n });\n child.on(\"close\", (exitCode) => {\n resolve({ exitCode: exitCode ?? 1, stdout, stderr });\n });\n });\n}\n\nfunction resolveNpxCliPath(\n env: Record<string, string | undefined>,\n nodeExecutable: string,\n): string | undefined {\n const executableDirectory = dirname(nodeExecutable);\n const candidates = [\n ...(env.npm_execpath\n ? [join(dirname(env.npm_execpath), \"npx-cli.js\")]\n : []),\n join(executableDirectory, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\"),\n join(\n executableDirectory,\n \"..\",\n \"lib\",\n \"node_modules\",\n \"npm\",\n \"bin\",\n \"npx-cli.js\",\n ),\n ];\n return candidates.find((candidate) => existsSync(candidate));\n}\n\nfunction npxProcessInvocation(\n processArgs: string[],\n dependencies: CliDependencies,\n env: Record<string, string | undefined>,\n): { executable: string; arguments: string[] } {\n if ((dependencies.platform ?? process.platform) !== \"win32\") {\n return { executable: \"npx\", arguments: processArgs };\n }\n\n const nodeExecutable = dependencies.nodeExecutable ?? process.execPath;\n const npxCliPath =\n dependencies.npxCliPath ?? resolveNpxCliPath(env, nodeExecutable);\n if (!npxCliPath) {\n throw new CliError(\n EXIT_INTERNAL,\n \"NPX_NOT_FOUND\",\n \"Could not find the npm npx program. Install npm, then run the command again.\",\n );\n }\n return {\n executable: nodeExecutable,\n arguments: [npxCliPath, ...processArgs],\n };\n}\n\nfunction rejectUnsafeCredentialArgument(args: string[]): void {\n if (args.some((arg) => arg === \"--api-key\" || arg.startsWith(\"--api-key=\"))) {\n throw new CliError(\n EXIT_USAGE,\n \"UNSAFE_CREDENTIAL_ARGUMENT\",\n \"API keys are accepted only through WEFT_API_KEY or --api-key-stdin\",\n );\n }\n}\n\nfunction requestedHelp(args: string[]): Command | \"all\" | undefined {\n const isHelp = (value: string) => value === \"--help\" || value === \"-h\";\n if (args.length === 1 && isHelp(args[0])) return \"all\";\n if (\n args.length === 2 &&\n COMMANDS.includes(args[0] as Command) &&\n isHelp(args[1])\n ) {\n return args[0] as Command;\n }\n return undefined;\n}\n\nfunction helpData(command: Command | \"all\") {\n if (command !== \"all\") {\n return {\n command,\n ...COMMAND_HELP[command],\n global_options: GLOBAL_OPTIONS,\n };\n }\n return {\n usage: \"weft <command> [options]\",\n commands: COMMANDS.map((name) => ({ name, ...COMMAND_HELP[name] })),\n global_options: GLOBAL_OPTIONS,\n authentication: [\"WEFT_API_KEY\", \"--api-key-stdin\"],\n exit_codes: { success: 0, usage: 2, auth: 3, api: 4, internal: 5 },\n };\n}\n\nfunction parseArgs(args: string[]): ParsedArgs {\n let command: Command | undefined;\n let apiKeyStdin = false;\n let baseUrl: string | undefined;\n const positionals: string[] = [];\n const options = new Map<string, string | true | string[]>();\n\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === \"--api-key-stdin\") {\n apiKeyStdin = true;\n } else if (arg === \"--base-url\") {\n [baseUrl, index] = takeValue(args, index, arg);\n } else if (arg === \"--global\" || arg === \"--raw\") {\n options.set(arg.slice(2), true);\n } else if (arg.startsWith(\"--\")) {\n const [value, nextIndex] = takeValue(args, index, arg);\n const name = arg.slice(2);\n if (name === \"header\") {\n const previous = options.get(name);\n if (typeof previous === \"string\") {\n options.set(name, [previous, value]);\n } else if (Array.isArray(previous)) {\n previous.push(value);\n } else {\n options.set(name, value);\n }\n } else {\n options.set(name, value);\n }\n index = nextIndex;\n } else if (!command) {\n if (!COMMANDS.includes(arg as Command)) {\n throw new CliError(\n EXIT_USAGE,\n \"UNKNOWN_COMMAND\",\n `Unknown command: ${arg}`,\n );\n }\n command = arg as Command;\n } else {\n positionals.push(arg);\n }\n }\n\n if (!command) {\n throw new CliError(\n EXIT_USAGE,\n \"COMMAND_REQUIRED\",\n \"Command required: bootstrap, auth, me, balance, search, fetch, or purchases\",\n );\n }\n\n return { command, apiKeyStdin, baseUrl, positionals, options };\n}\n\nfunction positiveInteger(\n value: string | true | string[] | undefined,\n option: string,\n maximum?: number,\n): number | undefined {\n if (value == null) return undefined;\n if (typeof value !== \"string\") {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n `${option} must be a positive integer`,\n );\n }\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n `${option} must be a positive integer`,\n );\n }\n if (maximum != null && parsed > maximum) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n `${option} must be at most ${maximum}`,\n );\n }\n return parsed;\n}\n\nfunction requiredOption(\n options: Map<string, string | true | string[]>,\n name: string,\n): string {\n const value = options.get(name);\n if (typeof value !== \"string\" || !value.trim()) {\n throw new CliError(EXIT_USAGE, \"MISSING_ARGUMENT\", `--${name} is required`);\n }\n return value;\n}\n\nfunction fetchHeaders(\n raw: string | true | string[] | undefined,\n hasJsonBody: boolean,\n): PaidFetchRequest[\"headers\"] {\n const values =\n typeof raw === \"string\" ? [raw] : Array.isArray(raw) ? raw : [];\n const headers: Record<string, string> = {};\n for (const rawHeader of values) {\n const colon = rawHeader.indexOf(\":\");\n if (colon <= 0) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"--header must be Name:Value\",\n );\n }\n headers[rawHeader.slice(0, colon).trim()] = rawHeader\n .slice(colon + 1)\n .trim();\n }\n if (\n hasJsonBody &&\n !Object.keys(headers).some((name) => name.toLowerCase() === \"content-type\")\n ) {\n headers[\"content-type\"] = \"application/json\";\n }\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nfunction baseApiUrl(\n baseUrl: string | undefined,\n env: Record<string, string | undefined>,\n): string {\n const raw = baseUrl ?? env.WEFT_BASE_URL ?? WEFT_API_BASE;\n return raw.endsWith(\"/\") ? raw.slice(0, -1) : raw;\n}\n\nfunction resolveApiKeyFromStored(\n credentials?: StoredCredentials,\n): string | undefined {\n if (!credentials) return undefined;\n if (\n \"access_token\" in credentials &&\n typeof credentials.access_token === \"string\" &&\n credentials.access_token.trim()\n ) {\n return credentials.access_token;\n }\n if (\n \"temporary_api_key\" in credentials &&\n typeof credentials.temporary_api_key === \"string\" &&\n credentials.temporary_api_key.trim()\n ) {\n return credentials.temporary_api_key;\n }\n return undefined;\n}\n\nfunction isOAuthCredentials(\n credentials: StoredCredentials | undefined,\n): credentials is OAuthCredentials {\n return Boolean(\n credentials && \"type\" in credentials && credentials.type === \"oauth\",\n );\n}\n\nfunction isLegacyBootstrapCredentials(\n credentials: StoredCredentials | undefined,\n): credentials is LegacyBootstrapCredentials {\n return Boolean(\n credentials && \"type\" in credentials && credentials.type === \"bootstrap\",\n );\n}\n\nfunction oauthNeedsRefresh(credentials: OAuthCredentials): boolean {\n const expiry = Date.parse(credentials.expiry);\n return (\n !Number.isFinite(expiry) || expiry <= Date.now() + OAUTH_REFRESH_SKEW_MS\n );\n}\n\nasync function refreshOAuthCredentials(\n fetchApi: typeof fetch,\n env: Record<string, string | undefined>,\n stored: OAuthCredentials,\n): Promise<OAuthCredentials> {\n const token = await requestJson<OAuthTokenResponse>(\n fetchApi,\n `${stored.base_url}/oauth/token`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: stored.refresh_token,\n client_id: stored.client_id,\n }).toString(),\n },\n true,\n );\n const refreshed: OAuthCredentials = {\n ...stored,\n access_token: token.access_token,\n refresh_token: token.refresh_token,\n token_type: token.token_type,\n scope: token.scope,\n expiry: new Date(Date.now() + token.expires_in * 1000).toISOString(),\n };\n await writeStoredCredentialsWhileLocked(env, refreshed);\n return refreshed;\n}\n\nfunction noSecretFields(data: object): Record<string, unknown> {\n return {\n ...data,\n temporary_api_key: undefined,\n access_token: undefined,\n refresh_token: undefined,\n client_secret: undefined,\n };\n}\n\nasync function requestJson<T>(\n fetchApi: typeof fetch,\n url: string,\n init: RequestInit,\n redactError = false,\n): Promise<T> {\n const response = await fetchApi(url, init);\n if (!response.ok) {\n if (redactError) {\n throw new CliError(\n response.status === 401 || response.status === 403\n ? EXIT_AUTH\n : response.status >= 500\n ? EXIT_INTERNAL\n : EXIT_API,\n \"OAUTH_TOKEN_ERROR\",\n `OAuth token request failed with HTTP ${response.status}`,\n );\n }\n throw new ResponseError(response);\n }\n\n return (await response.json()) as T;\n}\n\nfunction withCredentials(\n headers: Record<string, string>,\n apiKey: string,\n): Record<string, string> {\n return {\n ...headers,\n authorization: `Bearer ${apiKey}`,\n };\n}\n\nfunction ensureOnly(\n options: Map<string, string | true | string[]>,\n allowed: string[],\n): void {\n for (const name of options.keys()) {\n if (!allowed.includes(name)) {\n throw new CliError(\n EXIT_USAGE,\n \"UNKNOWN_OPTION\",\n `Unknown option: --${name}`,\n );\n }\n }\n}\n\nasync function responseDetails(error: ResponseError): Promise<unknown> {\n try {\n return await error.response.json();\n } catch {\n return undefined;\n }\n}\n\nasync function normalizeError(error: unknown): Promise<CliError> {\n if (error instanceof CliError) return error;\n if (error instanceof WeftError) {\n // status 0 is a transport failure with no API response; it exits like an\n // internal failure, not an API rejection.\n const exitCode =\n error.status === 401 || error.status === 403\n ? EXIT_AUTH\n : error.status >= 500 || error.status === 0\n ? EXIT_INTERNAL\n : EXIT_API;\n return new CliError(exitCode, error.code, error.message, error.details);\n }\n if (error instanceof ResponseError) {\n const details = await responseDetails(error);\n const body = details as\n | {\n error?: { code?: string; message?: string } | string;\n error_description?: string;\n }\n | undefined;\n const nested = typeof body?.error === \"object\" ? body.error : undefined;\n const code =\n nested?.code ??\n (typeof body?.error === \"string\"\n ? body.error\n : `HTTP_${error.response.status}`);\n const message =\n nested?.message ??\n body?.error_description ??\n `Weft API returned HTTP ${error.response.status}`;\n const exitCode =\n error.response.status === 401 || error.response.status === 403\n ? EXIT_AUTH\n : error.response.status >= 500\n ? EXIT_INTERNAL\n : EXIT_API;\n return new CliError(exitCode, code, message, details);\n }\n const message = error instanceof Error ? error.message : String(error);\n return new CliError(EXIT_INTERNAL, \"INTERNAL_ERROR\", message);\n}\n\nasync function defaultReadStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nasync function defaultWriteOut(value: string): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n // The write callback reports failure before the stream emits its error.\n // Keep the one-shot listener until that event to prevent an uncaught EPIPE.\n const onError = (error: Error) => reject(error);\n process.stdout.once(\"error\", onError);\n process.stdout.write(value, (error) => {\n if (error) {\n reject(error);\n } else {\n process.stdout.removeListener(\"error\", onError);\n resolve();\n }\n });\n });\n}\n\nexport async function runCli(\n args: string[],\n dependencies: CliDependencies = {},\n): Promise<number> {\n const outputWriter = dependencies.writeOut ?? defaultWriteOut;\n const writeErr =\n dependencies.writeErr ?? ((value) => process.stderr.write(value));\n let command = \"unknown\";\n let idempotencyKey: string | undefined;\n let schemaVersion = \"1\";\n let meta: Record<string, unknown> | undefined;\n let deliveryReceipt: Record<string, unknown> | undefined;\n const fetchApi = dependencies.fetchApi ?? fetch;\n const writeOut = async (value: string) => {\n try {\n await outputWriter(value);\n } catch {\n throw new CliError(\n EXIT_INTERNAL,\n command === \"fetch\" ? \"RESULT_OUTPUT_FAILED\" : \"OUTPUT_FAILED\",\n \"Cannot write stdout. Use the saved result paths below if present. Otherwise keep this receipt and retry the same fetch with --idempotency-key and the same key.\",\n deliveryReceipt === undefined\n ? undefined\n : { receipt: deliveryReceipt },\n );\n }\n };\n\n try {\n rejectUnsafeCredentialArgument(args);\n const help = requestedHelp(args);\n if (help !== undefined) {\n command = \"help\";\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: helpData(help),\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n const parsed = parseArgs(args);\n command = parsed.command;\n const env = dependencies.env ?? process.env;\n const baseUrl = baseApiUrl(parsed.baseUrl, env);\n\n if (parsed.command === \"skill\") {\n if (\n parsed.positionals[0] !== \"install\" ||\n parsed.positionals.length > 2\n ) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"skill requires 'install' and accepts at most one Skill name\",\n );\n }\n\n const skillName = parsed.positionals[1];\n if (skillName) {\n ensureOnly(parsed.options, [\"agent\", \"global\"]);\n const agent = requiredOption(parsed.options, \"agent\");\n if (!SKILL_NAME_PATTERN.test(skillName)) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"Skill name must contain only lowercase letters, numbers, and single hyphens\",\n );\n }\n if (CORE_SKILL_NAMES.has(skillName)) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n `Use 'weft skill install' without a name to install the core ${skillName} Skill`,\n );\n }\n if (!SKILL_NAME_PATTERN.test(agent)) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"Agent name must contain only lowercase letters, numbers, and single hyphens\",\n );\n }\n\n const processArgs = [\n \"--yes\",\n \"skills\",\n \"add\",\n \"weftlabs/skills\",\n \"--skill\",\n skillName,\n \"--agent\",\n agent,\n \"--yes\",\n ...(parsed.options.get(\"global\") === true ? [\"--global\"] : []),\n ];\n const invocation = npxProcessInvocation(processArgs, dependencies, env);\n const result = await (dependencies.runProcess ?? defaultRunProcess)(\n invocation.executable,\n invocation.arguments,\n );\n if (result.exitCode !== 0) {\n const remediation = `npx ${processArgs.join(\" \")}`;\n throw new CliError(\n EXIT_INTERNAL,\n \"SKILL_INSTALL_FAILED\",\n `Could not install ${skillName}. Run '${remediation}' directly for more detail.`,\n {\n executable: invocation.executable,\n arguments: invocation.arguments,\n exit_code: result.exitCode,\n stderr: result.stderr,\n },\n );\n }\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: {\n status: \"installed\",\n skill: skillName,\n agent,\n scope:\n parsed.options.get(\"global\") === true ? \"global\" : \"project\",\n },\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n ensureOnly(parsed.options, []);\n const installSkill = await loadSkillInstaller();\n const result = await installSkill({ force: true });\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: {\n status: result.status,\n installed: result.installed,\n hosts: result.hosts,\n ...(result.reason === undefined ? {} : { reason: result.reason }),\n ...(result.warnings.length === 0\n ? {}\n : { warnings: result.warnings }),\n },\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n await installSkillInBackground();\n\n if (parsed.command === \"bootstrap\") {\n ensureOnly(parsed.options, [\"email\", \"agent-name\", \"reason\"]);\n if (parsed.positionals.length !== 0) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"bootstrap does not accept positional arguments\",\n );\n }\n const email = requiredOption(parsed.options, \"email\");\n const agentName = requiredOption(parsed.options, \"agent-name\");\n const reason = requiredOption(parsed.options, \"reason\");\n\n const bootstrap = await requestJson<BootstrapCreateResponse>(\n fetchApi,\n `${baseUrl}/api/v1/account_bootstraps`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n email,\n agent_name: agentName,\n host_name: OAUTH_HOST_NAME,\n reason,\n }),\n },\n );\n\n const stored: BootstrapCredentials = {\n ...bootstrap.data,\n base_url: baseUrl,\n };\n\n await writeStoredCredentials(env, stored);\n\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: noSecretFields(stored),\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n if (parsed.command === \"auth\") {\n ensureOnly(parsed.options, []);\n if (\n parsed.positionals.length !== 1 ||\n parsed.positionals[0] !== \"status\"\n ) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"auth requires 'status'\",\n );\n }\n\n const stored = await readStoredCredentials(env);\n if (isOAuthCredentials(stored)) {\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: {\n status: \"consumed\",\n authentication: \"oauth\",\n scope: stored.scope,\n },\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n if (isLegacyBootstrapCredentials(stored)) {\n const status = await requestJson<BootstrapStatus>(\n fetchApi,\n `${stored.base_url}/api/v1/account_bootstraps/${stored.bootstrap_id}`,\n {\n method: \"GET\",\n headers: withCredentials({}, stored.temporary_api_key),\n },\n );\n if (\n status.data.status !== \"claimed\" &&\n status.data.status !== \"consumed\"\n ) {\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: { status: status.data.status },\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n const token = await requestJson<OAuthTokenResponse>(\n fetchApi,\n `${stored.base_url}/oauth/token`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/x-www-form-urlencoded\",\n },\n body: new URLSearchParams({\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n device_code: stored.device_code,\n client_id: stored.client_id,\n name: \"Weft CLI\",\n }).toString(),\n },\n true,\n );\n const oauth: OAuthCredentials = {\n version: 1,\n type: \"oauth\",\n base_url: stored.base_url,\n client_id: stored.client_id,\n access_token: token.access_token,\n refresh_token: token.refresh_token,\n token_type: token.token_type,\n scope: token.scope,\n expiry: new Date(Date.now() + token.expires_in * 1000).toISOString(),\n };\n const active = await withCredentialsLock(env, async () => {\n const current = await readStoredCredentials(env);\n if (isOAuthCredentials(current)) return current;\n if (\n !isLegacyBootstrapCredentials(current) ||\n JSON.stringify(current) !== JSON.stringify(stored)\n ) {\n throw new CliError(\n EXIT_AUTH,\n \"CREDENTIALS_CHANGED\",\n \"Stored credentials changed; rerun auth status\",\n );\n }\n await writeStoredCredentialsWhileLocked(env, oauth);\n return oauth;\n });\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: {\n status: \"consumed\",\n authentication: \"oauth\",\n scope: active.scope,\n },\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n if (!stored) {\n throw new CliError(\n EXIT_AUTH,\n \"BOOTSTRAP_REQUIRED\",\n \"Run weft bootstrap before auth status\",\n );\n }\n\n const status = await requestJson<BootstrapStatus>(\n fetchApi,\n `${stored.base_url}/api/v1/account_bootstraps/${stored.id}`,\n {\n method: \"GET\",\n headers: withCredentials({}, stored.temporary_api_key),\n },\n );\n\n const merged: BootstrapCredentials = {\n base_url: stored.base_url,\n id: status.data.id ?? stored.id,\n status: status.data.status,\n capabilities: status.data.capabilities ?? stored.capabilities,\n expires_at:\n status.data.expires_at === undefined\n ? stored.expires_at\n : status.data.expires_at,\n approval: status.data.approval ?? stored.approval,\n temporary_api_key: stored.temporary_api_key,\n };\n const active = await withCredentialsLock(env, async () => {\n const current = await readStoredCredentials(env);\n if (JSON.stringify(current) !== JSON.stringify(stored)) {\n throw new CliError(\n EXIT_AUTH,\n \"CREDENTIALS_CHANGED\",\n \"Stored credentials changed; rerun auth status\",\n );\n }\n await writeStoredCredentialsWhileLocked(env, merged);\n return merged;\n });\n\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: noSecretFields(active),\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n const rawKey = parsed.apiKeyStdin\n ? await (dependencies.readStdin ?? defaultReadStdin)()\n : env.WEFT_API_KEY;\n let apiKey = rawKey?.trim();\n let authenticatedBaseUrl = baseUrl;\n if (parsed.apiKeyStdin && !apiKey) {\n throw new CliError(\n EXIT_AUTH,\n \"API_KEY_REQUIRED\",\n \"--api-key-stdin requires a non-empty API key\",\n );\n }\n if (!apiKey && !parsed.apiKeyStdin) {\n let stored = await readStoredCredentials(env);\n if (isOAuthCredentials(stored) && oauthNeedsRefresh(stored)) {\n stored = await withCredentialsLock(env, async () => {\n const current = await readStoredCredentials(env);\n if (isOAuthCredentials(current) && oauthNeedsRefresh(current)) {\n return refreshOAuthCredentials(fetchApi, env, current);\n }\n return current;\n });\n }\n apiKey = resolveApiKeyFromStored(stored);\n if (stored) {\n authenticatedBaseUrl = stored.base_url;\n }\n }\n\n if (!apiKey) {\n throw new CliError(\n EXIT_AUTH,\n \"API_KEY_REQUIRED\",\n \"Set WEFT_API_KEY, pass --api-key-stdin, or store credentials\",\n );\n }\n\n const client = new WeftClient({\n apiKey,\n baseUrl: authenticatedBaseUrl,\n fetchApi,\n });\n\n let data: unknown;\n if (parsed.command === \"me\") {\n ensureOnly(parsed.options, []);\n data = await client.me();\n } else if (parsed.command === \"balance\") {\n ensureOnly(parsed.options, []);\n data = await client.balance();\n } else if (parsed.command === \"search\") {\n ensureOnly(parsed.options, [\"max-results\"]);\n if (parsed.positionals.length !== 1) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"search requires exactly one query\",\n );\n }\n data = await client.search({\n query: parsed.positionals[0],\n maxResults: positiveInteger(\n parsed.options.get(\"max-results\"),\n \"--max-results\",\n 50,\n ),\n });\n } else if (parsed.command === \"fetch\") {\n ensureOnly(parsed.options, [\n \"max-cost-usd\",\n \"method\",\n \"body\",\n \"header\",\n \"idempotency-key\",\n \"raw\",\n ]);\n const raw = parsed.options.has(\"raw\");\n schemaVersion = raw ? \"1\" : \"2\";\n if (parsed.positionals.length !== 1) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"fetch requires exactly one URL\",\n );\n }\n const maxCostUsd = requiredOption(parsed.options, \"max-cost-usd\");\n if (!/^\\d+(?:\\.\\d+)?$/.test(maxCostUsd)) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"--max-cost-usd must be a non-negative decimal\",\n );\n }\n const method = parsed.options.get(\"method\");\n const rawBody = parsed.options.get(\"body\");\n let body: PaidFetchRequest[\"body\"];\n if (typeof rawBody === \"string\") {\n try {\n JSON.parse(rawBody);\n } catch {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"--body must be JSON\",\n );\n }\n body = rawBody;\n }\n const headers = fetchHeaders(\n parsed.options.get(\"header\"),\n typeof rawBody === \"string\",\n );\n const request: PaidFetchRequest = {\n url: parsed.positionals[0],\n maxCostUsd,\n method:\n typeof method === \"string\"\n ? (method.toUpperCase() as PaidFetchRequest[\"method\"])\n : undefined,\n body,\n headers,\n };\n const explicitKey = parsed.options.get(\"idempotency-key\");\n idempotencyKey =\n typeof explicitKey === \"string\"\n ? explicitKey\n : (dependencies.generateIdempotencyKey ?? randomUUID)();\n let resultDirectory: string | undefined;\n if (!raw) {\n try {\n resultDirectory = await reserveResultDirectory(env);\n } catch {\n throw new CliError(\n EXIT_INTERNAL,\n \"RESULT_STORAGE_UNAVAILABLE\",\n \"Cannot reserve local result storage. Set WEFT_RESULTS_DIR to a directory you own that is writable only by you, with no symlink at that path, then retry. No fetch was sent.\",\n );\n }\n }\n const response = await client.fetch(request, { idempotencyKey });\n meta = { idempotency_key: idempotencyKey };\n data = response;\n const { bodyBase64, ...receipt } = response;\n deliveryReceipt = receipt;\n if (resultDirectory) {\n const savedPath = join(resultDirectory, \"body\");\n const receiptPath = join(resultDirectory, \"receipt.json\");\n const bytes =\n typeof bodyBase64 === \"string\"\n ? Buffer.from(bodyBase64, \"base64\")\n : undefined;\n if (!bytes || bytes.toString(\"base64\") !== bodyBase64) {\n throw new CliError(\n EXIT_INTERNAL,\n \"RESULT_DECODE_FAILED\",\n \"Fetch returned invalid Base64. No body was saved. Keep this receipt and retry the same request with --idempotency-key and the same key; if it persists, report the artifact ID to support.\",\n { receipt, file_complete: false },\n );\n }\n try {\n meta = {\n ...meta,\n saved_path: savedPath,\n receipt_path: receiptPath,\n byte_count: bytes.length,\n };\n await writeResultFile(\n receiptPath,\n `${JSON.stringify({ schema_version: \"2\", meta, data: receipt })}\\n`,\n );\n await writeResultFile(savedPath, bytes);\n data = { ...receipt, ...readableBody(bytes, response.headers) };\n } catch {\n throw new CliError(\n EXIT_INTERNAL,\n \"RESULT_STORAGE_FAILED\",\n \"Fetch returned, but local result delivery failed. Keep this receipt. Check local storage, then retry the same request with --idempotency-key and the key below. Do not use a new key.\",\n {\n receipt,\n saved_path: savedPath,\n receipt_path: receiptPath,\n file_complete: false,\n },\n );\n }\n }\n } else {\n ensureOnly(parsed.options, [\"page\", \"per-page\"]);\n if (parsed.positionals.length > 1) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"purchases accepts at most one purchase ID\",\n );\n }\n data = parsed.positionals[0]\n ? await client.purchase(\n positiveInteger(parsed.positionals[0], \"purchase ID\")!,\n )\n : await client.purchases({\n page: positiveInteger(parsed.options.get(\"page\"), \"--page\"),\n perPage: positiveInteger(\n parsed.options.get(\"per-page\"),\n \"--per-page\",\n 100,\n ),\n });\n }\n\n await writeOut(\n `${JSON.stringify({\n schema_version: schemaVersion,\n ok: true,\n command,\n ...(meta === undefined ? {} : { meta }),\n data,\n })}\\n`,\n );\n return EXIT_SUCCESS;\n } catch (error) {\n const normalized = await normalizeError(error);\n writeErr(\n `${JSON.stringify({\n schema_version: schemaVersion,\n ok: false,\n command,\n ...(idempotencyKey === undefined\n ? {}\n : { meta: { ...meta, idempotency_key: idempotencyKey } }),\n error: {\n code: normalized.code,\n message: normalized.message,\n ...(normalized.details === undefined\n ? {}\n : { details: normalized.details }),\n },\n })}\\n`,\n );\n return normalized.exitCode;\n }\n}\n","import { chmod, lstat, mkdir, mkdtemp, open, realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\nexport async function reserveResultDirectory(\n env: Record<string, string | undefined>,\n): Promise<string> {\n const root = resolve(\n env.WEFT_RESULTS_DIR ||\n join(env.HOME || env.USERPROFILE || homedir(), \".weft-results\"),\n );\n await mkdir(root, { recursive: true, mode: 0o700 });\n const stat = await lstat(root);\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new Error(\n \"The result storage root must be a directory, not a symlink\",\n );\n }\n if (\n process.platform !== \"win32\" &&\n ((stat.mode & 0o022) !== 0 || stat.uid !== process.getuid?.())\n ) {\n throw new Error(\n \"The result storage root must be owned by this user and not writable by others\",\n );\n }\n // A private child keeps payloads protected without changing an existing parent.\n const directory = await mkdtemp(join(await realpath(root), \"result-\"));\n await chmod(directory, 0o700);\n return directory;\n}\n\nexport async function writeResultFile(\n path: string,\n contents: string | Buffer,\n): Promise<void> {\n const file = await open(path, \"wx\", 0o600);\n try {\n await file.chmod(0o600);\n await file.writeFile(contents);\n await file.sync();\n } finally {\n await file.close();\n }\n}\n\nexport function readableBody(\n bytes: Buffer,\n headers: Record<string, string>,\n): {\n media_type: string | null;\n body_encoding: \"utf-8\" | \"file\";\n body?: string;\n} {\n const header = (name: string) =>\n Object.entries(headers).find(([key]) => key.toLowerCase() === name)?.[1];\n const contentType = header(\"content-type\")?.toLowerCase() ?? \"\";\n const mediaType = contentType.split(\";\", 1)[0].trim();\n const charset = /(?:^|;)\\s*charset\\s*=\\s*\"?([^;\"\\s]+)/.exec(contentType)?.[1];\n const encoding = header(\"content-encoding\")?.trim().toLowerCase();\n const file = {\n media_type: mediaType || null,\n body_encoding: \"file\" as const,\n };\n const textual =\n mediaType.startsWith(\"text/\") ||\n /^application\\/(?:json|xml|javascript|x-ndjson|x-www-form-urlencoded|[^;]+\\+(?:json|xml))$/.test(\n mediaType,\n );\n if (\n (encoding && encoding !== \"identity\") ||\n (charset && ![\"utf-8\", \"utf8\", \"us-ascii\"].includes(charset)) ||\n (!textual && !(bytes.length === 0 && !mediaType))\n )\n return file;\n try {\n // Keep a UTF-8 BOM and JSON spelling exactly as delivered.\n const body = new TextDecoder(\"utf-8\", {\n fatal: true,\n ignoreBOM: true,\n }).decode(bytes);\n return { media_type: mediaType || null, body_encoding: \"utf-8\", body };\n } catch {\n return file;\n }\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;AACxB,SAAS,cAAc,aAAa;AAEpC,IAAM,wBAAwB;AAC9B,IAAM,uBAAuB;AAC7B,IAAM,gBAAgB;AACtB,IAAM,kBAAkB;AA4CxB,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAEA,SAAS,uBACP,OACkC;AAClC,MACE,OAAO,MAAM,aAAa,YAC1B,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,WAAW,YACxB,MAA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AC1D,SAAS;AAAA,UACP,OAAO,QAAQ,IAAI,UAAU;AAAA,UAC7B;AAAA,UACA;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACP;AAEA,UAAM;AAAA,MACJ,GAAG,KAAK,UAAU;AAAA,QAChB,gBAAgB;AAAA,QAChB,IAAI;AAAA,QACJ;AAAA,QACA,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,KAAK;AAAA,QACrC;AAAA,MACF,CAAC,CAAC;AAAA;AAAA,IACJ;AACA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,UAAM,aAAa,MAAM,eAAe,KAAK;AAC7C;AAAA,MACE,GAAG,KAAK,UAAU;AAAA,QAChB,gBAAgB;AAAA,QAChB,IAAI;AAAA,QACJ;AAAA,QACA,GAAI,mBAAmB,SACnB,CAAC,IACD,EAAE,MAAM,EAAE,GAAG,MAAM,iBAAiB,eAAe,EAAE;AAAA,QACzD,OAAO;AAAA,UACL,MAAM,WAAW;AAAA,UACjB,SAAS,WAAW;AAAA,UACpB,GAAI,WAAW,YAAY,SACvB,CAAC,IACD,EAAE,SAAS,WAAW,QAAQ;AAAA,QACpC;AAAA,MACF,CAAC,CAAC;AAAA;AAAA,IACJ;AACA,WAAO,WAAW;AAAA,EACpB;AACF;","names":["randomUUID","dirname","join","chmod","mkdir","open","resolve","dirname","join","isOAuthCredentials","isLegacyBootstrapCredentials","message","result","status","active","randomUUID"]}
1
+ {"version":3,"sources":["../src/credentials.ts","../src/cli.ts","../src/results.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n chmod,\n mkdir,\n open,\n readFile,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nconst CREDENTIALS_FILE_MODE = 0o600;\nconst CREDENTIALS_DIR_MODE = 0o700;\nconst LOCK_RETRY_MS = 50;\nconst LOCK_TIMEOUT_MS = 10_000;\n\nexport interface BootstrapCredentials {\n base_url: string;\n id: string;\n status: string;\n capabilities: string[];\n expires_at: string | null;\n approval: {\n method: string;\n expires_in: number;\n interval: number;\n user_code?: string;\n };\n temporary_api_key: string;\n}\n\nexport interface LegacyBootstrapCredentials {\n version: 1;\n type: \"bootstrap\";\n base_url: string;\n bootstrap_id: string;\n temporary_api_key: string;\n device_code: string;\n client_id: string;\n expiry: string;\n polling_interval: number;\n}\n\nexport interface OAuthCredentials {\n version: 1;\n type: \"oauth\";\n base_url: string;\n client_id: string;\n access_token: string;\n refresh_token: string;\n token_type: string;\n scope: string;\n expiry: string;\n}\n\nexport type StoredCredentials =\n BootstrapCredentials | LegacyBootstrapCredentials | OAuthCredentials;\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isBootstrapCredentials(\n value: Record<string, unknown>,\n): BootstrapCredentials | undefined {\n if (\n typeof value.base_url === \"string\" &&\n typeof value.id === \"string\" &&\n typeof value.status === \"string\" &&\n Array.isArray(value.capabilities) &&\n value.capabilities.every((capability) => typeof capability === \"string\") &&\n (typeof value.expires_at === \"string\" || value.expires_at === null) &&\n isObject(value.approval) &&\n typeof value.approval.method === \"string\" &&\n typeof value.approval.expires_in === \"number\" &&\n typeof value.approval.interval === \"number\" &&\n (value.approval.user_code === undefined ||\n typeof value.approval.user_code === \"string\") &&\n typeof value.temporary_api_key === \"string\"\n ) {\n return value as unknown as BootstrapCredentials;\n }\n\n return undefined;\n}\n\nfunction isLegacyBootstrapCredentials(\n value: Record<string, unknown>,\n): LegacyBootstrapCredentials | undefined {\n if (\n value.version === 1 &&\n value.type === \"bootstrap\" &&\n typeof value.base_url === \"string\" &&\n typeof value.bootstrap_id === \"string\" &&\n typeof value.temporary_api_key === \"string\" &&\n typeof value.device_code === \"string\" &&\n typeof value.client_id === \"string\" &&\n typeof value.expiry === \"string\" &&\n typeof value.polling_interval === \"number\"\n ) {\n return value as unknown as LegacyBootstrapCredentials;\n }\n\n return undefined;\n}\n\nfunction isOAuthCredentials(\n value: Record<string, unknown>,\n): OAuthCredentials | undefined {\n if (\n value.type === \"oauth\" &&\n typeof value.version === \"number\" &&\n typeof value.base_url === \"string\" &&\n typeof value.client_id === \"string\" &&\n typeof value.access_token === \"string\" &&\n typeof value.refresh_token === \"string\" &&\n typeof value.token_type === \"string\" &&\n typeof value.scope === \"string\" &&\n typeof value.expiry === \"string\"\n ) {\n return value as unknown as OAuthCredentials;\n }\n\n return undefined;\n}\n\nexport function resolveCredentialsPath(\n env: Record<string, string | undefined>,\n): string | undefined {\n if (env.WEFT_CREDENTIALS_FILE) return env.WEFT_CREDENTIALS_FILE;\n if (env.XDG_CONFIG_HOME)\n return `${env.XDG_CONFIG_HOME}/weft/credentials.json`;\n const home = env.HOME || env.USERPROFILE;\n if (!home) return undefined;\n return `${home}/.config/weft/credentials.json`;\n}\n\nexport async function readStoredCredentials(\n env: Record<string, string | undefined>,\n): Promise<StoredCredentials | undefined> {\n const path = resolveCredentialsPath(env);\n if (!path) return undefined;\n try {\n const raw = await readFile(path, \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n if (!isObject(parsed)) throw new Error(\"Stored credentials malformed\");\n return (\n isBootstrapCredentials(parsed) ??\n isLegacyBootstrapCredentials(parsed) ??\n isOAuthCredentials(parsed)\n );\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw error;\n }\n}\n\nexport async function writeStoredCredentials(\n env: Record<string, string | undefined>,\n credentials: StoredCredentials,\n): Promise<void> {\n await withCredentialsLock(env, () =>\n writeStoredCredentialsWhileLocked(env, credentials),\n );\n}\n\nexport async function writeStoredCredentialsWhileLocked(\n env: Record<string, string | undefined>,\n credentials: StoredCredentials,\n): Promise<void> {\n const path = resolveCredentialsPath(env);\n if (!path) {\n throw new Error(\"HOME, USERPROFILE, or WEFT_CREDENTIALS_FILE is required\");\n }\n const parent = dirname(path);\n await mkdir(parent, { recursive: true, mode: CREDENTIALS_DIR_MODE });\n await chmod(parent, CREDENTIALS_DIR_MODE);\n\n const tempPath = `${path}.${randomUUID()}.tmp`;\n try {\n await writeFile(tempPath, JSON.stringify(credentials), {\n mode: CREDENTIALS_FILE_MODE,\n });\n await rename(tempPath, path);\n await chmod(path, CREDENTIALS_FILE_MODE);\n } catch (error) {\n await rm(tempPath, { force: true });\n throw error;\n }\n}\n\nexport async function withCredentialsLock<T>(\n env: Record<string, string | undefined>,\n action: () => Promise<T>,\n): Promise<T> {\n const path = resolveCredentialsPath(env);\n if (!path) {\n throw new Error(\"HOME, USERPROFILE, or WEFT_CREDENTIALS_FILE is required\");\n }\n const lockPath = `${path}.lock`;\n const deadline = Date.now() + LOCK_TIMEOUT_MS;\n await mkdir(dirname(path), { recursive: true, mode: CREDENTIALS_DIR_MODE });\n\n for (;;) {\n try {\n const lock = await open(lockPath, \"wx\", CREDENTIALS_FILE_MODE);\n await lock.close();\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (Date.now() >= deadline) {\n throw new Error(\n `Timed out waiting for the credential lock; if no Weft CLI process is running, remove ${lockPath}`,\n );\n }\n await delay(LOCK_RETRY_MS);\n }\n }\n\n try {\n return await action();\n } finally {\n await rm(lockPath, { force: true });\n }\n}\n","import {\n readStoredCredentials,\n type BootstrapCredentials,\n type LegacyBootstrapCredentials,\n type OAuthCredentials,\n type StoredCredentials,\n withCredentialsLock,\n writeStoredCredentials,\n writeStoredCredentialsWhileLocked,\n} from \"./credentials\";\nimport { spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport {\n readableBody,\n reserveResultDirectory,\n writeResultFile,\n} from \"./results\";\nimport {\n type PaidFetchRequest,\n ResponseError,\n WeftClient,\n WeftError,\n} from \"@weftlabs/sdk\";\n\nexport const EXIT_SUCCESS = 0;\nexport const EXIT_USAGE = 2;\nexport const EXIT_AUTH = 3;\nexport const EXIT_API = 4;\nexport const EXIT_INTERNAL = 5;\n\ntype Command =\n | \"bootstrap\"\n | \"auth\"\n | \"skill\"\n | \"me\"\n | \"balance\"\n | \"search\"\n | \"fetch\"\n | \"purchases\";\n\nconst COMMANDS: Command[] = [\n \"bootstrap\",\n \"auth\",\n \"skill\",\n \"me\",\n \"balance\",\n \"search\",\n \"fetch\",\n \"purchases\",\n];\n\nconst WEFT_API_BASE = \"https://weft.network\";\nconst OAUTH_HOST_NAME = \"Weft CLI\";\nconst OAUTH_REFRESH_SKEW_MS = 60_000;\nconst PROCESS_OUTPUT_LIMIT = 8_192;\nconst SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst CORE_SKILL_NAMES = new Set([\"weft\", \"weft-setup\"]);\n\nconst COMMAND_HELP = {\n bootstrap: {\n description: \"Bootstrap an agent account\",\n usage: \"weft bootstrap --email <email> --agent-name <name> --reason <text>\",\n options: [\n \"--email <email>\",\n \"--agent-name <name>\",\n \"--reason <text>\",\n \"[--base-url <url>]\",\n ],\n },\n auth: {\n description: \"Check bootstrap status\",\n usage: \"weft auth status\",\n options: [\"status\"],\n },\n skill: {\n description: \"Install the core Weft Skill or one optional workflow Skill\",\n usage: \"weft skill install [name --agent <agent> [--global]]\",\n options: [\"install\", \"[name]\", \"--agent <agent>\", \"--global\"],\n },\n me: {\n description: \"Return the authenticated principal\",\n usage: \"weft me\",\n options: [],\n },\n balance: {\n description: \"Return wallet balance and spending policy\",\n usage: \"weft balance\",\n options: [],\n },\n search: {\n description: \"Search for payable resources\",\n usage: \"weft search <query> [--max-results <1..50>]\",\n options: [\"--max-results <1..50>\"],\n },\n fetch: {\n description: \"Fetch a URL within an explicit spending limit\",\n usage:\n \"weft fetch <url> --max-cost-usd <amount> [--method <method>] [--body <json>] [--header <name:value>]... [--idempotency-key <key>] [--raw]\",\n options: [\n \"--max-cost-usd <amount>\",\n \"--method <method>\",\n \"--body <json>\",\n \"--header <name:value> (repeatable)\",\n \"--idempotency-key <key>\",\n \"--raw\",\n ],\n },\n purchases: {\n description: \"List purchases or return one purchase by ID\",\n usage: \"weft purchases [id] [--page <number>] [--per-page <1..100>]\",\n options: [\"--page <number>\", \"--per-page <1..100>\"],\n },\n} satisfies Record<\n Command,\n { description: string; usage: string; options: string[] }\n>;\n\ninterface SkillInstallResult {\n status: \"ok\" | \"skipped\";\n reason?: string;\n installed: number;\n hosts: string[];\n warnings: string[];\n}\n\ntype SkillInstaller = (options?: {\n force?: boolean;\n silent?: boolean;\n}) => Promise<SkillInstallResult>;\n\n/**\n * The Skill installer ships as a plain script beside `dist/`, and reads the\n * packed Skill relative to its own location. The specifier is built at runtime\n * so the bundler leaves it external and that relative path stays correct in the\n * published package.\n */\nasync function loadSkillInstaller(): Promise<SkillInstaller> {\n const specifier = new URL(\"../scripts/install-skill.mjs\", import.meta.url)\n .href;\n const module = (await import(specifier)) as { installSkill: SkillInstaller };\n return module.installSkill;\n}\n\n/**\n * Best-effort Skill installation on any ordinary command. This is the safety\n * net for a user who never runs `weft skill install`, and it is what lets the\n * Skill appear in an agent host that was installed after the CLI. It is\n * idempotent, it stays silent, and it never fails the command the user asked\n * for.\n */\nasync function installSkillInBackground(): Promise<void> {\n try {\n const installSkill = await loadSkillInstaller();\n await installSkill({ silent: true });\n } catch {\n // Deliberately ignored — `weft skill install` is the surface that reports\n // installation problems.\n }\n}\n\ninterface BootstrapCreateResponse {\n data: Omit<BootstrapCredentials, \"base_url\">;\n}\n\ninterface BootstrapStatus {\n data: {\n id?: string;\n status: string;\n expires_at?: string | null;\n capabilities?: string[];\n approval?: BootstrapCredentials[\"approval\"];\n };\n}\n\ninterface OAuthTokenResponse {\n access_token: string;\n token_type: string;\n expires_in: number;\n refresh_token: string;\n scope: string;\n}\n\nconst GLOBAL_OPTIONS = [\"--api-key-stdin\", \"--base-url <url>\", \"--help\", \"-h\"];\n\nexport interface CliDependencies {\n env?: Record<string, string | undefined>;\n fetchApi?: typeof fetch;\n readStdin?: () => Promise<string>;\n writeOut?: (value: string) => void | Promise<void>;\n writeErr?: (value: string) => void;\n generateIdempotencyKey?: () => string;\n runProcess?: ProcessRunner;\n platform?: NodeJS.Platform;\n nodeExecutable?: string;\n npxCliPath?: string;\n}\n\ninterface ProcessResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\ntype ProcessRunner = (\n command: string,\n args: string[],\n) => Promise<ProcessResult>;\n\ninterface ParsedArgs {\n command: Command;\n apiKeyStdin: boolean;\n baseUrl?: string;\n positionals: string[];\n options: Map<string, string | true | string[]>;\n}\n\nclass CliError extends Error {\n constructor(\n readonly exitCode: number,\n readonly code: string,\n message: string,\n readonly details?: unknown,\n ) {\n super(message);\n }\n}\n\nfunction takeValue(\n args: string[],\n index: number,\n option: string,\n): [string, number] {\n const value = args[index + 1];\n if (value == null || value.startsWith(\"--\")) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n `${option} requires a value`,\n );\n }\n return [value, index + 1];\n}\n\nfunction appendBounded(current: string, chunk: Buffer | string): string {\n return `${current}${chunk.toString()}`.slice(-PROCESS_OUTPUT_LIMIT);\n}\n\nfunction defaultRunProcess(\n command: string,\n args: string[],\n): Promise<ProcessResult> {\n return new Promise((resolve) => {\n const child = spawn(command, args, {\n shell: false,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.on(\"data\", (chunk: Buffer) => {\n stdout = appendBounded(stdout, chunk);\n });\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderr = appendBounded(stderr, chunk);\n });\n child.on(\"error\", (error) => {\n resolve({\n exitCode: 1,\n stdout,\n stderr: appendBounded(stderr, error.message),\n });\n });\n child.on(\"close\", (exitCode) => {\n resolve({ exitCode: exitCode ?? 1, stdout, stderr });\n });\n });\n}\n\nfunction resolveNpxCliPath(\n env: Record<string, string | undefined>,\n nodeExecutable: string,\n): string | undefined {\n const executableDirectory = dirname(nodeExecutable);\n const candidates = [\n ...(env.npm_execpath\n ? [join(dirname(env.npm_execpath), \"npx-cli.js\")]\n : []),\n join(executableDirectory, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\"),\n join(\n executableDirectory,\n \"..\",\n \"lib\",\n \"node_modules\",\n \"npm\",\n \"bin\",\n \"npx-cli.js\",\n ),\n ];\n return candidates.find((candidate) => existsSync(candidate));\n}\n\nfunction npxProcessInvocation(\n processArgs: string[],\n dependencies: CliDependencies,\n env: Record<string, string | undefined>,\n): { executable: string; arguments: string[] } {\n if ((dependencies.platform ?? process.platform) !== \"win32\") {\n return { executable: \"npx\", arguments: processArgs };\n }\n\n const nodeExecutable = dependencies.nodeExecutable ?? process.execPath;\n const npxCliPath =\n dependencies.npxCliPath ?? resolveNpxCliPath(env, nodeExecutable);\n if (!npxCliPath) {\n throw new CliError(\n EXIT_INTERNAL,\n \"NPX_NOT_FOUND\",\n \"Could not find the npm npx program. Install npm, then run the command again.\",\n );\n }\n return {\n executable: nodeExecutable,\n arguments: [npxCliPath, ...processArgs],\n };\n}\n\nfunction rejectUnsafeCredentialArgument(args: string[]): void {\n if (args.some((arg) => arg === \"--api-key\" || arg.startsWith(\"--api-key=\"))) {\n throw new CliError(\n EXIT_USAGE,\n \"UNSAFE_CREDENTIAL_ARGUMENT\",\n \"API keys are accepted only through WEFT_API_KEY or --api-key-stdin\",\n );\n }\n}\n\nfunction requestedHelp(args: string[]): Command | \"all\" | undefined {\n const isHelp = (value: string) => value === \"--help\" || value === \"-h\";\n if (args.length === 1 && isHelp(args[0])) return \"all\";\n if (\n args.length === 2 &&\n COMMANDS.includes(args[0] as Command) &&\n isHelp(args[1])\n ) {\n return args[0] as Command;\n }\n return undefined;\n}\n\nfunction helpData(command: Command | \"all\") {\n if (command !== \"all\") {\n return {\n command,\n ...COMMAND_HELP[command],\n global_options: GLOBAL_OPTIONS,\n };\n }\n return {\n usage: \"weft <command> [options]\",\n commands: COMMANDS.map((name) => ({ name, ...COMMAND_HELP[name] })),\n global_options: GLOBAL_OPTIONS,\n authentication: [\"WEFT_API_KEY\", \"--api-key-stdin\"],\n exit_codes: { success: 0, usage: 2, auth: 3, api: 4, internal: 5 },\n };\n}\n\nfunction parseArgs(args: string[]): ParsedArgs {\n let command: Command | undefined;\n let apiKeyStdin = false;\n let baseUrl: string | undefined;\n const positionals: string[] = [];\n const options = new Map<string, string | true | string[]>();\n\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === \"--api-key-stdin\") {\n apiKeyStdin = true;\n } else if (arg === \"--base-url\") {\n [baseUrl, index] = takeValue(args, index, arg);\n } else if (arg === \"--global\" || arg === \"--raw\") {\n options.set(arg.slice(2), true);\n } else if (arg.startsWith(\"--\")) {\n const [value, nextIndex] = takeValue(args, index, arg);\n const name = arg.slice(2);\n if (name === \"header\") {\n const previous = options.get(name);\n if (typeof previous === \"string\") {\n options.set(name, [previous, value]);\n } else if (Array.isArray(previous)) {\n previous.push(value);\n } else {\n options.set(name, value);\n }\n } else {\n options.set(name, value);\n }\n index = nextIndex;\n } else if (!command) {\n if (!COMMANDS.includes(arg as Command)) {\n throw new CliError(\n EXIT_USAGE,\n \"UNKNOWN_COMMAND\",\n `Unknown command: ${arg}`,\n );\n }\n command = arg as Command;\n } else {\n positionals.push(arg);\n }\n }\n\n if (!command) {\n throw new CliError(\n EXIT_USAGE,\n \"COMMAND_REQUIRED\",\n \"Command required: bootstrap, auth, me, balance, search, fetch, or purchases\",\n );\n }\n\n return { command, apiKeyStdin, baseUrl, positionals, options };\n}\n\nfunction positiveInteger(\n value: string | true | string[] | undefined,\n option: string,\n maximum?: number,\n): number | undefined {\n if (value == null) return undefined;\n if (typeof value !== \"string\") {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n `${option} must be a positive integer`,\n );\n }\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n `${option} must be a positive integer`,\n );\n }\n if (maximum != null && parsed > maximum) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n `${option} must be at most ${maximum}`,\n );\n }\n return parsed;\n}\n\nfunction requiredOption(\n options: Map<string, string | true | string[]>,\n name: string,\n): string {\n const value = options.get(name);\n if (typeof value !== \"string\" || !value.trim()) {\n throw new CliError(EXIT_USAGE, \"MISSING_ARGUMENT\", `--${name} is required`);\n }\n return value;\n}\n\nfunction fetchHeaders(\n raw: string | true | string[] | undefined,\n hasJsonBody: boolean,\n): PaidFetchRequest[\"headers\"] {\n const values =\n typeof raw === \"string\" ? [raw] : Array.isArray(raw) ? raw : [];\n const headers: Record<string, string> = {};\n for (const rawHeader of values) {\n const colon = rawHeader.indexOf(\":\");\n if (colon <= 0) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"--header must be Name:Value\",\n );\n }\n headers[rawHeader.slice(0, colon).trim()] = rawHeader\n .slice(colon + 1)\n .trim();\n }\n if (\n hasJsonBody &&\n !Object.keys(headers).some((name) => name.toLowerCase() === \"content-type\")\n ) {\n headers[\"content-type\"] = \"application/json\";\n }\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nfunction baseApiUrl(\n baseUrl: string | undefined,\n env: Record<string, string | undefined>,\n): string {\n const raw = baseUrl ?? env.WEFT_BASE_URL ?? WEFT_API_BASE;\n return raw.endsWith(\"/\") ? raw.slice(0, -1) : raw;\n}\n\nfunction resolveApiKeyFromStored(\n credentials?: StoredCredentials,\n): string | undefined {\n if (!credentials) return undefined;\n if (\n \"access_token\" in credentials &&\n typeof credentials.access_token === \"string\" &&\n credentials.access_token.trim()\n ) {\n return credentials.access_token;\n }\n if (\n \"temporary_api_key\" in credentials &&\n typeof credentials.temporary_api_key === \"string\" &&\n credentials.temporary_api_key.trim()\n ) {\n return credentials.temporary_api_key;\n }\n return undefined;\n}\n\nfunction isOAuthCredentials(\n credentials: StoredCredentials | undefined,\n): credentials is OAuthCredentials {\n return Boolean(\n credentials && \"type\" in credentials && credentials.type === \"oauth\",\n );\n}\n\nfunction isLegacyBootstrapCredentials(\n credentials: StoredCredentials | undefined,\n): credentials is LegacyBootstrapCredentials {\n return Boolean(\n credentials && \"type\" in credentials && credentials.type === \"bootstrap\",\n );\n}\n\nfunction oauthNeedsRefresh(credentials: OAuthCredentials): boolean {\n const expiry = Date.parse(credentials.expiry);\n return (\n !Number.isFinite(expiry) || expiry <= Date.now() + OAUTH_REFRESH_SKEW_MS\n );\n}\n\nasync function refreshOAuthCredentials(\n fetchApi: typeof fetch,\n env: Record<string, string | undefined>,\n stored: OAuthCredentials,\n): Promise<OAuthCredentials> {\n const token = await requestJson<OAuthTokenResponse>(\n fetchApi,\n `${stored.base_url}/oauth/token`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: stored.refresh_token,\n client_id: stored.client_id,\n }).toString(),\n },\n true,\n );\n const refreshed: OAuthCredentials = {\n ...stored,\n access_token: token.access_token,\n refresh_token: token.refresh_token,\n token_type: token.token_type,\n scope: token.scope,\n expiry: new Date(Date.now() + token.expires_in * 1000).toISOString(),\n };\n await writeStoredCredentialsWhileLocked(env, refreshed);\n return refreshed;\n}\n\nfunction noSecretFields(data: object): Record<string, unknown> {\n return {\n ...data,\n temporary_api_key: undefined,\n access_token: undefined,\n refresh_token: undefined,\n client_secret: undefined,\n };\n}\n\nasync function requestJson<T>(\n fetchApi: typeof fetch,\n url: string,\n init: RequestInit,\n redactError = false,\n): Promise<T> {\n const response = await fetchApi(url, init);\n if (!response.ok) {\n if (redactError) {\n throw new CliError(\n response.status === 401 || response.status === 403\n ? EXIT_AUTH\n : response.status >= 500\n ? EXIT_INTERNAL\n : EXIT_API,\n \"OAUTH_TOKEN_ERROR\",\n `OAuth token request failed with HTTP ${response.status}`,\n );\n }\n throw new ResponseError(response);\n }\n\n return (await response.json()) as T;\n}\n\nfunction withCredentials(\n headers: Record<string, string>,\n apiKey: string,\n): Record<string, string> {\n return {\n ...headers,\n authorization: `Bearer ${apiKey}`,\n };\n}\n\nfunction ensureOnly(\n options: Map<string, string | true | string[]>,\n allowed: string[],\n): void {\n for (const name of options.keys()) {\n if (!allowed.includes(name)) {\n throw new CliError(\n EXIT_USAGE,\n \"UNKNOWN_OPTION\",\n `Unknown option: --${name}`,\n );\n }\n }\n}\n\nasync function responseDetails(error: ResponseError): Promise<unknown> {\n try {\n return await error.response.json();\n } catch {\n return undefined;\n }\n}\n\nasync function normalizeError(error: unknown): Promise<CliError> {\n if (error instanceof CliError) return error;\n if (error instanceof WeftError) {\n // status 0 is a transport failure with no API response; it exits like an\n // internal failure, not an API rejection.\n const exitCode =\n error.status === 401 || error.status === 403\n ? EXIT_AUTH\n : error.status >= 500 || error.status === 0\n ? EXIT_INTERNAL\n : EXIT_API;\n return new CliError(exitCode, error.code, error.message, error.details);\n }\n if (error instanceof ResponseError) {\n const details = await responseDetails(error);\n const body = details as\n | {\n error?: { code?: string; message?: string } | string;\n error_description?: string;\n }\n | undefined;\n const nested = typeof body?.error === \"object\" ? body.error : undefined;\n const code =\n nested?.code ??\n (typeof body?.error === \"string\"\n ? body.error\n : `HTTP_${error.response.status}`);\n const message =\n nested?.message ??\n body?.error_description ??\n `Weft API returned HTTP ${error.response.status}`;\n const exitCode =\n error.response.status === 401 || error.response.status === 403\n ? EXIT_AUTH\n : error.response.status >= 500\n ? EXIT_INTERNAL\n : EXIT_API;\n return new CliError(exitCode, code, message, details);\n }\n const message = error instanceof Error ? error.message : String(error);\n return new CliError(EXIT_INTERNAL, \"INTERNAL_ERROR\", message);\n}\n\nasync function defaultReadStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nasync function defaultWriteOut(value: string): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n // The write callback reports failure before the stream emits its error.\n // Keep the one-shot listener until that event to prevent an uncaught EPIPE.\n const onError = (error: Error) => reject(error);\n process.stdout.once(\"error\", onError);\n process.stdout.write(value, (error) => {\n if (error) {\n reject(error);\n } else {\n process.stdout.removeListener(\"error\", onError);\n resolve();\n }\n });\n });\n}\n\nexport async function runCli(\n args: string[],\n dependencies: CliDependencies = {},\n): Promise<number> {\n const outputWriter = dependencies.writeOut ?? defaultWriteOut;\n const writeErr =\n dependencies.writeErr ?? ((value) => process.stderr.write(value));\n let command = \"unknown\";\n let idempotencyKey: string | undefined;\n let schemaVersion = \"1\";\n let meta: Record<string, unknown> | undefined;\n let deliveryReceipt: Record<string, unknown> | undefined;\n const fetchApi = dependencies.fetchApi ?? fetch;\n const writeOut = async (value: string) => {\n try {\n await outputWriter(value);\n } catch {\n throw new CliError(\n EXIT_INTERNAL,\n command === \"fetch\" ? \"RESULT_OUTPUT_FAILED\" : \"OUTPUT_FAILED\",\n \"Cannot write stdout. Use the saved result paths below if present. Otherwise keep this receipt and retry the same fetch with --idempotency-key and the same key.\",\n deliveryReceipt === undefined\n ? undefined\n : { receipt: deliveryReceipt },\n );\n }\n };\n\n try {\n rejectUnsafeCredentialArgument(args);\n const help = requestedHelp(args);\n if (help !== undefined) {\n command = \"help\";\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: helpData(help),\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n const parsed = parseArgs(args);\n command = parsed.command;\n const env = dependencies.env ?? process.env;\n const baseUrl = baseApiUrl(parsed.baseUrl, env);\n\n if (parsed.command === \"skill\") {\n if (\n parsed.positionals[0] !== \"install\" ||\n parsed.positionals.length > 2\n ) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"skill requires 'install' and accepts at most one Skill name\",\n );\n }\n\n const skillName = parsed.positionals[1];\n if (skillName) {\n ensureOnly(parsed.options, [\"agent\", \"global\"]);\n const agent = requiredOption(parsed.options, \"agent\");\n if (!SKILL_NAME_PATTERN.test(skillName)) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"Skill name must contain only lowercase letters, numbers, and single hyphens\",\n );\n }\n if (CORE_SKILL_NAMES.has(skillName)) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n `Use 'weft skill install' without a name to install the core ${skillName} Skill`,\n );\n }\n if (!SKILL_NAME_PATTERN.test(agent)) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"Agent name must contain only lowercase letters, numbers, and single hyphens\",\n );\n }\n\n const processArgs = [\n \"--yes\",\n \"skills\",\n \"add\",\n \"weftlabs/skills\",\n \"--skill\",\n skillName,\n \"--agent\",\n agent,\n \"--yes\",\n ...(parsed.options.get(\"global\") === true ? [\"--global\"] : []),\n ];\n const invocation = npxProcessInvocation(processArgs, dependencies, env);\n const result = await (dependencies.runProcess ?? defaultRunProcess)(\n invocation.executable,\n invocation.arguments,\n );\n if (result.exitCode !== 0) {\n const remediation = `npx ${processArgs.join(\" \")}`;\n throw new CliError(\n EXIT_INTERNAL,\n \"SKILL_INSTALL_FAILED\",\n `Could not install ${skillName}. Run '${remediation}' directly for more detail.`,\n {\n executable: invocation.executable,\n arguments: invocation.arguments,\n exit_code: result.exitCode,\n stderr: result.stderr,\n },\n );\n }\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: {\n status: \"installed\",\n skill: skillName,\n agent,\n scope:\n parsed.options.get(\"global\") === true ? \"global\" : \"project\",\n },\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n ensureOnly(parsed.options, []);\n const installSkill = await loadSkillInstaller();\n const result = await installSkill({ force: true });\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: {\n status: result.status,\n installed: result.installed,\n hosts: result.hosts,\n ...(result.reason === undefined ? {} : { reason: result.reason }),\n ...(result.warnings.length === 0\n ? {}\n : { warnings: result.warnings }),\n },\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n await installSkillInBackground();\n\n if (parsed.command === \"bootstrap\") {\n ensureOnly(parsed.options, [\"email\", \"agent-name\", \"reason\"]);\n if (parsed.positionals.length !== 0) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"bootstrap does not accept positional arguments\",\n );\n }\n const email = requiredOption(parsed.options, \"email\");\n const agentName = requiredOption(parsed.options, \"agent-name\");\n const reason = requiredOption(parsed.options, \"reason\");\n\n const bootstrap = await requestJson<BootstrapCreateResponse>(\n fetchApi,\n `${baseUrl}/api/v1/account_bootstraps`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n email,\n agent_name: agentName,\n host_name: OAUTH_HOST_NAME,\n reason,\n }),\n },\n );\n\n const stored: BootstrapCredentials = {\n ...bootstrap.data,\n base_url: baseUrl,\n };\n\n await writeStoredCredentials(env, stored);\n\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: noSecretFields(stored),\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n if (parsed.command === \"auth\") {\n ensureOnly(parsed.options, []);\n if (\n parsed.positionals.length !== 1 ||\n parsed.positionals[0] !== \"status\"\n ) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"auth requires 'status'\",\n );\n }\n\n const stored = await readStoredCredentials(env);\n if (isOAuthCredentials(stored)) {\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: {\n status: \"consumed\",\n authentication: \"oauth\",\n scope: stored.scope,\n },\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n if (isLegacyBootstrapCredentials(stored)) {\n const status = await requestJson<BootstrapStatus>(\n fetchApi,\n `${stored.base_url}/api/v1/account_bootstraps/${stored.bootstrap_id}`,\n {\n method: \"GET\",\n headers: withCredentials({}, stored.temporary_api_key),\n },\n );\n if (\n status.data.status !== \"claimed\" &&\n status.data.status !== \"consumed\"\n ) {\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: { status: status.data.status },\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n const token = await requestJson<OAuthTokenResponse>(\n fetchApi,\n `${stored.base_url}/oauth/token`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/x-www-form-urlencoded\",\n },\n body: new URLSearchParams({\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n device_code: stored.device_code,\n client_id: stored.client_id,\n name: \"Weft CLI\",\n }).toString(),\n },\n true,\n );\n const oauth: OAuthCredentials = {\n version: 1,\n type: \"oauth\",\n base_url: stored.base_url,\n client_id: stored.client_id,\n access_token: token.access_token,\n refresh_token: token.refresh_token,\n token_type: token.token_type,\n scope: token.scope,\n expiry: new Date(Date.now() + token.expires_in * 1000).toISOString(),\n };\n const active = await withCredentialsLock(env, async () => {\n const current = await readStoredCredentials(env);\n if (isOAuthCredentials(current)) return current;\n if (\n !isLegacyBootstrapCredentials(current) ||\n JSON.stringify(current) !== JSON.stringify(stored)\n ) {\n throw new CliError(\n EXIT_AUTH,\n \"CREDENTIALS_CHANGED\",\n \"Stored credentials changed; rerun auth status\",\n );\n }\n await writeStoredCredentialsWhileLocked(env, oauth);\n return oauth;\n });\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: {\n status: \"consumed\",\n authentication: \"oauth\",\n scope: active.scope,\n },\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n if (!stored) {\n throw new CliError(\n EXIT_AUTH,\n \"BOOTSTRAP_REQUIRED\",\n \"Run weft bootstrap before auth status\",\n );\n }\n\n const status = await requestJson<BootstrapStatus>(\n fetchApi,\n `${stored.base_url}/api/v1/account_bootstraps/${stored.id}`,\n {\n method: \"GET\",\n headers: withCredentials({}, stored.temporary_api_key),\n },\n );\n\n const merged: BootstrapCredentials = {\n base_url: stored.base_url,\n id: status.data.id ?? stored.id,\n status: status.data.status,\n capabilities: status.data.capabilities ?? stored.capabilities,\n expires_at:\n status.data.expires_at === undefined\n ? stored.expires_at\n : status.data.expires_at,\n approval: status.data.approval ?? stored.approval,\n temporary_api_key: stored.temporary_api_key,\n };\n const active = await withCredentialsLock(env, async () => {\n const current = await readStoredCredentials(env);\n if (JSON.stringify(current) !== JSON.stringify(stored)) {\n throw new CliError(\n EXIT_AUTH,\n \"CREDENTIALS_CHANGED\",\n \"Stored credentials changed; rerun auth status\",\n );\n }\n await writeStoredCredentialsWhileLocked(env, merged);\n return merged;\n });\n\n await writeOut(\n `${JSON.stringify({\n schema_version: \"1\",\n ok: true,\n command,\n data: noSecretFields(active),\n })}\\n`,\n );\n return EXIT_SUCCESS;\n }\n\n const rawKey = parsed.apiKeyStdin\n ? await (dependencies.readStdin ?? defaultReadStdin)()\n : env.WEFT_API_KEY;\n let apiKey = rawKey?.trim();\n let authenticatedBaseUrl = baseUrl;\n if (parsed.apiKeyStdin && !apiKey) {\n throw new CliError(\n EXIT_AUTH,\n \"API_KEY_REQUIRED\",\n \"--api-key-stdin requires a non-empty API key\",\n );\n }\n if (!apiKey && !parsed.apiKeyStdin) {\n let stored = await readStoredCredentials(env);\n if (isOAuthCredentials(stored) && oauthNeedsRefresh(stored)) {\n stored = await withCredentialsLock(env, async () => {\n const current = await readStoredCredentials(env);\n if (isOAuthCredentials(current) && oauthNeedsRefresh(current)) {\n return refreshOAuthCredentials(fetchApi, env, current);\n }\n return current;\n });\n }\n apiKey = resolveApiKeyFromStored(stored);\n if (stored) {\n authenticatedBaseUrl = stored.base_url;\n }\n }\n\n if (!apiKey) {\n throw new CliError(\n EXIT_AUTH,\n \"API_KEY_REQUIRED\",\n \"Set WEFT_API_KEY, pass --api-key-stdin, or store credentials\",\n );\n }\n\n const client = new WeftClient({\n apiKey,\n baseUrl: authenticatedBaseUrl,\n fetchApi,\n });\n\n let data: unknown;\n if (parsed.command === \"me\") {\n ensureOnly(parsed.options, []);\n data = await client.me();\n } else if (parsed.command === \"balance\") {\n ensureOnly(parsed.options, []);\n data = await client.balance();\n } else if (parsed.command === \"search\") {\n ensureOnly(parsed.options, [\"max-results\"]);\n if (parsed.positionals.length !== 1) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"search requires exactly one query\",\n );\n }\n data = await client.search({\n query: parsed.positionals[0],\n maxResults: positiveInteger(\n parsed.options.get(\"max-results\"),\n \"--max-results\",\n 50,\n ),\n });\n } else if (parsed.command === \"fetch\") {\n ensureOnly(parsed.options, [\n \"max-cost-usd\",\n \"method\",\n \"body\",\n \"header\",\n \"idempotency-key\",\n \"raw\",\n ]);\n const raw = parsed.options.has(\"raw\");\n schemaVersion = raw ? \"1\" : \"2\";\n if (parsed.positionals.length !== 1) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"fetch requires exactly one URL\",\n );\n }\n const maxCostUsd = requiredOption(parsed.options, \"max-cost-usd\");\n if (!/^\\d+(?:\\.\\d+)?$/.test(maxCostUsd)) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"--max-cost-usd must be a non-negative decimal\",\n );\n }\n const method = parsed.options.get(\"method\");\n const rawBody = parsed.options.get(\"body\");\n let body: PaidFetchRequest[\"body\"];\n if (typeof rawBody === \"string\") {\n try {\n JSON.parse(rawBody);\n } catch {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"--body must be JSON\",\n );\n }\n body = rawBody;\n }\n const headers = fetchHeaders(\n parsed.options.get(\"header\"),\n typeof rawBody === \"string\",\n );\n const request: PaidFetchRequest = {\n url: parsed.positionals[0],\n maxCostUsd,\n method:\n typeof method === \"string\"\n ? (method.toUpperCase() as PaidFetchRequest[\"method\"])\n : undefined,\n body,\n headers,\n };\n const explicitKey = parsed.options.get(\"idempotency-key\");\n idempotencyKey =\n typeof explicitKey === \"string\"\n ? explicitKey\n : (dependencies.generateIdempotencyKey ?? randomUUID)();\n let resultDirectory: string | undefined;\n if (!raw) {\n try {\n resultDirectory = await reserveResultDirectory(env);\n } catch {\n throw new CliError(\n EXIT_INTERNAL,\n \"RESULT_STORAGE_UNAVAILABLE\",\n \"Cannot reserve local result storage. Set WEFT_RESULTS_DIR to a directory you own that is writable only by you, with no symlink at that path, then retry. No fetch was sent.\",\n );\n }\n }\n const response = await client.fetch(request, { idempotencyKey });\n meta = { idempotency_key: idempotencyKey };\n data = response;\n const { bodyBase64, ...receipt } = response;\n deliveryReceipt = receipt;\n if (resultDirectory) {\n const savedPath = join(resultDirectory, \"body\");\n const receiptPath = join(resultDirectory, \"receipt.json\");\n const bytes =\n typeof bodyBase64 === \"string\"\n ? Buffer.from(bodyBase64, \"base64\")\n : undefined;\n if (!bytes || bytes.toString(\"base64\") !== bodyBase64) {\n throw new CliError(\n EXIT_INTERNAL,\n \"RESULT_DECODE_FAILED\",\n \"Fetch returned invalid Base64. No body was saved. Keep this receipt and retry the same request with --idempotency-key and the same key; if it persists, report the artifact ID to support.\",\n { receipt, file_complete: false },\n );\n }\n try {\n meta = {\n ...meta,\n saved_path: savedPath,\n receipt_path: receiptPath,\n byte_count: bytes.length,\n };\n await writeResultFile(\n receiptPath,\n `${JSON.stringify({ schema_version: \"2\", meta, data: receipt })}\\n`,\n );\n await writeResultFile(savedPath, bytes);\n data = { ...receipt, ...readableBody(bytes, response.headers) };\n } catch {\n throw new CliError(\n EXIT_INTERNAL,\n \"RESULT_STORAGE_FAILED\",\n \"Fetch returned, but local result delivery failed. Keep this receipt. Check local storage, then retry the same request with --idempotency-key and the key below. Do not use a new key.\",\n {\n receipt,\n saved_path: savedPath,\n receipt_path: receiptPath,\n file_complete: false,\n },\n );\n }\n }\n } else {\n ensureOnly(parsed.options, [\"page\", \"per-page\"]);\n if (parsed.positionals.length > 1) {\n throw new CliError(\n EXIT_USAGE,\n \"INVALID_ARGUMENT\",\n \"purchases accepts at most one purchase ID\",\n );\n }\n data = parsed.positionals[0]\n ? await client.purchase(\n positiveInteger(parsed.positionals[0], \"purchase ID\")!,\n )\n : await client.purchases({\n page: positiveInteger(parsed.options.get(\"page\"), \"--page\"),\n perPage: positiveInteger(\n parsed.options.get(\"per-page\"),\n \"--per-page\",\n 100,\n ),\n });\n }\n\n await writeOut(\n `${JSON.stringify({\n schema_version: schemaVersion,\n ok: true,\n command,\n ...(meta === undefined ? {} : { meta }),\n data,\n })}\\n`,\n );\n return EXIT_SUCCESS;\n } catch (error) {\n const normalized = await normalizeError(error);\n writeErr(\n `${JSON.stringify({\n schema_version: schemaVersion,\n ok: false,\n command,\n ...(idempotencyKey === undefined\n ? {}\n : { meta: { ...meta, idempotency_key: idempotencyKey } }),\n error: {\n code: normalized.code,\n message: normalized.message,\n ...(normalized.details === undefined\n ? {}\n : { details: normalized.details }),\n },\n })}\\n`,\n );\n return normalized.exitCode;\n }\n}\n","import { chmod, lstat, mkdir, mkdtemp, open, realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\nexport async function reserveResultDirectory(\n env: Record<string, string | undefined>,\n): Promise<string> {\n const root = resolve(\n env.WEFT_RESULTS_DIR ||\n join(env.HOME || env.USERPROFILE || homedir(), \".weft-results\"),\n );\n await mkdir(root, { recursive: true, mode: 0o700 });\n const stat = await lstat(root);\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new Error(\n \"The result storage root must be a directory, not a symlink\",\n );\n }\n if (\n process.platform !== \"win32\" &&\n ((stat.mode & 0o022) !== 0 || stat.uid !== process.getuid?.())\n ) {\n throw new Error(\n \"The result storage root must be owned by this user and not writable by others\",\n );\n }\n // A private child keeps payloads protected without changing an existing parent.\n const directory = await mkdtemp(join(await realpath(root), \"result-\"));\n await chmod(directory, 0o700);\n return directory;\n}\n\nexport async function writeResultFile(\n path: string,\n contents: string | Buffer,\n): Promise<void> {\n const file = await open(path, \"wx\", 0o600);\n try {\n await file.chmod(0o600);\n await file.writeFile(contents);\n await file.sync();\n } finally {\n await file.close();\n }\n}\n\nexport function readableBody(\n bytes: Buffer,\n headers: Record<string, string>,\n): {\n media_type: string | null;\n body_encoding: \"utf-8\" | \"file\";\n body?: string;\n} {\n const header = (name: string) =>\n Object.entries(headers).find(([key]) => key.toLowerCase() === name)?.[1];\n const contentType = header(\"content-type\")?.toLowerCase() ?? \"\";\n const mediaType = contentType.split(\";\", 1)[0].trim();\n const charset = /(?:^|;)\\s*charset\\s*=\\s*\"?([^;\"\\s]+)/.exec(contentType)?.[1];\n const encoding = header(\"content-encoding\")?.trim().toLowerCase();\n const file = {\n media_type: mediaType || null,\n body_encoding: \"file\" as const,\n };\n const textual =\n mediaType.startsWith(\"text/\") ||\n /^application\\/(?:json|xml|javascript|x-ndjson|x-www-form-urlencoded|[^;]+\\+(?:json|xml))$/.test(\n mediaType,\n );\n if (\n (encoding && encoding !== \"identity\") ||\n (charset && ![\"utf-8\", \"utf8\", \"us-ascii\"].includes(charset)) ||\n (!textual && !(bytes.length === 0 && !mediaType))\n )\n return file;\n try {\n // Keep a UTF-8 BOM and JSON spelling exactly as delivered.\n const body = new TextDecoder(\"utf-8\", {\n fatal: true,\n ignoreBOM: true,\n }).decode(bytes);\n return { media_type: mediaType || null, body_encoding: \"utf-8\", body };\n } catch {\n return file;\n }\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;AACxB,SAAS,cAAc,aAAa;AAEpC,IAAM,wBAAwB;AAC9B,IAAM,uBAAuB;AAC7B,IAAM,gBAAgB;AACtB,IAAM,kBAAkB;AA4CxB,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAEA,SAAS,uBACP,OACkC;AAClC,MACE,OAAO,MAAM,aAAa,YAC1B,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,WAAW,YACxB,MAAM,QAAQ,MAAM,YAAY,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,OAAO,QAAQ,IAAI,UAAU;AAAA,UAC7B;AAAA,UACA;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACP;AAEA,UAAM;AAAA,MACJ,GAAG,KAAK,UAAU;AAAA,QAChB,gBAAgB;AAAA,QAChB,IAAI;AAAA,QACJ;AAAA,QACA,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,KAAK;AAAA,QACrC;AAAA,MACF,CAAC,CAAC;AAAA;AAAA,IACJ;AACA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,UAAM,aAAa,MAAM,eAAe,KAAK;AAC7C;AAAA,MACE,GAAG,KAAK,UAAU;AAAA,QAChB,gBAAgB;AAAA,QAChB,IAAI;AAAA,QACJ;AAAA,QACA,GAAI,mBAAmB,SACnB,CAAC,IACD,EAAE,MAAM,EAAE,GAAG,MAAM,iBAAiB,eAAe,EAAE;AAAA,QACzD,OAAO;AAAA,UACL,MAAM,WAAW;AAAA,UACjB,SAAS,WAAW;AAAA,UACpB,GAAI,WAAW,YAAY,SACvB,CAAC,IACD,EAAE,SAAS,WAAW,QAAQ;AAAA,QACpC;AAAA,MACF,CAAC,CAAC;AAAA;AAAA,IACJ;AACA,WAAO,WAAW;AAAA,EACpB;AACF;","names":["randomUUID","dirname","join","chmod","mkdir","open","resolve","dirname","join","isOAuthCredentials","isLegacyBootstrapCredentials","message","result","status","active","randomUUID"]}
@@ -0,0 +1,97 @@
1
+ # CLI commands
2
+
3
+ | CLI command | API operation |
4
+ | --- | --- |
5
+ | `weft bootstrap` | `createAccountBootstrap` |
6
+ | `weft auth status` | `getAccountBootstrap` |
7
+ | `weft me` | `getMe` |
8
+ | `weft balance` | `getBalance` |
9
+ | `weft search QUERY` | `search` |
10
+ | `weft fetch URL --max-cost-usd USD` | `fetch` |
11
+ | `weft purchases` | `listPurchases` |
12
+ | `weft purchases ID` | `getPurchase` |
13
+
14
+ ## CLI contract
15
+
16
+ Authentication precedence is explicit `--api-key-stdin`, then `WEFT_API_KEY`,
17
+ then the protected local bootstrap or legacy OAuth credential store. A
18
+ `--api-key VALUE` argument is rejected so credentials do not leak into shell
19
+ history or process listings. Legacy stored OAuth credentials refresh before expiry.
20
+ The API origin defaults to `https://weft.network` and can be changed with
21
+ `WEFT_BASE_URL` or `--base-url`; stored credentials retain their API origin.
22
+
23
+ Every command prints one versioned JSON object. Most successes use
24
+ `{"schema_version":"1","ok":true,"command":"…","data":…}` on stdout.
25
+ Errors use
26
+ `{"schema_version":"1","ok":false,"command":"…","error":{"code":"…","message":"…","details":…}}`
27
+ on stderr. Fetch success also includes
28
+ `"meta":{"idempotency_key":"…"}` so an uncertain call can be retried with
29
+ the exact same key. Default `weft fetch` uses schema version `"2"` for results
30
+ and for errors after fetch option validation starts. Other commands and
31
+ `weft fetch --raw` retain schema version `"1"`.
32
+
33
+ Default fetch saves exact response bytes before stdout. Its `meta` object
34
+ precedes `data` and includes `saved_path`, `receipt_path`, `byte_count`, and
35
+ `idempotency_key`. Both paths are absolute. `data` retains the SDK's camelCase
36
+ receipt fields but replaces `bodyBase64` with `body_encoding`, `media_type`,
37
+ and, for valid UTF-8 text or JSON, the complete original `body` string. JSON
38
+ body values are not parsed or reformatted. Binary, compressed, and invalid
39
+ UTF-8 responses use `body_encoding: "file"` and omit `body`. Fetch with `--raw`
40
+ retains the original SDK result with `bodyBase64` and does not write files.
41
+
42
+ Local files use private per-result directories and are not deleted automatically.
43
+ `RESULT_STORAGE_UNAVAILABLE` means no fetch was sent. `RESULT_STORAGE_FAILED`
44
+ means the response arrived but local delivery failed; its error details keep
45
+ the body-free receipt and mark `file_complete: false`, while `meta` keeps the
46
+ retry key. Both use exit code `5`. See [CLI result storage](../README.md#fetch-results)
47
+ for paths, permissions, cleanup, and retry instructions.
48
+ Invalid transport Base64 returns `RESULT_DECODE_FAILED`, with the receipt and
49
+ retry key. A failed stdout write returns `RESULT_OUTPUT_FAILED`, with the
50
+ receipt and any saved paths. Both use exit code `5`; reading a saved local file
51
+ requires no fetch or payment.
52
+
53
+ `weft --help` returns every command, global option, authentication method, and
54
+ exit code as JSON. `weft <command> --help` returns command-specific usage and
55
+ options. Help does not require authentication or make a network request.
56
+
57
+ Exit codes are stable:
58
+
59
+ - `0`: success
60
+ - `2`: invalid command, argument, or option
61
+ - `3`: missing authentication or an HTTP `401`/`403`
62
+ - `4`: other HTTP `4xx` API or policy rejection
63
+ - `5`: HTTP `5xx`, network, runtime, or unexpected internal failure
64
+
65
+ `weft fetch` always requires `--max-cost-usd`. It accepts
66
+ `--idempotency-key`; when omitted, the CLI generates a UUID for the
67
+ `Idempotency-Key` header.
68
+
69
+ `--max-results` is validated as `1..50`, and `--per-page` as `1..100`,
70
+ before a network request is made.
71
+
72
+ ## Agent bootstrap
73
+
74
+ The package implements the bootstrap lifecycle. Read `weft --help` before
75
+ scripting it so the installed CLI remains the source of command syntax.
76
+
77
+ | Command | Purpose |
78
+ | --- | --- |
79
+ | `weft bootstrap --email EMAIL --agent-name NAME --reason TEXT` | Create a temporary bootstrap, email the human a claim link, store the `wbt_` credential in a mode-0600 local file |
80
+ | `weft auth status` | Report the bootstrap lifecycle state; poll at the interval returned by `weft bootstrap` |
81
+
82
+ The `wbt_` credential is secret. Before claim it is temporary for 30 minutes and
83
+ has exactly `search`, `status`, and `cancel`. Human approval promotes the same
84
+ bearer to durable `identity`, `search`, `balance`, `fetch`, `purchases`,
85
+ `status`, and `revoke` capabilities. It remains valid until revoked. Seller,
86
+ organization, API-key administration, dashboard-session, transfer, withdrawal,
87
+ and MCP surfaces always refuse it. Lifecycle states are `pending`, `claimed`,
88
+ `rejected`, `expired`, and `revoked`; the last three are terminal. Claimed
89
+ credentials retain search. Cancellation and revocation are API capabilities; no
90
+ CLI cancel or revoke command is shipped in this version.
91
+
92
+ New bootstrap flows make no OAuth registration or token request. Existing
93
+ stored OAuth credentials remain compatible and refresh before expiry.
94
+
95
+ Ask the human to verify the claim email. Weft applies the one-time signup grant
96
+ after verification; then check the balance. Do not ask for a wallet top-up
97
+ during onboarding.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weftlabs/cli",
3
- "version": "0.26.9",
3
+ "version": "0.29.0",
4
4
  "description": "Command-line client for the Weft buyer runtime",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,6 +11,7 @@
11
11
  "dist",
12
12
  "examples",
13
13
  "README.md",
14
+ "docs/contract.md",
14
15
  "scripts/install-skill.mjs",
15
16
  "scripts/skill-paths.mjs"
16
17
  ],
@@ -25,19 +26,21 @@
25
26
  "homepage": "https://weftlabs.com/x402/cli",
26
27
  "repository": {
27
28
  "type": "git",
28
- "url": "https://github.com/weftlabs/weft-sdk",
29
- "directory": "cli"
29
+ "url": "https://github.com/weftlabs/weft-cli"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/weftlabs/weft-cli/issues"
30
33
  },
31
34
  "dependencies": {
32
- "@weftlabs/sdk": "0.26.9"
35
+ "@weftlabs/sdk": "^0.29.0"
33
36
  },
34
37
  "devDependencies": {
35
- "@types/node": "^26.1.2",
36
- "@typescript-eslint/eslint-plugin": "^8.29.1",
37
- "@typescript-eslint/parser": "^8.29.1",
38
- "eslint": "^10.4.1",
38
+ "@types/node": "^26.6.2",
39
+ "@typescript-eslint/eslint-plugin": "^8.70.1",
40
+ "@typescript-eslint/parser": "^8.70.1",
41
+ "eslint": "^10.11.0",
39
42
  "prettier": "3.9.6",
40
- "tsup": "^8.4.0",
43
+ "tsup": "^8.5.1",
41
44
  "typescript": "^6.0.3",
42
45
  "vitest": "^4.1.11"
43
46
  },
@@ -46,11 +49,11 @@
46
49
  },
47
50
  "scripts": {
48
51
  "build": "tsup",
49
- "pretest": "pnpm --filter @weftlabs/sdk build",
50
- "test": "vitest run",
51
- "pretest:unit": "pnpm --filter @weftlabs/sdk build",
52
- "test:unit": "vitest run",
52
+ "typecheck": "tsc --noEmit",
53
+ "test": "vitest run tests && node --test scripts/publish-npm-archive.test.mjs",
54
+ "test:unit": "vitest run tests && node --test scripts/publish-npm-archive.test.mjs",
55
+ "test:packed": "node scripts/test-packed-artifact.mjs",
53
56
  "lint:check": "eslint",
54
- "format:check": "prettier --check \"src/**/*.ts\" \"tests/**/*.ts\""
57
+ "format:check": "prettier --check \"src/**/*.ts\" \"tests/**/*.ts\" \"scripts/**/*.mjs\""
55
58
  }
56
59
  }
@@ -20,7 +20,7 @@ import {
20
20
  } from "./skill-paths.mjs";
21
21
 
22
22
  const bundledRoot = "../dist/weft-skill/";
23
- const workspaceSkill = new URL("../../skills/weft/SKILL.md", import.meta.url);
23
+ const workspaceSkill = new URL("../skills/weft/SKILL.md", import.meta.url);
24
24
 
25
25
  const sha256 = (value) => createHash("sha256").update(value).digest("hex");
26
26
 
@@ -59,9 +59,7 @@ async function removeLegacySkill(skillsRootRelative, warn) {
59
59
  legacySkill !== undefined &&
60
60
  marker !== JSON.stringify({ sha256: sha256(legacySkill) })
61
61
  ) {
62
- warn(
63
- `Kept modified legacy Skill at ${skillPath}; remove it manually.`,
64
- );
62
+ warn(`Kept modified legacy Skill at ${skillPath}; remove it manually.`);
65
63
  return;
66
64
  }
67
65
  if (legacySkill !== undefined) await unlink(skillPath);
@@ -70,9 +68,7 @@ async function removeLegacySkill(skillsRootRelative, warn) {
70
68
  await rm(join(legacyDirectory, ".weft-cli-backup"), { force: true });
71
69
  await rmdir(legacyDirectory).catch((error) => {
72
70
  if (error.code !== "ENOTEMPTY") throw error;
73
- warn(
74
- `Kept non-empty legacy Skill directory at ${legacyDirectory}.`,
75
- );
71
+ warn(`Kept non-empty legacy Skill directory at ${legacyDirectory}.`);
76
72
  });
77
73
  }
78
74
 
@@ -85,7 +81,13 @@ export async function installSkill({ force = false, silent = false } = {}) {
85
81
  const hosts = [];
86
82
 
87
83
  if (process.env.WEFT_SKIP_SKILL_INSTALL === "1") {
88
- return { status: "skipped", reason: "opt-out", installed: 0, hosts, warnings };
84
+ return {
85
+ status: "skipped",
86
+ reason: "opt-out",
87
+ installed: 0,
88
+ hosts,
89
+ warnings,
90
+ };
89
91
  }
90
92
 
91
93
  if (!force && process.env.WEFT_FORCE_SKILL_INSTALL !== "1") {
@@ -147,9 +149,15 @@ export async function installSkill({ force = false, silent = false } = {}) {
147
149
  const marker = await readIfPresent(markerTarget);
148
150
  if (marker !== undefined) {
149
151
  for (const file of skillFiles) {
150
- await rm(join(dirname(join(directory, file)), `.weft-next-${basename(file)}`), {
151
- force: true,
152
- });
152
+ await rm(
153
+ join(
154
+ dirname(join(directory, file)),
155
+ `.weft-next-${basename(file)}`,
156
+ ),
157
+ {
158
+ force: true,
159
+ },
160
+ );
153
161
  }
154
162
  }
155
163
 
@@ -177,7 +185,8 @@ export async function installSkill({ force = false, silent = false } = {}) {
177
185
  // it. Anything else is user-owned or user-modified and stays.
178
186
  let recorded;
179
187
  try {
180
- recorded = marker === undefined ? undefined : JSON.parse(marker).sha256;
188
+ recorded =
189
+ marker === undefined ? undefined : JSON.parse(marker).sha256;
181
190
  } catch {
182
191
  recorded = undefined;
183
192
  }
@@ -204,7 +213,10 @@ export async function installSkill({ force = false, silent = false } = {}) {
204
213
  for (const file of skillFiles) {
205
214
  const target = join(directory, file);
206
215
  await mkdir(dirname(target), { recursive: true });
207
- const temporary = join(dirname(target), `.weft-next-${basename(file)}`);
216
+ const temporary = join(
217
+ dirname(target),
218
+ `.weft-next-${basename(file)}`,
219
+ );
208
220
  await writeFile(temporary, skill.get(file), {
209
221
  encoding: "utf8",
210
222
  mode: 0o600,
@@ -257,7 +269,7 @@ export async function installSkill({ force = false, silent = false } = {}) {
257
269
 
258
270
  // Still runnable as a script (`node scripts/install-skill.mjs`) for tests and
259
271
  // for anyone repairing an install by hand. Nothing invokes it automatically —
260
- // see cli/README.md for why this is no longer a postinstall hook.
272
+ // see README.md for why this is no longer a postinstall hook.
261
273
  if (
262
274
  process.argv[1] &&
263
275
  import.meta.url === pathToFileURL(process.argv[1]).href