@composable-os/cli 0.0.0-stage → 0.1.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/LICENSE +109 -0
  2. package/README.md +24 -2
  3. package/dist/blocks-DEELKGDC.js +233 -0
  4. package/dist/chunk-2ABSVMGB.js +13 -0
  5. package/dist/chunk-2S7375SC.js +802 -0
  6. package/dist/chunk-5KSXSK7Y.js +47 -0
  7. package/dist/chunk-6UWRT4VM.js +220 -0
  8. package/dist/chunk-E5JLTLRM.js +50 -0
  9. package/dist/chunk-G3ORKXVP.js +1178 -0
  10. package/dist/chunk-HDIOVFAZ.js +544 -0
  11. package/dist/chunk-KGHA67HG.js +765 -0
  12. package/dist/chunk-KOKYDJ7Z.js +1423 -0
  13. package/dist/chunk-KTXGEXTY.js +358 -0
  14. package/dist/chunk-LTQDLCP7.js +16486 -0
  15. package/dist/chunk-MAXLUQKB.js +1287 -0
  16. package/dist/chunk-STJZJIRA.js +11378 -0
  17. package/dist/chunk-X6I2LWB3.js +24319 -0
  18. package/dist/chunk-XDDBLYKW.js +29154 -0
  19. package/dist/chunk-ZRWF6QZS.js +2357 -0
  20. package/dist/cli-BRSACHSG.js +31393 -0
  21. package/dist/cli-DTMGNDXN.js +121 -0
  22. package/dist/cli.js +25 -0
  23. package/dist/client-repo-ZVZ6KW5S.js +55 -0
  24. package/dist/create.js +25 -0
  25. package/dist/fields-64BQJA62.js +48 -0
  26. package/dist/invoke-NHHOLLF6.js +26 -0
  27. package/dist/person-WMWRF2HV.js +58 -0
  28. package/dist/platform/migrations/0001_init.sql +59 -0
  29. package/dist/platform/migrations/0002_users_settings.sql +34 -0
  30. package/dist/platform/migrations/0003_people_organisations.sql +225 -0
  31. package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
  32. package/dist/platform/migrations/0005_views_audit.sql +79 -0
  33. package/dist/platform/migrations/0006_search.sql +223 -0
  34. package/dist/platform/migrations/0007_crm_views.sql +141 -0
  35. package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
  36. package/dist/platform/migrations/0010_approval_queue.sql +90 -0
  37. package/dist/platform/migrations/0011_connected_apps.sql +36 -0
  38. package/dist/platform/migrations/0020_extensions.sql +373 -0
  39. package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
  40. package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
  41. package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
  42. package/dist/platform/migrations/0061_audit_retention.sql +95 -0
  43. package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
  44. package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
  45. package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
  46. package/dist/platform/migrations/0065_storage_stats.sql +13 -0
  47. package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
  48. package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
  49. package/dist/platform/migrations/0100_stage_history.sql +54 -0
  50. package/dist/platform/migrations/0110_integrations.sql +103 -0
  51. package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
  52. package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
  53. package/dist/platform/migrations/0130_automations.sql +113 -0
  54. package/dist/platform/migrations/0131_notifications.sql +29 -0
  55. package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
  56. package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
  57. package/dist/platform/migrations/0160_releases.sql +41 -0
  58. package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
  59. package/dist/platform/migrations/0170_automation_connections.sql +32 -0
  60. package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
  61. package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
  62. package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
  63. package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
  64. package/dist/platform/migrations/0210_daily_digest.sql +33 -0
  65. package/dist/platform/migrations/0220_entitlements.sql +13 -0
  66. package/dist/platform/migrations/0221_support_grants.sql +33 -0
  67. package/dist/platform/migrations/0250_judge.sql +11 -0
  68. package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
  69. package/dist/platform/migrations/0252_judge_usage.sql +14 -0
  70. package/dist/platform/migrations/0255_summary_checks.sql +9 -0
  71. package/dist/platform/migrations/0256_outbound_check.sql +9 -0
  72. package/dist/platform/migrations/0260_ai_usage.sql +20 -0
  73. package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
  74. package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
  75. package/dist/platform/migrations/0320_duplicates.sql +41 -0
  76. package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
  77. package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
  78. package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
  79. package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
  80. package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
  81. package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
  82. package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
  83. package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
  84. package/dist/platform/migrations/0362_voice_usage.sql +17 -0
  85. package/dist/platform/migrations/0365_routines.sql +38 -0
  86. package/dist/platform/migrations/0370_approval_execution.sql +20 -0
  87. package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
  88. package/dist/platform/migrations/0380_rec_views.sql +94 -0
  89. package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
  90. package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
  91. package/dist/platform/migrations/0402_erase_requests.sql +34 -0
  92. package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
  93. package/dist/platform/migrations/0411_device_sessions.sql +33 -0
  94. package/dist/platform/migrations/0420_transition_history.sql +100 -0
  95. package/dist/platform/migrations/0421_orders.sql +134 -0
  96. package/dist/platform/migrations/0422_order_payments.sql +109 -0
  97. package/dist/platform/migrations/0440_capacity.sql +100 -0
  98. package/dist/platform/migrations/0441_capacity_views.sql +40 -0
  99. package/dist/platform/migrations/0450_order_grants.sql +21 -0
  100. package/dist/platform/migrations/0451_pack_roles.sql +18 -0
  101. package/dist/platform/migrations/0460_content.sql +59 -0
  102. package/dist/platform/migrations/0461_media.sql +52 -0
  103. package/dist/platform/migrations/0470_publish_versions.sql +36 -0
  104. package/dist/platform/migrations/0471_permission_grants.sql +18 -0
  105. package/dist/platform/migrations/0490_staff_invites.sql +40 -0
  106. package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
  107. package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
  108. package/dist/platform/migrations/0500_published_media_field.sql +25 -0
  109. package/dist/platform/migrations/0501_import_keys.sql +23 -0
  110. package/dist/platform/migrations/0520_publish_requests.sql +20 -0
  111. package/dist/platform/sdk/automation-check.ts +534 -0
  112. package/dist/platform/sdk/automation.ts +743 -0
  113. package/dist/platform/sdk/behaviour.ts +215 -0
  114. package/dist/platform/sdk/capacity.ts +112 -0
  115. package/dist/platform/sdk/contract.ts +766 -0
  116. package/dist/platform/sdk/document.ts +788 -0
  117. package/dist/platform/sdk/field-types.ts +106 -0
  118. package/dist/platform/sdk/formula/ast.ts +72 -0
  119. package/dist/platform/sdk/formula/compile.ts +454 -0
  120. package/dist/platform/sdk/formula/index.ts +4 -0
  121. package/dist/platform/sdk/formula/parser.ts +417 -0
  122. package/dist/platform/sdk/index.ts +33 -0
  123. package/dist/platform/sdk/manifest.ts +1484 -0
  124. package/dist/platform/sdk/media.ts +46 -0
  125. package/dist/platform/sdk/permissions.ts +60 -0
  126. package/dist/platform/sdk/renamed.ts +63 -0
  127. package/dist/platform/sdk/rich-text-fixture.ts +68 -0
  128. package/dist/platform/sdk/rich-text.ts +173 -0
  129. package/dist/platform/sdk/runtime.ts +410 -0
  130. package/dist/platform/sdk/sellable.ts +396 -0
  131. package/dist/platform/sdk/slug.ts +25 -0
  132. package/dist/platform/sdk/states.ts +162 -0
  133. package/dist/platform/sdk/testing.ts +836 -0
  134. package/dist/products-2H5DR232.js +11 -0
  135. package/dist/run-4JNFLYXV.js +847 -0
  136. package/dist/src-G6OF5SKW.js +31 -0
  137. package/dist/src-J27WXNLY.js +270 -0
  138. package/dist/token-MOJUA2U6.js +70 -0
  139. package/dist/token-util-TENRN4V7.js +6 -0
  140. package/package.json +33 -4
@@ -0,0 +1,1178 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CHANNELS,
4
+ CloudflareClient,
5
+ GATEWAY_TOKEN_SECRET,
6
+ JUDGE_BYOK_VAR,
7
+ JUDGE_GATEWAY_PROVIDER,
8
+ MODEL_ROLES_VAR,
9
+ apiKillSwitchStore,
10
+ appliedMigrationsViaApi,
11
+ applyBundleMigrations,
12
+ compareVersions,
13
+ d1ApiMigrations,
14
+ databaseIdOf,
15
+ deployWorkers,
16
+ fetchReleaseManifest,
17
+ fetchVerifiedRelease,
18
+ gatewayProviderSlug,
19
+ getRelease,
20
+ healthSmoke,
21
+ installedExtensionsViaApi,
22
+ killSwitchControl,
23
+ listReleases,
24
+ locateDeployment,
25
+ mergeSecrets,
26
+ neededResources,
27
+ newRunId,
28
+ openBundle,
29
+ preflight,
30
+ provisionAiGateway,
31
+ provisionResources,
32
+ releaseAssetNames,
33
+ retireGatewayToken,
34
+ rollbackTarget,
35
+ runRollback,
36
+ runUpdate,
37
+ runsViaApi,
38
+ saveRunViaApi,
39
+ toHex,
40
+ varWorkers,
41
+ verifyBundleBytes,
42
+ withByokProvider,
43
+ withDeploymentVar,
44
+ workersDevHostname,
45
+ writeDeploymentState
46
+ } from "./chunk-ZRWF6QZS.js";
47
+ import {
48
+ DEFAULT_PRODUCT,
49
+ products
50
+ } from "./chunk-2ABSVMGB.js";
51
+ import {
52
+ PRODUCT_LABEL_VAR
53
+ } from "./chunk-6UWRT4VM.js";
54
+ import {
55
+ PROVIDER_INFO,
56
+ ROLE_PRESETS,
57
+ RoleLayerError,
58
+ modelRolesVar
59
+ } from "./chunk-KGHA67HG.js";
60
+
61
+ // src/io.ts
62
+ import { createInterface } from "node:readline/promises";
63
+ var Redactor = class {
64
+ values = /* @__PURE__ */ new Set();
65
+ add(value) {
66
+ if (value && value.length >= 6) this.values.add(value);
67
+ }
68
+ clean(text) {
69
+ let out = text;
70
+ for (const value of this.values) out = out.split(value).join("***");
71
+ return out;
72
+ }
73
+ };
74
+ function terminalIo(redactor) {
75
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
76
+ return {
77
+ interactive,
78
+ out: (line) => process.stdout.write(`${redactor.clean(line)}
79
+ `),
80
+ err: (line) => process.stderr.write(`${redactor.clean(line)}
81
+ `),
82
+ async ask(question, options = {}) {
83
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
84
+ const suffix = options.default ? ` [${options.default}]` : "";
85
+ if (options.secret) {
86
+ const output = rl;
87
+ const prompt = `${question}${suffix}: `;
88
+ process.stdout.write(prompt);
89
+ output._writeToOutput = () => {
90
+ };
91
+ const answer2 = await rl.question("");
92
+ process.stdout.write("\n");
93
+ rl.close();
94
+ return answer2.trim() || options.default || "";
95
+ }
96
+ const answer = await rl.question(`${question}${suffix}: `);
97
+ rl.close();
98
+ return answer.trim() || options.default || "";
99
+ }
100
+ };
101
+ }
102
+ async function choose(io, question, choices, fallback) {
103
+ if (choices.length === 1) return choices[0];
104
+ io.out(question);
105
+ for (const [i, c] of choices.entries()) io.out(` ${i + 1}) ${c}`);
106
+ for (; ; ) {
107
+ const answer = await io.ask("Choose", fallback ? { default: fallback } : {});
108
+ const index = Number(answer) - 1;
109
+ if (choices[index]) return choices[index];
110
+ if (choices.includes(answer)) return answer;
111
+ io.err(`Pick 1-${choices.length}.`);
112
+ }
113
+ }
114
+
115
+ // src/main.ts
116
+ import { existsSync, readFileSync } from "node:fs";
117
+ import { join } from "node:path";
118
+ var HELP = `cos: the Composable OS command. One command for a company's own repository and for
119
+ installing a product with no repository.
120
+
121
+ A client repo (stage 24)
122
+ cos create <dir> [--label <name>] [--with-mobile] [--version x.y.z]
123
+ a new client repo from the release's template (also
124
+ \`npm create composable-os <dir>\`)
125
+ cos init [--web <dir>] [--mobile <dir>] [--id <id>] [--label <name>] [--packs <list>]
126
+ [--envs staging,live] [--yes]
127
+ adopt the repo you are in: adds product.ts, skills/, each
128
+ app's typed client and host module and the rules in
129
+ AGENTS.md; shows a diff of every change to a file that
130
+ exists and applies it with --yes. The id and label default
131
+ to the folder's name; an adopted web app keeps its Worker
132
+ and deploys itself (web.deploy "own"); --envs declares
133
+ environments and binds HOST under the site's own ones
134
+ cos deploy [--env <name>] the host from the release in product.ts, with its packs and
135
+ the org's own extensions (checked first), then the web app;
136
+ with environments in product.ts, the one --env names
137
+ (--rotate-customer-auth-secret: a new customer secret,
138
+ which signs every customer out)
139
+ cos upgrade [--version X.Y.Z] in a client repo: move product.ts to a newer platform
140
+ version, regenerate the client, replace skills/, report type
141
+ errors; deploys nothing
142
+ cos add <block>, cos diff <block> [--accept]
143
+ copy a block from the release; show its upstream changes
144
+ (--accept: record them as merged by hand)
145
+ (cos add with no block lists them, with their skins)
146
+ cos client generate in a client repo: each app's typed client, again
147
+ cos content import <folder> --host <url> [--email <you>] [--dry-run] [--publish] [--yes]
148
+ load posts and their pictures into the host as you,
149
+ signed in for the run (by code with --email, else in the
150
+ browser); checks everything first and writes nothing on a
151
+ problem; a re-run creates nothing twice; --publish
152
+ publishes (or schedules) them with their own dates
153
+ (docs/importing.md)
154
+
155
+ Installing a product with no client repo
156
+ cos install [options] install, or repair an existing install (idempotent)
157
+ cos upgrade [--version X.Y.Z] update to a newer release (preflight, bookmark, migrate,
158
+ switch all Workers, smoke check; rolls back on failure)
159
+ cos rollback redeploy the previous release and restore its bookmark
160
+ cos status installed version, channel, URL and available releases
161
+ cos uninstall delete the Workers, database, bucket and namespace (asks)
162
+ cos ext check <dir> | test <dir> in a checkout of the repository: check an extension with
163
+ the checks the host runs, and run its tests
164
+ cos client generate --out <dir> in a checkout: write a product's typed client (customer.ts
165
+ and staff.ts) from its registry; see cos client --help
166
+
167
+ Options
168
+ --token <t> Cloudflare API token (or CLOUDFLARE_API_TOKEN). Needs, on the account:
169
+ Workers Scripts Edit, D1 Edit, Workers R2 Storage Edit, Workers KV
170
+ Storage Edit, Queues Edit, Vectorize Edit, Account Settings Read; with AI
171
+ on, AI Gateway Edit, Account API Tokens Edit (to generate the gateway's
172
+ token) and Secrets Store Edit (for --provider-key); and for a custom
173
+ hostname, Zone Read + Workers Routes Edit on that zone.
174
+ --account <id> account id (or CLOUDFLARE_ACCOUNT_ID); asked when the token sees several
175
+ --version <x.y.z> release to install or upgrade to (default: newest on the channel)
176
+ --channel <c> stable (default) or beta
177
+ --hostname <h> "workers.dev" (default) or a hostname on one of your zones
178
+ --zone <name> the zone of a custom hostname (default: inferred from it)
179
+ --identity <i> better-auth (default) or cloudflare-access
180
+ --gatekeepers <list> optional gatekeeper Workers to install, e.g. google,email-send
181
+ --ai <on|off> in-app AI: Workers AI and the demo-records Vectorize index (default on,
182
+ or COS_AI). Off: AI features say "AI is not configured". Upgrades keep
183
+ the choice; re-run install with --ai to change it
184
+ --ai-gateway <id|off> AI Gateway every model call goes through (default: one named after the
185
+ install, e.g. crm, created with logging and authentication on and its
186
+ token, with AI Gateway Run and Workers AI Read, stored as
187
+ AI_GATEWAY_TOKEN). Workers AI then goes through it over REST with
188
+ prompt and response logging off. off: call Workers AI directly over
189
+ the binding
190
+ --provider-key P=KEY store a provider key in the gateway as BYOK (repeatable), e.g.
191
+ deepseek=\u2026 or openai=\u2026 (a custom provider by its slug; typesafe=\u2026 is
192
+ the judge's key, Jev, and sets JUDGE_BYOK). Never logged.
193
+ Keys can also be added later in Settings \u2192 AI
194
+ --model-roles <m> this deployment's model roles (the AI_MODEL_ROLES layer): a preset
195
+ (${Object.keys(ROLE_PRESETS).join(", ")}), a JSON file, inline JSON, or
196
+ default (the shipped Workers AI roles). Kept by upgrades; Settings \u2192 AI
197
+ overrides still win
198
+ --ai-admin-token <t> Settings \u2192 AI's token (or COS_AI_ADMIN_TOKEN), stored on demo-app as
199
+ CLOUDFLARE_API_TOKEN; permissions in docs/deploying.md "In-app AI"
200
+ --secret NAME=VALUE a secret to set (repeatable); WORKER:NAME=VALUE for a gatekeeper's
201
+ --update-token <t> store a scoped token so Settings \u2192 Updates can update in place
202
+ --store-update-token store --token itself for one-click updates
203
+ --product <id> the product to install (default ${DEFAULT_PRODUCT}; one of ${Object.keys(products).join(", ")})
204
+ --repo <owner/repo> where releases come from (default: the product's own repository)
205
+ --no-gh skip \`gh attestation verify\` even if gh is installed
206
+ --require-gh fail unless \`gh attestation verify\` passes (full Sigstore check)
207
+ --wait after install, wait until /api/health answers
208
+ --bundle-dir <dir> use composable-os-<product>-<version>.tar.gz and SHA256SUMS from <dir> instead of downloading
209
+ (still verified against its build attestation)
210
+ --yes don't ask; fail on anything that would need an answer
211
+ -h, --help
212
+
213
+ Nothing is sent anywhere except the Cloudflare API and GitHub Releases. No telemetry.
214
+ `;
215
+ function parseArgs(argv) {
216
+ const flags = {};
217
+ let command = "";
218
+ for (let i = 0; i < argv.length; i++) {
219
+ const arg = argv[i];
220
+ if (arg === "-h") {
221
+ flags.help = true;
222
+ continue;
223
+ }
224
+ if (!arg.startsWith("--")) {
225
+ if (!command) command = arg;
226
+ else throw new Error(`unexpected argument ${arg}`);
227
+ continue;
228
+ }
229
+ const [key, inline] = arg.slice(2).split(/=(.*)/s, 2);
230
+ const takesValue = ![
231
+ "yes",
232
+ "help",
233
+ "no-gh",
234
+ "require-gh",
235
+ "wait",
236
+ "store-update-token",
237
+ "json",
238
+ "unverified",
239
+ "skip-build",
240
+ "no-typecheck",
241
+ "rotate-customer-auth-secret",
242
+ "accept",
243
+ "with-mobile",
244
+ "dry-run",
245
+ "publish"
246
+ ].includes(key);
247
+ let value = true;
248
+ if (takesValue) {
249
+ value = inline ?? argv[++i];
250
+ if (value === void 0) throw new Error(`--${key} needs a value`);
251
+ }
252
+ if (key === "secret") flags.secret = [...flags.secret ?? [], String(value)];
253
+ else if (key === "provider-key")
254
+ flags["provider-key"] = [...flags["provider-key"] ?? [], String(value)];
255
+ else flags[key] = value;
256
+ }
257
+ return { command, flags };
258
+ }
259
+ var CliError = class extends Error {
260
+ };
261
+ var PACKS_VAR = "COS_PACKS";
262
+ var CUSTOMER_SECRET = "CUSTOMER_AUTH_SECRET";
263
+ var ORG_EXTENSIONS_VAR = "COS_ORG_EXTENSIONS";
264
+ function str(flags, key) {
265
+ const value = flags[key];
266
+ return typeof value === "string" ? value : void 0;
267
+ }
268
+ function productOf(flags, deps) {
269
+ const known = deps.products ?? { all: products, default: DEFAULT_PRODUCT };
270
+ const id = str(flags, "product") ?? known.default;
271
+ const product = known.all[id];
272
+ if (!product) {
273
+ throw new CliError(`Unknown product ${id}. Known: ${Object.keys(known.all).join(", ")}.`);
274
+ }
275
+ return product;
276
+ }
277
+ async function session(flags, deps) {
278
+ const { io, env } = deps;
279
+ const product = productOf(flags, deps);
280
+ let token = str(flags, "token") ?? env.CLOUDFLARE_API_TOKEN;
281
+ if (!token) {
282
+ if (!io.interactive || flags.yes)
283
+ throw new CliError("A Cloudflare API token is needed: --token or CLOUDFLARE_API_TOKEN.");
284
+ io.out(
285
+ "Create a token at https://dash.cloudflare.com/profile/api-tokens with the permissions in `--help`."
286
+ );
287
+ token = await io.ask("Cloudflare API token", { secret: true });
288
+ }
289
+ deps.redactor.add(token);
290
+ const api = new CloudflareClient({
291
+ token,
292
+ ...env.COS_CLOUDFLARE_API ? { apiBase: env.COS_CLOUDFLARE_API } : {},
293
+ ...deps.fetch ? { fetch: deps.fetch } : {}
294
+ });
295
+ let accountId = str(flags, "account") ?? env.CLOUDFLARE_ACCOUNT_ID;
296
+ await api.verifyToken(accountId);
297
+ if (!accountId) {
298
+ const accounts = await api.listAccounts();
299
+ if (accounts.length === 0) throw new CliError("The token cannot see any account.");
300
+ if (accounts.length > 1 && (flags.yes || !io.interactive)) {
301
+ throw new CliError("The token sees several accounts; pass --account <id>.");
302
+ }
303
+ const label = await choose(
304
+ io,
305
+ "Which account?",
306
+ accounts.map((a) => `${a.name} (${a.id})`)
307
+ );
308
+ accountId = accounts.find((a) => label.endsWith(`(${a.id})`))?.id;
309
+ }
310
+ const source = releaseSource(flags, deps, product);
311
+ return { ...source, api, accountId };
312
+ }
313
+ function githubToken(deps) {
314
+ const token = deps.env.GITHUB_TOKEN || deps.env.GH_TOKEN || void 0;
315
+ if (token) deps.redactor.add(token);
316
+ return token;
317
+ }
318
+ function releaseSource(flags, deps, product) {
319
+ const { env } = deps;
320
+ const repository = str(flags, "repo") ?? product.updateRepository;
321
+ const github = {
322
+ repository,
323
+ product: product.id,
324
+ ...env.COS_GITHUB_API ? { apiBase: env.COS_GITHUB_API } : {},
325
+ ...deps.fetch ? { fetch: deps.fetch } : {},
326
+ ...githubToken(deps) ? { token: githubToken(deps) } : {}
327
+ };
328
+ const bundleDir = str(flags, "bundle-dir");
329
+ if (flags.unverified && !bundleDir)
330
+ throw new CliError("--unverified only applies to --bundle-dir");
331
+ let extra;
332
+ if (!flags["no-gh"] && deps.ghVerifier) extra = deps.ghVerifier;
333
+ if (flags["require-gh"] && !deps.ghVerifier) {
334
+ throw new CliError("--require-gh: the GitHub CLI (gh) is not installed.");
335
+ }
336
+ return {
337
+ product,
338
+ github,
339
+ repository,
340
+ extra,
341
+ ...bundleDir ? { bundleDir } : {},
342
+ unverified: Boolean(flags.unverified)
343
+ };
344
+ }
345
+ async function verified(s, version, deps) {
346
+ const local = s.bundleDir ? join(s.bundleDir, releaseAssetNames(s.product.id, version).bundle) : null;
347
+ if (local && existsSync(local)) {
348
+ deps.io.out(`Verifying the local bundle ${local}\u2026`);
349
+ const bytes = new Uint8Array(readFileSync(local));
350
+ const sums = readFileSync(join(s.bundleDir, "SHA256SUMS"), "utf8");
351
+ if (s.unverified) deps.io.err(" WARNING: --unverified: skipping the build attestation check.");
352
+ const { digest } = await verifyBundleBytes({
353
+ bytes,
354
+ product: s.product.id,
355
+ version,
356
+ sums,
357
+ repository: s.repository,
358
+ github: s.github,
359
+ skipProvenance: s.unverified,
360
+ ...s.extra && !s.unverified ? { extra: s.extra } : {}
361
+ });
362
+ const bundle = await openBundle(bytes);
363
+ if (bundle.manifest.version !== version) {
364
+ throw new CliError(`${local} holds ${bundle.manifest.version}, not ${version}`);
365
+ }
366
+ if (bundle.manifest.product !== s.product.id) {
367
+ throw new CliError(
368
+ `${local} is a release of ${bundle.manifest.product}, not ${s.product.id}`
369
+ );
370
+ }
371
+ return { bundle, digest };
372
+ }
373
+ deps.io.out(`Downloading ${s.product.label} ${version} and verifying it\u2026`);
374
+ const release = await fetchVerifiedRelease(version, {
375
+ ...s.github,
376
+ ...s.extra ? { extra: s.extra } : {}
377
+ });
378
+ deps.io.out(
379
+ ` sha256 ${release.digest} matches SHA256SUMS and its build attestation (${s.repository}, release workflow, v${version})${s.extra ? "; gh attestation verify passed" : ""}`
380
+ );
381
+ return release;
382
+ }
383
+ function parseSecrets(flags, redactor, appWorker) {
384
+ const out = {};
385
+ for (const entry of flags.secret ?? []) {
386
+ const match = /^(?:([\w-]+):)?([A-Z][A-Z0-9_]*)=(.*)$/s.exec(entry);
387
+ if (!match) throw new CliError(`--secret expects NAME=VALUE or WORKER:NAME=VALUE`);
388
+ const worker = match[1] ?? appWorker;
389
+ out[worker] ??= {};
390
+ out[worker][match[2]] = match[3];
391
+ redactor.add(match[3]);
392
+ }
393
+ return out;
394
+ }
395
+ function parseProviderKeys(flags, redactor) {
396
+ const out = [];
397
+ for (const entry of flags["provider-key"] ?? []) {
398
+ const match = /^([a-z0-9][a-z0-9-]*)=(.+)$/is.exec(entry);
399
+ if (match?.[2]) redactor.add(match[2]);
400
+ if (!match) throw new CliError("--provider-key expects PROVIDER=KEY, e.g. deepseek=\u2026");
401
+ out.push({ provider: match[1].toLowerCase(), key: match[2] });
402
+ }
403
+ return out;
404
+ }
405
+ function modelRolesChoice(flags) {
406
+ const raw = str(flags, "model-roles")?.trim();
407
+ if (raw === void 0) return void 0;
408
+ const isFile = raw !== "default" && !ROLE_PRESETS[raw] && !/^[[{]/.test(raw);
409
+ if (isFile && !existsSync(raw)) {
410
+ throw new CliError(
411
+ `--model-roles: no preset or file "${raw}" (presets: ${Object.keys(ROLE_PRESETS).join(", ")}, or default)`
412
+ );
413
+ }
414
+ try {
415
+ return modelRolesVar(isFile ? readFileSync(raw, "utf8") : raw);
416
+ } catch (error) {
417
+ if (error instanceof RoleLayerError) throw new CliError(`--model-roles: ${error.message}`);
418
+ throw error;
419
+ }
420
+ }
421
+ function registryProvider(slug) {
422
+ return Object.values(PROVIDER_INFO).find((p) => p.gatewaySlug === slug && p.needsKey)?.id;
423
+ }
424
+ function aiChoice(flags, env) {
425
+ const value = (str(flags, "ai") ?? env.COS_AI)?.trim().toLowerCase();
426
+ if (value === void 0 || value === "") return void 0;
427
+ if (value === "on" || value === "true") return true;
428
+ if (value === "off" || value === "false") return false;
429
+ throw new CliError("--ai is on or off");
430
+ }
431
+ function randomSecret() {
432
+ return toHex(crypto.getRandomValues(new Uint8Array(32)));
433
+ }
434
+ async function latestVersion(s, channel) {
435
+ const releases = await listReleases(channel, s.github);
436
+ const latest = releases[0];
437
+ if (!latest) throw new CliError(`No ${channel} release is published in ${s.repository} yet.`);
438
+ return latest.version;
439
+ }
440
+ function deploymentDatabase(flags, s) {
441
+ return str(flags, "database") ?? s.product.names.database;
442
+ }
443
+ function firstInstallNames(flags) {
444
+ const text = str(flags, "names");
445
+ if (!text) return { workers: {}, resources: {} };
446
+ const parsed = JSON.parse(text);
447
+ const ok = (map) => map === void 0 || typeof map === "object" && map !== null && Object.values(map).every((v) => typeof v === "string" && /^[a-z0-9-]+$/.test(v));
448
+ if (!ok(parsed.workers) || !ok(parsed.resources))
449
+ throw new CliError("--names is { workers, resources } of names");
450
+ return { workers: parsed.workers ?? {}, resources: parsed.resources ?? {} };
451
+ }
452
+ async function install(flags, deps) {
453
+ const { io } = deps;
454
+ const s = await session(flags, deps);
455
+ const existing = await locateDeployment(s.api, s.accountId, deploymentDatabase(flags, s));
456
+ const found = existing?.state ?? null;
457
+ const names = found ? null : firstInstallNames(flags);
458
+ const channelFlag = str(flags, "channel");
459
+ if (channelFlag && !CHANNELS.includes(channelFlag))
460
+ throw new CliError("--channel is stable or beta");
461
+ const channel = channelFlag ?? found?.channel ?? "stable";
462
+ const version = str(flags, "version") ?? found?.version ?? await latestVersion(s, channel);
463
+ if (found && compareVersions(version, found.version) > 0) {
464
+ throw new CliError(
465
+ `${s.product.label} ${found.version} is already installed here. Run \`cos upgrade --version ${version}\` to update it.`
466
+ );
467
+ }
468
+ if (found)
469
+ io.out(
470
+ `Found an existing install (${found.version}); re-running it to repair anything missing.`
471
+ );
472
+ const { bundle, digest } = await verified(s, version, deps);
473
+ const manifest = bundle.manifest;
474
+ const previous = found;
475
+ const app = manifest.workers.find((w) => w.role === "app");
476
+ if (!app) throw new CliError("The release has no app Worker.");
477
+ let hostnameMode = previous?.hostnameMode ?? "workers.dev";
478
+ let hostname = previous?.hostname;
479
+ let zoneId = previous?.zoneId;
480
+ if (!previous) {
481
+ let choice = str(flags, "hostname");
482
+ if (!choice && io.interactive && !flags.yes) {
483
+ choice = await io.ask(
484
+ "Hostname (workers.dev, or e.g. crm.example.com on one of your zones)",
485
+ {
486
+ default: "workers.dev"
487
+ }
488
+ );
489
+ }
490
+ if (!choice || choice === "workers.dev") {
491
+ hostname = await workersDevHostname(
492
+ s.api,
493
+ s.accountId,
494
+ names?.workers[app.name] ?? app.name,
495
+ deploymentDatabase(flags, s)
496
+ );
497
+ } else {
498
+ hostnameMode = "custom";
499
+ hostname = choice.toLowerCase();
500
+ const zones = await s.api.listZones(s.accountId);
501
+ const zoneName = str(flags, "zone");
502
+ const zone = zoneName ? zones.find((z) => z.name === zoneName) : zones.filter((z) => hostname === z.name || hostname?.endsWith(`.${z.name}`)).sort((a, b) => b.name.length - a.name.length)[0];
503
+ if (!zone) throw new CliError(`No active zone in this account covers ${hostname}.`);
504
+ zoneId = zone.id;
505
+ }
506
+ }
507
+ if (!hostname) throw new CliError("No hostname.");
508
+ let identity = previous?.identityProvider ?? str(flags, "identity");
509
+ if (!identity) {
510
+ identity = io.interactive && !flags.yes ? await choose(
511
+ io,
512
+ "Sign-in:",
513
+ ["better-auth", "cloudflare-access"],
514
+ "better-auth"
515
+ ) : "better-auth";
516
+ }
517
+ if (identity !== "better-auth" && identity !== "cloudflare-access") {
518
+ throw new CliError("--identity is better-auth or cloudflare-access");
519
+ }
520
+ const optional = manifest.workers.filter((w) => w.optional);
521
+ const requested = (str(flags, "gatekeepers") ?? "").split(",").map((g) => g.trim()).filter(Boolean).map(
522
+ (g) => g.startsWith(s.product.names.gatekeeperPrefix) ? g : `${s.product.names.gatekeeperPrefix}${g}`
523
+ );
524
+ for (const name of requested) {
525
+ if (!optional.some((w) => w.name === name)) throw new CliError(`Unknown gatekeeper ${name}.`);
526
+ }
527
+ const gatekeepers = [.../* @__PURE__ */ new Set([...previous?.gatekeepers ?? [], ...requested])].sort();
528
+ const ai = aiChoice(flags, deps.env) ?? previous?.ai ?? true;
529
+ const gatewayFlag = str(flags, "ai-gateway")?.trim();
530
+ if (gatewayFlag !== void 0 && gatewayFlag !== "off" && !/^[a-z0-9][a-z0-9-_]{0,63}$/i.test(gatewayFlag)) {
531
+ throw new CliError("--ai-gateway is a gateway id (letters, digits, - and _) or off");
532
+ }
533
+ const aiGateway = gatewayFlag === "off" ? false : gatewayFlag ?? previous?.aiGateway;
534
+ const providerKeys = parseProviderKeys(flags, deps.redactor);
535
+ if (providerKeys.length && (!ai || aiGateway === false)) {
536
+ throw new CliError("--provider-key stores keys in AI Gateway: it needs AI and a gateway on");
537
+ }
538
+ const modelRoles = modelRolesChoice(flags);
539
+ if (modelRoles && !ai) throw new CliError("--model-roles needs in-app AI on (--ai on)");
540
+ const secrets = parseSecrets(flags, deps.redactor, app.name);
541
+ secrets[app.name] ??= {};
542
+ const appSecrets = secrets[app.name];
543
+ const scripts = new Set((await s.api.listScripts(s.accountId)).map((sc) => sc.id));
544
+ const deployedAs = (name) => (previous?.workerNames ?? names?.workers)?.[name] ?? name;
545
+ const appSet = scripts.has(deployedAs(app.name)) ? await s.api.listSecrets(s.accountId, deployedAs(app.name)) : [];
546
+ if (!appSet.includes("BETTER_AUTH_SECRET") && !appSecrets.BETTER_AUTH_SECRET) {
547
+ appSecrets.BETTER_AUTH_SECRET = randomSecret();
548
+ deps.redactor.add(appSecrets.BETTER_AUTH_SECRET);
549
+ }
550
+ appSecrets.BETTER_AUTH_URL ??= `https://${hostname}`;
551
+ const customerAuthUrl = str(flags, "customer-auth-url");
552
+ if (customerAuthUrl !== void 0) {
553
+ if (!/^https?:\/\/[^/]+$/.test(customerAuthUrl)) {
554
+ throw new CliError("--customer-auth-url is the web app's origin, https://host");
555
+ }
556
+ if (flags["rotate-customer-auth-secret"] || !appSet.includes(CUSTOMER_SECRET) && !appSecrets[CUSTOMER_SECRET]) {
557
+ let secret = randomSecret();
558
+ while (secret === appSecrets.BETTER_AUTH_SECRET) secret = randomSecret();
559
+ appSecrets[CUSTOMER_SECRET] = secret;
560
+ deps.redactor.add(secret);
561
+ }
562
+ }
563
+ const updateToken = str(flags, "update-token") ?? (flags["store-update-token"] ? str(flags, "token") ?? deps.env.CLOUDFLARE_API_TOKEN : void 0);
564
+ if (updateToken) {
565
+ deps.redactor.add(updateToken);
566
+ appSecrets.COS_UPDATE_TOKEN = updateToken;
567
+ }
568
+ const aiAdminToken = str(flags, "ai-admin-token") ?? deps.env.COS_AI_ADMIN_TOKEN;
569
+ if (aiAdminToken) {
570
+ deps.redactor.add(aiAdminToken);
571
+ appSecrets.CLOUDFLARE_API_TOKEN = aiAdminToken;
572
+ }
573
+ if (identity === "cloudflare-access") {
574
+ for (const name of ["CF_ACCESS_TEAM_DOMAIN", "CF_ACCESS_AUD"]) {
575
+ if (appSecrets[name] || appSet.includes(name)) continue;
576
+ if (flags.yes || !io.interactive)
577
+ throw new CliError(`Cloudflare Access needs --secret ${name}=\u2026`);
578
+ appSecrets[name] = await io.ask(
579
+ name === "CF_ACCESS_AUD" ? "Access application AUD tag" : "Access team domain"
580
+ );
581
+ }
582
+ }
583
+ for (const name of gatekeepers) {
584
+ const worker = manifest.workers.find((w) => w.name === name);
585
+ const set = scripts.has(deployedAs(name)) ? await s.api.listSecrets(s.accountId, deployedAs(name)) : [];
586
+ for (const secret of worker?.secrets ?? []) {
587
+ if (!secret.required || set.includes(secret.name) || secrets[name]?.[secret.name]) continue;
588
+ if (flags.yes || !io.interactive) {
589
+ throw new CliError(`${name} needs --secret ${name}:${secret.name}=\u2026`);
590
+ }
591
+ const value = await io.ask(
592
+ `${name} ${secret.name}${secret.description ? ` (${secret.description})` : ""}`,
593
+ {
594
+ secret: true
595
+ }
596
+ );
597
+ deps.redactor.add(value);
598
+ secrets[name] = { ...secrets[name], [secret.name]: value };
599
+ }
600
+ }
601
+ let vars = { ...previous?.vars ?? {} };
602
+ if (identity !== "better-auth")
603
+ vars[app.name] = { ...vars[app.name], IDENTITY_PROVIDER: identity };
604
+ if (modelRoles !== void 0) {
605
+ vars = withDeploymentVar(vars, manifest, MODEL_ROLES_VAR, modelRoles);
606
+ }
607
+ for (const [flag, name] of [
608
+ ["packs", PACKS_VAR],
609
+ ["org-extensions", ORG_EXTENSIONS_VAR]
610
+ ]) {
611
+ const value = str(flags, flag);
612
+ if (value === void 0) continue;
613
+ for (const worker of varWorkers(manifest, name))
614
+ vars[worker] = { ...vars[worker], [name]: value };
615
+ }
616
+ if (customerAuthUrl !== void 0) {
617
+ vars[app.name] = { ...vars[app.name], CUSTOMER_AUTH_URL: customerAuthUrl };
618
+ }
619
+ const nativeRedirects = str(flags, "native-redirect-uris");
620
+ if (nativeRedirects !== void 0) {
621
+ vars[app.name] = { ...vars[app.name], NATIVE_REDIRECT_URIS: nativeRedirects };
622
+ } else if (vars[app.name]?.NATIVE_REDIRECT_URIS === void 0) {
623
+ vars[app.name] = { ...vars[app.name], NATIVE_REDIRECT_URIS: "http://127.0.0.1/cos-sign-in" };
624
+ }
625
+ const gatekeeperVars = str(flags, "gatekeeper-vars");
626
+ if (gatekeeperVars !== void 0) {
627
+ const parsed = JSON.parse(gatekeeperVars);
628
+ for (const [worker, values] of Object.entries(parsed)) {
629
+ if (!manifest.workers.some((w) => w.name === worker && w.role === "gatekeeper")) {
630
+ throw new CliError(`--gatekeeper-vars names ${worker}, not a gatekeeper of this release`);
631
+ }
632
+ vars[worker] = { ...vars[worker], ...values };
633
+ }
634
+ }
635
+ const sendEmailFlag = str(flags, "send-email");
636
+ const sendEmail = {
637
+ ...previous?.sendEmail ?? {},
638
+ ...sendEmailFlag ? JSON.parse(sendEmailFlag) : {}
639
+ };
640
+ const label = str(flags, "label");
641
+ if (label !== void 0) {
642
+ for (const worker of varWorkers(manifest, PRODUCT_LABEL_VAR)) {
643
+ vars[worker] = { ...vars[worker], [PRODUCT_LABEL_VAR]: label };
644
+ }
645
+ }
646
+ if (aiGateway === false) {
647
+ for (const [worker, values] of Object.entries(vars)) {
648
+ if (values.AI_GATEWAY_ID === void 0 && values.AI_GATEWAY_REST === void 0) continue;
649
+ const { AI_GATEWAY_ID: _gone, AI_GATEWAY_REST: _rest, ...rest } = values;
650
+ vars[worker] = rest;
651
+ }
652
+ }
653
+ io.out(
654
+ `
655
+ Installing ${s.product.label} ${version} into account ${s.accountId} at https://${hostname}`
656
+ );
657
+ if (!ai) io.out("In-app AI is off (--ai off): no Workers AI or Vectorize bindings.");
658
+ io.out("Resources:");
659
+ const resources = {
660
+ ...previous?.resources ?? {},
661
+ ...await provisionResources(
662
+ s.api,
663
+ s.accountId,
664
+ neededResources(manifest, gatekeepers, { ai }),
665
+ (l) => io.out(l),
666
+ previous?.resourceNames ?? names?.resources
667
+ )
668
+ };
669
+ const base = {
670
+ version,
671
+ accountId: s.accountId,
672
+ hostname,
673
+ hostnameMode,
674
+ ...zoneId ? { zoneId } : {},
675
+ identityProvider: identity,
676
+ channel,
677
+ gatekeepers,
678
+ ai,
679
+ ...aiGateway !== void 0 ? { aiGateway } : {},
680
+ ...previous?.aiGatewayCreated ? { aiGatewayCreated: true } : {},
681
+ ...previous?.aiGatewayTokenId ? { aiGatewayTokenId: previous.aiGatewayTokenId } : {},
682
+ ...previous?.aiGatewayTokenWorkersAi ? { aiGatewayTokenWorkersAi: true } : {},
683
+ workerNames: previous?.workerNames ?? names?.workers ?? {},
684
+ ...previous?.resourceNames ? { resourceNames: previous.resourceNames } : names && Object.keys(names.resources).length ? { resourceNames: names.resources } : {},
685
+ vars,
686
+ ...sendEmail && Object.keys(sendEmail).length ? { sendEmail } : {},
687
+ resources,
688
+ bundleDigest: digest,
689
+ installedAt: previous?.installedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
690
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
691
+ };
692
+ if (ai && aiGateway !== false) io.out("AI Gateway:");
693
+ const suppliedToken = Object.values(secrets).find((v) => v[GATEWAY_TOKEN_SECRET])?.[GATEWAY_TOKEN_SECRET];
694
+ const gateway = await provisionAiGateway({
695
+ api: s.api,
696
+ manifest,
697
+ state: base,
698
+ ...suppliedToken ? { token: suppliedToken } : {},
699
+ log: (l) => io.out(l)
700
+ });
701
+ for (const values of Object.values(gateway.secrets)) {
702
+ for (const value of Object.values(values)) deps.redactor.add(value);
703
+ }
704
+ Object.assign(secrets, mergeSecrets(secrets, gateway.secrets));
705
+ const state = { ...base, vars: gateway.vars, ...gateway.state };
706
+ if (providerKeys.length) {
707
+ if (!gateway.gatewayId) {
708
+ throw new CliError("--provider-key: no AI Gateway could be set up (see the warning above).");
709
+ }
710
+ for (const { provider, key } of providerKeys) {
711
+ const slug = gatewayProviderSlug(manifest, provider);
712
+ await s.api.setGatewayProviderKey(s.accountId, gateway.gatewayId, slug, key);
713
+ io.out(` provider key ${slug}: stored in AI Gateway ${gateway.gatewayId} (BYOK)`);
714
+ const registry = registryProvider(slug);
715
+ if (registry) state.vars = withByokProvider(state.vars, manifest, registry);
716
+ if (slug === JUDGE_GATEWAY_PROVIDER) {
717
+ state.vars = withDeploymentVar(state.vars, manifest, JUDGE_BYOK_VAR, "true");
718
+ }
719
+ }
720
+ }
721
+ if (modelRoles !== void 0) {
722
+ const name = str(flags, "model-roles")?.trim() ?? "";
723
+ const what = !modelRoles ? "the shipped defaults" : ROLE_PRESETS[name] ? name : "custom JSON";
724
+ const on = varWorkers(manifest, MODEL_ROLES_VAR).join(" and ");
725
+ io.out(`Model roles (${MODEL_ROLES_VAR} on ${on}): ${what}`);
726
+ }
727
+ const databaseId = databaseIdOf(manifest, resources);
728
+ io.out("Core migrations:");
729
+ const applied = await applyBundleMigrations(
730
+ bundle,
731
+ d1ApiMigrations(s.api, s.accountId, databaseId),
732
+ (l) => io.out(l)
733
+ );
734
+ if (!applied.length) io.out(" up to date");
735
+ await writeDeploymentState(s.api, databaseId, state);
736
+ io.out("Workers:");
737
+ for (const [worker, values] of Object.entries(secrets)) {
738
+ if (Object.keys(values).length)
739
+ io.out(` setting secrets on ${worker}: ${Object.keys(values).sort().join(", ")}`);
740
+ }
741
+ const result = await deployWorkers({ api: s.api, bundle, state, secrets, log: (l) => io.out(l) });
742
+ await retireGatewayToken(s.api, s.accountId, gateway.retiredTokenId, (l) => io.out(l));
743
+ if (flags.wait) {
744
+ io.out("Waiting for /api/health\u2026");
745
+ await healthSmoke(hostname, version, {
746
+ ...deps.fetch ? { fetch: deps.fetch } : {},
747
+ ...deps.env.COS_HEALTH_ORIGIN ? { origin: deps.env.COS_HEALTH_ORIGIN } : {},
748
+ ...deps.smokeDelayMs !== void 0 ? { delayMs: deps.smokeDelayMs } : {}
749
+ });
750
+ }
751
+ io.out(`
752
+ Done. ${s.product.label} ${version} is at ${result.url}`);
753
+ io.out(`Open ${result.url}/setup to create the first admin and finish setting up.`);
754
+ if (!updateToken) {
755
+ io.out(
756
+ "Updates: run `npx @composable-os/cli upgrade` (or store a token with --update-token for Settings \u2192 Updates)."
757
+ );
758
+ }
759
+ return 0;
760
+ }
761
+ async function locate(s, flags = {}) {
762
+ const located = await locateDeployment(s.api, s.accountId, deploymentDatabase(flags, s));
763
+ if (!located?.state) {
764
+ throw new CliError(
765
+ `No ${s.product.label} installed from a release was found in this account. Run \`npx @composable-os/cli install\` first.`
766
+ );
767
+ }
768
+ return { databaseId: located.databaseId, state: located.state };
769
+ }
770
+ function printPreflight(io, result) {
771
+ io.out(`Preflight ${result.from ?? "?"} \u2192 ${result.to}: ${result.ok ? "OK" : "BLOCKED"}`);
772
+ io.out(` migrations: ${result.migrations.length ? result.migrations.join(", ") : "none"}`);
773
+ const gk = result.gatekeepers;
774
+ if (gk.added.length || gk.changed.length || gk.removed.length) {
775
+ io.out(
776
+ ` gatekeepers: +${gk.added.join(",") || "-"} ~${gk.changed.join(",") || "-"} -${gk.removed.join(",") || "-"}`
777
+ );
778
+ }
779
+ for (const secret of result.secrets) {
780
+ io.out(
781
+ ` secret ${secret.worker} ${secret.name}${secret.required ? " (required)" : ""}: ${secret.set === null ? "?" : secret.set ? "set" : "not set"}`
782
+ );
783
+ }
784
+ for (const extension of result.extensions) {
785
+ io.out(
786
+ ` extension ${extension.id}: contract ${extension.contractVersion} ${extension.compatible ? "ok" : "INCOMPATIBLE"}`
787
+ );
788
+ }
789
+ for (const w of result.warnings) io.out(` note: ${w.message}`);
790
+ for (const b of result.blockers) io.err(` blocked: ${b.message}`);
791
+ }
792
+ async function currentManifest(s, version) {
793
+ try {
794
+ return await fetchReleaseManifest(await getRelease(version, s.github), s.github);
795
+ } catch {
796
+ return null;
797
+ }
798
+ }
799
+ async function upgrade(flags, deps) {
800
+ const { io } = deps;
801
+ const s = await session(flags, deps);
802
+ const { databaseId, state: found } = await locate(s, flags);
803
+ const channel = found.channel;
804
+ const target = str(flags, "version") ?? await latestVersion(s, channel);
805
+ if (compareVersions(target, found.version) <= 0) {
806
+ io.out(
807
+ `${s.product.label} ${found.version} is installed; nothing newer on the ${channel} channel.`
808
+ );
809
+ return 0;
810
+ }
811
+ const release = await verified(s, target, deps);
812
+ const state = found;
813
+ const secretsSet = {};
814
+ const scripts = new Set((await s.api.listScripts(s.accountId)).map((x) => x.id));
815
+ for (const worker of release.bundle.manifest.workers) {
816
+ const deployed = state.workerNames[worker.name] ?? worker.name;
817
+ if (scripts.has(deployed))
818
+ secretsSet[worker.name] = await s.api.listSecrets(s.accountId, deployed);
819
+ }
820
+ const result = preflight({
821
+ currentVersion: state.version,
822
+ current: await currentManifest(s, state.version),
823
+ target: release.bundle.manifest,
824
+ appliedMigrations: await appliedMigrationsViaApi(s.api, s.accountId, databaseId),
825
+ extensions: await installedExtensionsViaApi(s.api, s.accountId, databaseId),
826
+ installedGatekeepers: state.gatekeepers,
827
+ secretsSet
828
+ });
829
+ printPreflight(io, result);
830
+ if (!result.ok) return 1;
831
+ if (!flags.yes && io.interactive) {
832
+ const answer = await io.ask(`Update ${state.version} \u2192 ${target}? (yes/no)`, { default: "no" });
833
+ if (answer.toLowerCase() !== "yes") return 1;
834
+ }
835
+ const run = {
836
+ id: newRunId(),
837
+ kind: "update",
838
+ from_version: state.version,
839
+ to_version: target,
840
+ status: "running",
841
+ step: null,
842
+ bookmark: null,
843
+ bundle_digest: release.digest,
844
+ preflight: JSON.stringify(result),
845
+ error: null,
846
+ started_by: null,
847
+ surface: "cli",
848
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
849
+ finished_at: null
850
+ };
851
+ await saveRunViaApi(s.api, s.accountId, databaseId, run);
852
+ let previousBundle = null;
853
+ const outcome = await runUpdate({
854
+ api: s.api,
855
+ state,
856
+ databaseId,
857
+ target: release.bundle,
858
+ targetDigest: release.digest,
859
+ previous: async () => {
860
+ previousBundle ??= (await verified(s, state.version, deps)).bundle;
861
+ return previousBundle;
862
+ },
863
+ migrations: d1ApiMigrations(s.api, s.accountId, databaseId),
864
+ // Stage 5's kill switch, reversibly: on before migrating, off after the smoke check or rollback.
865
+ automations: killSwitchControl(apiKillSwitchStore(s.api, s.accountId, databaseId)),
866
+ smoke: (hostname, version) => healthSmoke(hostname, version, {
867
+ ...deps.fetch ? { fetch: deps.fetch } : {},
868
+ ...deps.env.COS_HEALTH_ORIGIN ? { origin: deps.env.COS_HEALTH_ORIGIN } : {},
869
+ ...deps.smokeDelayMs !== void 0 ? { delayMs: deps.smokeDelayMs } : {}
870
+ }),
871
+ onStep: async (step, o) => {
872
+ run.step = step;
873
+ run.bookmark = o?.bookmark ?? run.bookmark;
874
+ if (step === "done") {
875
+ run.status = o?.status ?? "failed";
876
+ run.error = o?.rollbackError ? `${o.error}; rollback failed: ${o.rollbackError}` : o?.error ?? null;
877
+ run.finished_at = (/* @__PURE__ */ new Date()).toISOString();
878
+ }
879
+ if (step === "pause" || step === "bookmark" || step === "restored" || step === "done") {
880
+ await saveRunViaApi(s.api, s.accountId, databaseId, run);
881
+ }
882
+ },
883
+ log: (l) => io.out(l)
884
+ });
885
+ if (outcome.status === "succeeded") {
886
+ io.out(
887
+ `
888
+ Updated to ${s.product.label} ${target}. Migrations applied: ${outcome.migrations.join(", ") || "none"}.`
889
+ );
890
+ return 0;
891
+ }
892
+ io.err(`
893
+ Update failed: ${outcome.error}`);
894
+ io.err(
895
+ outcome.status === "rolled_back" ? `Rolled back to ${state.version} and restored the database to bookmark ${outcome.bookmark}.` : `Rollback did not complete (${outcome.rollbackError ?? "no bookmark"}). Run \`cos rollback\`, or see docs/deploying.md.`
896
+ );
897
+ return 1;
898
+ }
899
+ async function rollback(flags, deps) {
900
+ const { io } = deps;
901
+ const s = await session(flags, deps);
902
+ const { databaseId, state } = await locate(s, flags);
903
+ const runs = await runsViaApi(s.api, s.accountId, databaseId, 20);
904
+ const last = rollbackTarget(runs);
905
+ if (!last?.from_version) {
906
+ io.err("There is no completed update to roll back.");
907
+ return 1;
908
+ }
909
+ if (!flags.yes && io.interactive) {
910
+ const answer = await io.ask(
911
+ `Roll back ${state.version} \u2192 ${last.from_version} and restore the database to before the update (changes since then are lost)? (yes/no)`,
912
+ { default: "no" }
913
+ );
914
+ if (answer.toLowerCase() !== "yes") return 1;
915
+ }
916
+ const previous = await verified(s, last.from_version, deps);
917
+ const record = {
918
+ id: newRunId(),
919
+ kind: "rollback",
920
+ from_version: state.version,
921
+ to_version: last.from_version,
922
+ status: "running",
923
+ step: null,
924
+ bookmark: last.bookmark,
925
+ bundle_digest: previous.digest,
926
+ preflight: null,
927
+ error: null,
928
+ started_by: null,
929
+ surface: "cli",
930
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
931
+ finished_at: null
932
+ };
933
+ await runRollback({
934
+ api: s.api,
935
+ state,
936
+ databaseId,
937
+ previous: previous.bundle,
938
+ previousDigest: previous.digest,
939
+ bookmark: last.bookmark,
940
+ automations: killSwitchControl(apiKillSwitchStore(s.api, s.accountId, databaseId)),
941
+ log: (l) => io.out(l)
942
+ });
943
+ await saveRunViaApi(s.api, s.accountId, databaseId, { ...last, status: "rolled_back" });
944
+ await saveRunViaApi(s.api, s.accountId, databaseId, {
945
+ ...record,
946
+ status: "succeeded",
947
+ finished_at: (/* @__PURE__ */ new Date()).toISOString()
948
+ });
949
+ io.out(`Rolled back to ${s.product.label} ${last.from_version}.`);
950
+ return 0;
951
+ }
952
+ async function status(flags, deps) {
953
+ const { io } = deps;
954
+ const s = await session(flags, deps);
955
+ const { state, databaseId } = await locate(s, flags);
956
+ const releases = await listReleases(state.channel, s.github).catch(() => []);
957
+ const newer = releases.filter((r) => compareVersions(r.version, state.version) > 0);
958
+ const runs = await runsViaApi(s.api, s.accountId, databaseId, 5);
959
+ if (flags.json) {
960
+ io.out(
961
+ JSON.stringify(
962
+ { state: { ...state, resources: void 0 }, available: newer.map((r) => r.version), runs },
963
+ null,
964
+ 2
965
+ )
966
+ );
967
+ return 0;
968
+ }
969
+ io.out(
970
+ `${s.product.label} ${state.version} (${state.channel} channel) at https://${state.hostname}`
971
+ );
972
+ io.out(
973
+ ` sign-in: ${state.identityProvider}; gatekeepers: ${state.gatekeepers.join(", ") || "none"}; AI: ${state.ai === false ? "off" : "on"}`
974
+ );
975
+ io.out(
976
+ newer.length ? ` available: ${newer.map((r) => r.version).join(", ")} (run \`cos upgrade\`)` : " up to date"
977
+ );
978
+ for (const run of runs) {
979
+ io.out(
980
+ ` ${run.started_at} ${run.kind} ${run.from_version ?? "?"} \u2192 ${run.to_version}: ${run.status} (${run.surface})`
981
+ );
982
+ }
983
+ return 0;
984
+ }
985
+ async function uninstall(flags, deps) {
986
+ const { io } = deps;
987
+ const s = await session(flags, deps);
988
+ const { state } = await locate(s, flags);
989
+ if (!flags.yes) {
990
+ if (!io.interactive) throw new CliError("uninstall deletes everything; pass --yes");
991
+ const answer = await io.ask(
992
+ `This deletes the Workers, the database and every record of https://${state.hostname}. Type the hostname to confirm`
993
+ );
994
+ if (answer !== state.hostname) return 1;
995
+ }
996
+ const names = [
997
+ ...new Set(
998
+ [s.product.names.app, ...state.gatekeepers, s.product.names.runner].map(
999
+ (n) => state.workerNames[n] ?? n
1000
+ )
1001
+ )
1002
+ ];
1003
+ const failures = [];
1004
+ const attempt = async (label, action) => {
1005
+ try {
1006
+ await action();
1007
+ io.out(` deleted ${label}`);
1008
+ } catch (error) {
1009
+ failures.push(`${label}: ${error.message}`);
1010
+ }
1011
+ };
1012
+ for (const name of names)
1013
+ await attempt(`Worker ${name}`, () => s.api.deleteScript(s.accountId, name));
1014
+ const seen = /* @__PURE__ */ new Set();
1015
+ for (const [key, value] of Object.entries(state.resources)) {
1016
+ const kind = key.slice(0, key.indexOf("("));
1017
+ if (seen.has(`${kind}:${value}`)) continue;
1018
+ seen.add(`${kind}:${value}`);
1019
+ if (kind === "D1_ID") await attempt(`D1 ${key}`, () => s.api.deleteD1(s.accountId, value));
1020
+ if (kind === "KV_ID") await attempt(`KV ${key}`, () => s.api.deleteKv(s.accountId, value));
1021
+ if (kind === "R2_NAME") await attempt(`R2 ${value}`, () => s.api.deleteR2(s.accountId, value));
1022
+ if (kind === "VECTORIZE_NAME") {
1023
+ await attempt(`Vectorize ${value}`, () => s.api.deleteVectorize(s.accountId, value));
1024
+ }
1025
+ if (kind === "QUEUE_NAME") {
1026
+ const queue = (await s.api.listQueues(s.accountId)).find((q) => q.queue_name === value);
1027
+ if (queue)
1028
+ await attempt(`Queue ${value}`, () => s.api.deleteQueue(s.accountId, queue.queue_id));
1029
+ }
1030
+ }
1031
+ if (typeof state.aiGateway === "string" && state.aiGatewayCreated) {
1032
+ const gatewayId = state.aiGateway;
1033
+ await attempt(`AI Gateway ${gatewayId}`, () => s.api.deleteAiGateway(s.accountId, gatewayId));
1034
+ }
1035
+ if (state.aiGatewayTokenId) {
1036
+ const tokenId = state.aiGatewayTokenId;
1037
+ await attempt("the AI Gateway token", () => s.api.deleteAccountToken(s.accountId, tokenId));
1038
+ }
1039
+ for (const failure of failures) io.err(` could not delete ${failure}`);
1040
+ return failures.length ? 1 : 0;
1041
+ }
1042
+ async function ext(argv, deps) {
1043
+ let runExt;
1044
+ try {
1045
+ ({ runExt } = await import("./cli-BRSACHSG.js"));
1046
+ return await runExt(argv, deps.io);
1047
+ } catch (error) {
1048
+ if (error.code === "ERR_MODULE_NOT_FOUND") {
1049
+ deps.io.err(
1050
+ "cos ext runs in a checkout of the Composable OS repository, after pnpm install: pnpm cos ext check <dir>"
1051
+ );
1052
+ return 2;
1053
+ }
1054
+ throw error;
1055
+ }
1056
+ }
1057
+ async function client(argv, deps) {
1058
+ if (argv[0] === "generate" && !argv.includes("--out")) {
1059
+ const repo = await import("./client-repo-ZVZ6KW5S.js");
1060
+ const parsed = parseArgs(["client", ...argv.slice(1)]);
1061
+ const dir = str(parsed.flags, "dir") ?? process.cwd();
1062
+ if (repo.isClientRepo(dir)) {
1063
+ try {
1064
+ return await repo.regenerate(parsed.flags, deps);
1065
+ } catch (error) {
1066
+ if (!(error instanceof CliError)) throw error;
1067
+ deps.io.err(error.message);
1068
+ return 1;
1069
+ }
1070
+ }
1071
+ }
1072
+ try {
1073
+ const { runClient } = await import("./cli-DTMGNDXN.js");
1074
+ return await runClient(argv, deps.io);
1075
+ } catch (error) {
1076
+ if (error.code === "ERR_MODULE_NOT_FOUND") {
1077
+ deps.io.err(
1078
+ "cos client runs in a checkout of the Composable OS repository, after pnpm install: pnpm cos client generate --out <dir>"
1079
+ );
1080
+ return 2;
1081
+ }
1082
+ throw error;
1083
+ }
1084
+ }
1085
+ async function content(argv, deps) {
1086
+ if (argv[0] !== "import") {
1087
+ deps.io.err(
1088
+ "Usage: cos content import <folder> --host <url> [--email <you>] [--dry-run] [--publish] [--yes]"
1089
+ );
1090
+ return 2;
1091
+ }
1092
+ const rest = argv.slice(1);
1093
+ const positional = rest[0] && !rest[0].startsWith("-") ? [rest[0]] : [];
1094
+ let parsed;
1095
+ try {
1096
+ parsed = parseArgs(["import", ...rest.slice(positional.length)]);
1097
+ } catch (error) {
1098
+ deps.io.err(error.message);
1099
+ return 2;
1100
+ }
1101
+ const { contentImport } = await import("./run-4JNFLYXV.js");
1102
+ try {
1103
+ return await contentImport(
1104
+ positional,
1105
+ {
1106
+ ...str(parsed.flags, "host") ? { host: str(parsed.flags, "host") } : {},
1107
+ ...str(parsed.flags, "email") ? { email: str(parsed.flags, "email") } : {},
1108
+ dryRun: Boolean(parsed.flags["dry-run"]),
1109
+ publish: Boolean(parsed.flags.publish),
1110
+ yes: Boolean(parsed.flags.yes)
1111
+ },
1112
+ deps.io
1113
+ );
1114
+ } catch (error) {
1115
+ deps.io.err(`Error: ${error.message}`);
1116
+ return 1;
1117
+ }
1118
+ }
1119
+ async function runCli(argv, input) {
1120
+ const deps = input;
1121
+ if (argv[0] === "content") return content(argv.slice(1), deps);
1122
+ if (argv[0] === "ext") return ext(argv.slice(1), deps);
1123
+ if (argv[0] === "client") return client(argv.slice(1), deps);
1124
+ const positional = ["create", "add", "diff"].includes(argv[0] ?? "") && argv[1] && !argv[1].startsWith("-") ? [argv[1]] : [];
1125
+ let parsed;
1126
+ try {
1127
+ parsed = parseArgs(positional.length ? [argv[0], ...argv.slice(2)] : argv);
1128
+ } catch (error) {
1129
+ deps.io.err(error.message);
1130
+ return 2;
1131
+ }
1132
+ if (parsed.flags.help || !argv.length) {
1133
+ deps.io.out(HELP);
1134
+ return argv.length ? 0 : 2;
1135
+ }
1136
+ const repo = await import("./client-repo-ZVZ6KW5S.js");
1137
+ const blocks = await import("./blocks-DEELKGDC.js");
1138
+ const commands = {
1139
+ install,
1140
+ // In a client repo (its product.ts is a client product), `cos upgrade` moves the repo to a
1141
+ // newer platform version; anywhere else it updates an installed deployment, as before.
1142
+ upgrade: (flags, d) => repo.isClientRepo(str(flags, "dir") ?? process.cwd()) ? repo.upgradeRepo(flags, d) : upgrade(flags, d),
1143
+ rollback,
1144
+ status,
1145
+ uninstall,
1146
+ create: (flags, d) => repo.create(positional, flags, d),
1147
+ init: repo.init,
1148
+ deploy: repo.deploy,
1149
+ add: (flags, d) => blocks.add(positional, flags, d),
1150
+ diff: (flags, d) => blocks.diff(positional, flags, d)
1151
+ };
1152
+ const command = commands[parsed.command];
1153
+ if (!command) {
1154
+ deps.io.err(`Unknown command ${parsed.command}.
1155
+
1156
+ ${HELP}`);
1157
+ return 2;
1158
+ }
1159
+ try {
1160
+ return await command(parsed.flags, deps);
1161
+ } catch (error) {
1162
+ deps.io.err(`Error: ${error.message}`);
1163
+ return 1;
1164
+ }
1165
+ }
1166
+
1167
+ export {
1168
+ Redactor,
1169
+ terminalIo,
1170
+ CliError,
1171
+ str,
1172
+ releaseSource,
1173
+ verified,
1174
+ latestVersion,
1175
+ install,
1176
+ upgrade,
1177
+ runCli
1178
+ };