usecloudy 0.3.2 → 0.3.5

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 (3) hide show
  1. package/README.md +4 -4
  2. package/dist/index.js +856 -403
  3. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { fileURLToPath } from "node:url";
3
3
  import fs, { chmodSync, createWriteStream, existsSync, lstatSync, readFileSync, readlinkSync, realpathSync, statSync, symlinkSync, watch, writeFileSync } from "node:fs";
4
- import { chmod, copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, readlink, rename, rm, stat, writeFile } from "node:fs/promises";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
  import { EventEmitter } from "node:events";
@@ -12,15 +12,254 @@ import { createHash } from "node:crypto";
12
12
  import { createInterface } from "node:readline/promises";
13
13
  import { Readable, Transform } from "node:stream";
14
14
  import { pipeline } from "node:stream/promises";
15
+ //#region src/config.ts
16
+ /**
17
+ * Pinned, never derived from the site domain: saved sign-ins and each folder's space are keyed by this address, so a
18
+ * new default would sign everyone out and make publish create a new space each time (docs/domain-move.md).
19
+ */
20
+ const DEFAULT_API_URL = "https://api.cloudtifact.com";
21
+ const REPO_CONFIG_FILE = ".cloudtifact.json";
22
+ function homeDir(env = process.env) {
23
+ return env.CLOUDTIFACT_HOME || os.homedir();
24
+ }
25
+ function globalConfigDir(env = process.env) {
26
+ if (env.CLOUDTIFACT_CONFIG_DIR) return env.CLOUDTIFACT_CONFIG_DIR;
27
+ const xdg = env.XDG_CONFIG_HOME || path.join(homeDir(env), ".config");
28
+ return path.join(xdg, "cloudtifact");
29
+ }
30
+ function globalConfigPath(env = process.env) {
31
+ return path.join(globalConfigDir(env), "config.json");
32
+ }
33
+ async function readGlobalConfig(env = process.env) {
34
+ const file = globalConfigPath(env);
35
+ if (!existsSync(file)) return {};
36
+ try {
37
+ const data = JSON.parse(await readFile(file, "utf8"));
38
+ return data && typeof data === "object" ? data : {};
39
+ } catch {
40
+ throw new Error(`Could not parse ${file}. Fix or delete it, then run \`cloudy login\`.`);
41
+ }
42
+ }
43
+ async function writeGlobalConfig(config, env = process.env) {
44
+ const dir = globalConfigDir(env);
45
+ await mkdir(dir, {
46
+ recursive: true,
47
+ mode: 448
48
+ });
49
+ const file = globalConfigPath(env);
50
+ await writeFile(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 384 });
51
+ await chmod(file, 384);
52
+ }
53
+ async function clearGlobalConfig(env = process.env) {
54
+ await rm(globalConfigPath(env), { force: true });
55
+ }
56
+ /** env CLOUDTIFACT_API_URL > config file > default. */
57
+ function resolveApiUrl(config, env = process.env) {
58
+ return (env.CLOUDTIFACT_API_URL || config.apiUrl || "https://api.cloudtifact.com").replace(/\/+$/, "");
59
+ }
60
+ /** The API the saved token was issued by: the apiUrl saved with it (`login` always saves both), else the default. */
61
+ function tokenApiUrl(config) {
62
+ return (config.apiUrl || "https://api.cloudtifact.com").replace(/\/+$/, "");
63
+ }
64
+ /**
65
+ * The saved token, but only for the API it came from. CLOUDTIFACT_API_URL can point the CLI at another API; the
66
+ * token is never sent there (that API could keep it and use it against ours). For another API you're signed out.
67
+ */
68
+ function savedTokenFor(config, apiUrl) {
69
+ return config.token && sameApi(tokenApiUrl(config), apiUrl) ? config.token : void 0;
70
+ }
71
+ function sameApi(a, b) {
72
+ const norm = (u) => {
73
+ try {
74
+ return new URL(u).href.replace(/\/+$/, "");
75
+ } catch {
76
+ return u.replace(/\/+$/, "");
77
+ }
78
+ };
79
+ return norm(a) === norm(b);
80
+ }
81
+ const sameAccount = (a, b) => a.handle === b.handle && sameApi(a.apiUrl, b.apiUrl);
82
+ /** The active account (the top-level fields), if signed in. Very old configs saved a token without a handle: "". */
83
+ function activeAccount(config) {
84
+ if (!config.token) return void 0;
85
+ const { token, handle = "", workspace } = config;
86
+ return {
87
+ apiUrl: tokenApiUrl(config),
88
+ token,
89
+ handle,
90
+ ...workspace ? { workspace } : {}
91
+ };
92
+ }
93
+ /** Every signed-in account, the active one first. Configs from before `accounts` hold just the active one. */
94
+ function accountsOf(config) {
95
+ const active = activeAccount(config);
96
+ const others = (config.accounts ?? []).filter((a) => !active || !sameAccount(a, active));
97
+ return active ? [active, ...others] : others;
98
+ }
99
+ /** Adds or updates an account and makes it the active one. */
100
+ function withActiveAccount(config, account) {
101
+ const { apiUrl, token, handle, workspace } = account;
102
+ const others = accountsOf(config).filter((a) => !sameAccount(a, account));
103
+ const { workspace: _w, ...rest } = config;
104
+ return {
105
+ ...rest,
106
+ apiUrl,
107
+ token,
108
+ handle,
109
+ ...workspace ? { workspace } : {},
110
+ accounts: [account, ...others]
111
+ };
112
+ }
113
+ /** Updates an account in place (its default workspace, say), active or not. */
114
+ function withAccountUpdated(config, account) {
115
+ const active = activeAccount(config);
116
+ if (active && sameAccount(active, account)) return withActiveAccount(config, account);
117
+ return {
118
+ ...config,
119
+ accounts: accountsOf(config).map((a) => sameAccount(a, account) ? account : a)
120
+ };
121
+ }
122
+ /** Forgets an account. If it was the active one, the next signed-in account becomes active. */
123
+ function withoutAccount(config, account) {
124
+ const left = accountsOf(config).filter((a) => !sameAccount(a, account));
125
+ const directories = Object.fromEntries(Object.entries(config.directories ?? {}).filter(([, h]) => h !== account.handle || left.some((a) => a.handle === h)));
126
+ const { apiUrl: _a, token: _t, handle: _h, workspace: _w, accounts: _l, directories: _d, ...rest } = config;
127
+ const base = {
128
+ ...rest,
129
+ ...Object.keys(directories).length ? { directories } : {}
130
+ };
131
+ const [next] = left;
132
+ return next ? withActiveAccount({
133
+ ...base,
134
+ accounts: left
135
+ }, next) : base;
136
+ }
137
+ /** The account a folder is bound to (`cloudy switch <handle> --here`): the nearest bound folder above `from`. */
138
+ function boundHandle(config, from = process.cwd()) {
139
+ const dirs = config.directories ?? {};
140
+ let dir = path.resolve(from);
141
+ for (;;) {
142
+ const handle = dirs[dir];
143
+ if (handle) return {
144
+ handle,
145
+ dir
146
+ };
147
+ const parent = path.dirname(dir);
148
+ if (parent === dir) return null;
149
+ dir = parent;
150
+ }
151
+ }
152
+ /** The folder `switch --here` binds: the repo root (or git root) above `from`, else `from`. */
153
+ function bindingRoot(from = process.cwd()) {
154
+ return findInitRoot(from);
155
+ }
156
+ /** Walks up from `from` to the nearest directory holding .cloudtifact.json. */
157
+ function findRepoRoot(from = process.cwd()) {
158
+ let dir = path.resolve(from);
159
+ for (;;) {
160
+ if (existsSync(path.join(dir, ".cloudtifact.json"))) return dir;
161
+ const parent = path.dirname(dir);
162
+ if (parent === dir) return null;
163
+ dir = parent;
164
+ }
165
+ }
166
+ /** Where `init` should write: the git root above `from`, else `from`. */
167
+ function findInitRoot(from = process.cwd()) {
168
+ let dir = path.resolve(from);
169
+ for (;;) {
170
+ if (existsSync(path.join(dir, ".git")) || existsSync(path.join(dir, ".cloudtifact.json"))) return dir;
171
+ const parent = path.dirname(dir);
172
+ if (parent === dir) return path.resolve(from);
173
+ dir = parent;
174
+ }
175
+ }
176
+ /**
177
+ * The project work belongs to, recorded on each version: CLOUDTIFACT_PROJECT, else the name of the git repo above
178
+ * `from` (a worktree counts as its main repo), else null.
179
+ */
180
+ function projectName(from = process.cwd(), env = process.env) {
181
+ const named = env.CLOUDTIFACT_PROJECT?.trim();
182
+ if (named) return named.slice(0, 100);
183
+ let dir = path.resolve(from);
184
+ for (;;) {
185
+ const git = path.join(dir, ".git");
186
+ if (existsSync(git)) {
187
+ try {
188
+ const m = /^gitdir:\s*(.+)$/m.exec(readFileSync(git, "utf8"));
189
+ const main = m?.[1] ? /^(.*)[\\/]\.git[\\/]worktrees[\\/]/.exec(m[1].trim()) : null;
190
+ if (main?.[1]) return path.basename(main[1]);
191
+ } catch {}
192
+ return path.basename(dir);
193
+ }
194
+ const parent = path.dirname(dir);
195
+ if (parent === dir) return null;
196
+ dir = parent;
197
+ }
198
+ }
199
+ function parseRepoConfig(raw, file = REPO_CONFIG_FILE) {
200
+ const bad = (why) => /* @__PURE__ */ new Error(`${file}: ${why}`);
201
+ if (!raw || typeof raw !== "object") throw bad("expected a JSON object");
202
+ const { dir, targets } = raw;
203
+ if (typeof dir !== "string" || !dir) throw bad("\"dir\" must be a non-empty string");
204
+ if (!Array.isArray(targets)) throw bad("\"targets\" must be an array");
205
+ return {
206
+ dir,
207
+ targets: targets.map((t, i) => {
208
+ if (!t || typeof t !== "object" || typeof t.spaceId !== "string") throw bad(`targets[${i}].spaceId must be a string`);
209
+ const { spaceId, label } = t;
210
+ return label ? {
211
+ spaceId,
212
+ label
213
+ } : { spaceId };
214
+ })
215
+ };
216
+ }
217
+ async function readRepoConfig(root) {
218
+ const file = path.join(root, REPO_CONFIG_FILE);
219
+ let raw;
220
+ try {
221
+ raw = JSON.parse(await readFile(file, "utf8"));
222
+ } catch (err) {
223
+ throw new Error(`Could not read ${file}: ${err.message}`);
224
+ }
225
+ return parseRepoConfig(raw, file);
226
+ }
227
+ async function writeRepoConfig(root, config) {
228
+ await writeFile(path.join(root, REPO_CONFIG_FILE), `${JSON.stringify(config, null, 2)}\n`);
229
+ }
230
+ const realOrSelf = (p) => {
231
+ try {
232
+ return realpathSync(p);
233
+ } catch {
234
+ return p;
235
+ }
236
+ };
237
+ async function loadRepo(from = process.cwd()) {
238
+ const root = findRepoRoot(from);
239
+ if (!root) throw new Error(`No ${REPO_CONFIG_FILE} found here or above. Run \`cloudy init\` first.`);
240
+ const config = await readRepoConfig(root);
241
+ const docsDir = path.resolve(root, config.dir);
242
+ const rel = path.relative(realOrSelf(root), realOrSelf(docsDir));
243
+ if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`"dir" in ${REPO_CONFIG_FILE} must be inside the repo (got "${config.dir}")`);
244
+ return {
245
+ root,
246
+ config,
247
+ docsDir
248
+ };
249
+ }
250
+ //#endregion
15
251
  //#region ../contract/src/domains.ts
16
252
  /**
17
253
  * Every public Cloudy address that code bakes in (CLI default, install command, landing and
18
- * docs links, badges). One place, so picking the real domain is a one-line change:
254
+ * docs links, badges). One place:
19
255
  *
20
- * export const PUBLIC_DOMAIN: string | null = "cloudtifact.com";
256
+ * export const PUBLIC_DOMAIN: string | null = "usecloudy.ai";
21
257
  *
22
- * With a domain set, our own hosts are api.<domain>, app.<domain> and the bare domain for the landing
23
- * site. What users publish (artifact pages and live apps) runs other people's HTML and JS, so it lives
258
+ * PUBLIC_DOMAIN is the site and app domain: app.<domain> and the bare domain for the landing site. The API lives on
259
+ * SERVICE_DOMAIN instead, which never moves (the domain move, docs/domain-move.md): the CLI keys saved sign-ins and
260
+ * each folder's space by its API address, so moving it would break every old CLI. The MCP server is given out as
261
+ * mcp.<PUBLIC_DOMAIN> and also answers, in place and forever, on mcp.<SERVICE_DOMAIN>: connectors are signed in to
262
+ * the address they were added with. What users publish (artifact pages and live apps) runs other people's HTML and JS, so it lives
24
263
  * on a separate registrable domain, USER_CONTENT_DOMAIN, the way GitHub uses githubusercontent.com:
25
264
  * pages at the bare user-content domain (/<id>/, /t/<token>/), apps at <slug>.<user-content domain>.
26
265
  * Then a published page can never read or set cookies for the app or for Clerk. While PUBLIC_DOMAIN is
@@ -29,9 +268,20 @@ import { pipeline } from "node:stream/promises";
29
268
  * Deploy-time values (PUBLIC_API_URL, WEB_URL, ... in each wrangler.jsonc) are separate: wrangler
30
269
  * reads JSON, not this file. Update those in the same change (see README "Choosing the domain").
31
270
  */
32
- const PUBLIC_DOMAIN = "cloudtifact.com";
271
+ const PUBLIC_DOMAIN = "usecloudy.ai";
33
272
  /** Separate domain for published pages and live apps. Must not share a registrable domain with PUBLIC_DOMAIN. */
34
- const USER_CONTENT_DOMAIN = "cloudtifact.app";
273
+ const USER_CONTENT_DOMAIN = "cloudy.page";
274
+ /** Where api., admin. and assets. live, forever, and mcp. too for old connectors: programs keep their addresses. */
275
+ const SERVICE_DOMAIN = "cloudtifact.com";
276
+ /**
277
+ * Every site and app domain we serve, new first. During and after the move (docs/domain-move.md) both answer: the old
278
+ * one sends page loads on to the new one and answers everything else in place.
279
+ */
280
+ const OWN_SITE_DOMAINS = ["usecloudy.ai", "cloudtifact.com"];
281
+ /** Every user-content domain we serve (published pages, live apps), new first. Same rule as OWN_SITE_DOMAINS. */
282
+ const OWN_USER_CONTENT_DOMAINS = ["cloudy.page", "cloudtifact.app"];
283
+ OWN_SITE_DOMAINS.map((d) => `https://app.${d}`);
284
+ OWN_USER_CONTENT_DOMAINS.map((d) => `https://${d}`);
35
285
  const WORKERS_DEV = {
36
286
  api: "https://cloudtifact-api.cloudtifact.workers.dev",
37
287
  web: "https://cloudtifact-docs.cloudtifact.workers.dev",
@@ -39,10 +289,10 @@ const WORKERS_DEV = {
39
289
  landing: "https://cloudtifact-landing.cloudtifact.workers.dev",
40
290
  appsHost: USER_CONTENT_DOMAIN
41
291
  };
42
- function urlsFor(domain, userContent = USER_CONTENT_DOMAIN) {
292
+ function urlsFor(domain, userContent = USER_CONTENT_DOMAIN, service = SERVICE_DOMAIN) {
43
293
  if (!domain) return WORKERS_DEV;
44
294
  return {
45
- api: `https://api.${domain}`,
295
+ api: `https://api.${service}`,
46
296
  web: `https://app.${domain}`,
47
297
  content: `https://${userContent}`,
48
298
  landing: `https://${domain}`,
@@ -5786,15 +6036,52 @@ const GUEST_KEY_HEADER = "x-cloudtifact-guest-key";
5786
6036
  const commentImageIdSchema = string().regex(/^[0-9a-f]{32}$/);
5787
6037
  //#endregion
5788
6038
  //#region ../contract/src/public-link.ts
5789
- /** Shared public-page URL rules: space ids, custom public links, leftover `@` paths, and `?v=` pins. */
6039
+ /** Shared public-page URL rules: space ids, custom public links, leftover `@` pins, person `/@handle`, and `?v=` pins. */
5790
6040
  const SPACE_ID_RE = /^[0-9a-z]{10}$/;
5791
- const SPACE_SLUG_RE = /^[a-z0-9]+$/;
6041
+ /** Lowercase letters and numbers, single dashes between them (no dash at either end). */
6042
+ const SPACE_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5792
6043
  const LEGACY_AT_RE = /^([0-9a-z]{10})@([1-9][0-9]{0,8})$/;
5793
6044
  const PIN_RE = /^[1-9][0-9]{0,8}$/;
6045
+ /** Same as handleSchema: 1–39 lowercase letters, digits, dashes, no dash at either end. */
6046
+ const HANDLE_RE = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/;
5794
6047
  const isSpaceId = (s) => SPACE_ID_RE.test(s);
5795
- /** A custom public-link segment: 2–48 lowercase letters and numbers, and not a space id. */
6048
+ /** Dashed names kept for us, refused as custom public links and post links: pages we may want on cloudy.page later. */
6049
+ const DASHED_RESERVED = /* @__PURE__ */ new Set([
6050
+ "about-cloudy",
6051
+ "made-with-cloudy",
6052
+ "sign-in",
6053
+ "sign-up",
6054
+ "log-in",
6055
+ "log-out"
6056
+ ]);
6057
+ /** A custom public-link segment: 2–60 lowercase letters, numbers and single dashes, and not a space id. */
5796
6058
  function looksLikeSlug(s) {
5797
- return s.length >= 2 && s.length <= 48 && SPACE_SLUG_RE.test(s) && !isSpaceId(s);
6059
+ return s.length >= 2 && s.length <= 60 && SPACE_SLUG_RE.test(s) && !isSpaceId(s);
6060
+ }
6061
+ function decodeSeg(seg) {
6062
+ try {
6063
+ return decodeURIComponent(seg);
6064
+ } catch {
6065
+ return null;
6066
+ }
6067
+ }
6068
+ /**
6069
+ * A person-URL path segment: `@` then a handle. `%40handle` is the same as `@handle`. Not a page slug.
6070
+ */
6071
+ function parsePersonHandle(seg) {
6072
+ const s = decodeSeg(seg);
6073
+ if (s === null || !s.startsWith("@")) return null;
6074
+ const handle = s.slice(1);
6075
+ return HANDLE_RE.test(handle) ? handle : null;
6076
+ }
6077
+ /**
6078
+ * `/u/<segment>` as a person (the standard profile URL, `/@handle` is the short one): no dot, and a handle.
6079
+ * Password unlock tokens always contain a dot.
6080
+ */
6081
+ function parsePersonHandleFromU(seg) {
6082
+ const s = decodeSeg(seg);
6083
+ if (s === null || s.includes(".")) return null;
6084
+ return HANDLE_RE.test(s) ? s : null;
5798
6085
  }
5799
6086
  function parseLegacyAt(seg) {
5800
6087
  const m = LEGACY_AT_RE.exec(seg);
@@ -5819,7 +6106,7 @@ const WORKSPACE_ROLES = [
5819
6106
  ];
5820
6107
  //#endregion
5821
6108
  //#region ../contract/src/schemas.ts
5822
- const handleSchema = string().regex(/^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/, "lowercase letters, digits and dashes, 1-39 chars");
6109
+ const handleSchema = string().regex(HANDLE_RE, "lowercase letters, digits and dashes, 1-39 chars");
5823
6110
  const RESERVED_NAMES = /* @__PURE__ */ new Set([
5824
6111
  "about",
5825
6112
  "account",
@@ -5832,7 +6119,11 @@ const RESERVED_NAMES = /* @__PURE__ */ new Set([
5832
6119
  "billing",
5833
6120
  "blog",
5834
6121
  "cloudtifact",
6122
+ "cloudy",
5835
6123
  "docs",
6124
+ "edit",
6125
+ "explore",
6126
+ "feed",
5836
6127
  "guest",
5837
6128
  "help",
5838
6129
  "login",
@@ -5842,6 +6133,7 @@ const RESERVED_NAMES = /* @__PURE__ */ new Set([
5842
6133
  "null",
5843
6134
  "official",
5844
6135
  "owner",
6136
+ "posts",
5845
6137
  "root",
5846
6138
  "security",
5847
6139
  "settings",
@@ -5854,14 +6146,16 @@ const RESERVED_NAMES = /* @__PURE__ */ new Set([
5854
6146
  "support",
5855
6147
  "system",
5856
6148
  "team",
6149
+ "topics",
5857
6150
  "undefined",
6151
+ "usecloudy",
5858
6152
  "www"
5859
6153
  ]);
5860
6154
  const isReservedName = (name) => RESERVED_NAMES.has(name) || name.startsWith("deleted-");
5861
6155
  const RESERVED_NAME_MESSAGE = "that name is reserved; pick another";
5862
6156
  const spaceIdSchema = string().regex(/^[0-9a-z]{10}$/);
5863
6157
  const sha256Schema = string().regex(/^[0-9a-f]{64}$/);
5864
- const spaceSlugSchema = string().min(2).max(48).regex(SPACE_SLUG_RE, "lowercase letters and numbers").refine((s) => !isReservedName(s) && s !== "find" && s !== "ping", { message: RESERVED_NAME_MESSAGE }).refine((s) => !isSpaceId(s), { message: "that name looks like a space id; pick another" });
6158
+ const spaceSlugSchema = string().min(2).max(60).regex(/^[a-z0-9-]+$/, "lowercase letters, numbers and dashes").regex(SPACE_SLUG_RE, "use single dashes, and none at the start or end").refine((s) => !isReservedName(s) && !DASHED_RESERVED.has(s) && s !== "find" && s !== "ping", { message: RESERVED_NAME_MESSAGE }).refine((s) => !isSpaceId(s), { message: "that name looks like a space id; pick another" });
5865
6159
  const spaceSlugPatchSchema = union([_null(), string().transform((s) => s.trim().toLowerCase()).pipe(spaceSlugSchema)]);
5866
6160
  const fileKindSchema = _enum([
5867
6161
  "markdown",
@@ -5939,11 +6233,27 @@ const devLoginOutput = object({
5939
6233
  token: string(),
5940
6234
  user: userSchema
5941
6235
  });
6236
+ object({
6237
+ username: string().trim().min(1).max(100),
6238
+ code: string().trim().min(1).max(100),
6239
+ client: _enum(["app", "web"]).default("app")
6240
+ });
6241
+ const reviewSignInOutput = object({
6242
+ token: string(),
6243
+ user: userSchema
6244
+ });
5942
6245
  /** A one-hour token for the comment panel on published pages: reads a space and reads or posts its comments. */
5943
6246
  const embedTokenOutput = object({
5944
6247
  token: string(),
5945
6248
  expiresAt: number$1()
5946
6249
  });
6250
+ object({ state: string().min(1).max(4096) });
6251
+ const signInCarryOutput = object({
6252
+ ticket: string(),
6253
+ expiresAt: number$1()
6254
+ });
6255
+ object({ ticket: string().min(1).max(200) });
6256
+ const signInCarryRedeemOutput = object({ state: string() });
5947
6257
  object({ token: string().max(200).optional() });
5948
6258
  const createSessionOutput = object({
5949
6259
  token: string(),
@@ -6047,8 +6357,21 @@ const notMePreviewOutput = object({ signIn: signInSchema.omit({
6047
6357
  }).nullable() });
6048
6358
  const preferencesSchema = object({ developerMode: boolean() });
6049
6359
  preferencesSchema.partial();
6050
- object({ handle: handleSchema });
6051
- const emailCategoryIdSchema = _enum([
6360
+ const atLinkChoiceSchema = object({
6361
+ id: string(),
6362
+ name: string()
6363
+ });
6364
+ const atLinkSchema = object({
6365
+ spaceId: string().nullable(),
6366
+ choices: array(atLinkChoiceSchema),
6367
+ searchIndexed: boolean().optional()
6368
+ });
6369
+ object({
6370
+ spaceId: string().nullable().optional(),
6371
+ searchIndexed: boolean().optional()
6372
+ });
6373
+ object({ handle: handleSchema });
6374
+ const emailCategoryIdSchema = _enum([
6052
6375
  "invites",
6053
6376
  "activity",
6054
6377
  "product"
@@ -6077,6 +6400,14 @@ const meOutput = object({
6077
6400
  });
6078
6401
  object({ ticket: string().min(1).max(2e3) });
6079
6402
  object({ userId: string().min(1).max(100) });
6403
+ object({
6404
+ reason: _enum([
6405
+ "spam",
6406
+ "abuse",
6407
+ "other"
6408
+ ]),
6409
+ note: string().trim().max(1e3).optional()
6410
+ });
6080
6411
  object({
6081
6412
  token: string().regex(/^[0-9a-fA-F]{32,200}$/, "an APNs device token, in hex"),
6082
6413
  environment: _enum(["sandbox", "production"])
@@ -6125,9 +6456,14 @@ object({
6125
6456
  slug: workspaceSlugSchema,
6126
6457
  name: string().min(1).max(100)
6127
6458
  });
6459
+ const optionalLine = (max) => string().trim().max(max).transform((s) => s.replace(/\s+/g, " ") || null).nullable().optional();
6128
6460
  object({
6129
6461
  slug: workspaceSlugSchema.optional(),
6130
- name: string().min(1).max(100).optional()
6462
+ name: string().min(1).max(100).optional(),
6463
+ publicPage: boolean().optional(),
6464
+ description: optionalLine(160),
6465
+ topic: optionalLine(40),
6466
+ searchIndexed: boolean().optional()
6131
6467
  });
6132
6468
  const workspaceMemberSchema = object({
6133
6469
  user: userSchema,
@@ -6143,7 +6479,11 @@ const workspaceDetailSchema = workspaceSchema.extend({
6143
6479
  seats: object({
6144
6480
  used: number$1().int(),
6145
6481
  limit: number$1().int()
6146
- }).optional()
6482
+ }).optional(),
6483
+ publicPage: boolean().optional(),
6484
+ description: string().nullable().optional(),
6485
+ topic: string().nullable().optional(),
6486
+ searchIndexed: boolean().optional()
6147
6487
  });
6148
6488
  object({
6149
6489
  handle: handleSchema,
@@ -6154,7 +6494,7 @@ object({
6154
6494
  role: workspaceRoleSchema.default("member"),
6155
6495
  email: email().max(200).optional(),
6156
6496
  maxUses: number$1().int().min(1).max(1e3).nullable().optional(),
6157
- expiresInDays: number$1().int().min(1).max(30).default(7)
6497
+ expiresInDays: number$1().int().min(1).max(30).default(30)
6158
6498
  });
6159
6499
  const workspaceInviteSchema = object({
6160
6500
  id: string(),
@@ -6181,7 +6521,12 @@ const workspaceInvitePreviewOutput = object({
6181
6521
  expiresAt: number$1(),
6182
6522
  alreadyMember: boolean(),
6183
6523
  email: string().nullable().default(null),
6184
- wrongAccount: boolean().default(false)
6524
+ wrongAccount: boolean().default(false),
6525
+ full: object({
6526
+ plan: string(),
6527
+ seats: number$1().int(),
6528
+ owner: userSchema.nullable()
6529
+ }).nullable().default(null)
6185
6530
  });
6186
6531
  const acceptWorkspaceInviteOutput = object({ workspace: myWorkspaceSchema });
6187
6532
  const auditActionSchema = _enum([
@@ -6222,6 +6567,11 @@ const auditActionSchema = _enum([
6222
6567
  "discord.connected",
6223
6568
  "discord.changed",
6224
6569
  "discord.disconnected",
6570
+ "slack.connected",
6571
+ "slack.changed",
6572
+ "slack.disconnected",
6573
+ "slack.stopped",
6574
+ "slack.paused",
6225
6575
  "domain.added",
6226
6576
  "domain.removed",
6227
6577
  "rule.created",
@@ -6241,7 +6591,8 @@ const auditEventSchema = object({
6241
6591
  object({
6242
6592
  before: number().int().positive().optional(),
6243
6593
  beforeId: string().max(64).optional(),
6244
- limit: number().int().min(1).max(200).default(50)
6594
+ limit: number().int().min(1).max(200).default(50),
6595
+ v: number().int().optional()
6245
6596
  });
6246
6597
  const listAuditOutput = object({
6247
6598
  events: array(auditEventSchema),
@@ -6399,6 +6750,7 @@ const spaceSchema = object({
6399
6750
  url: string(),
6400
6751
  shareUrl: string().nullable(),
6401
6752
  slug: string().nullable().optional(),
6753
+ searchIndexed: boolean().optional(),
6402
6754
  kind: _enum([
6403
6755
  "repo",
6404
6756
  "live",
@@ -6479,7 +6831,8 @@ object({
6479
6831
  guestWrites: boolean().optional(),
6480
6832
  viewers: viewersSchema.partial().optional(),
6481
6833
  password: string().min(4).max(200).nullable().optional(),
6482
- slug: spaceSlugPatchSchema.optional()
6834
+ slug: spaceSlugPatchSchema.optional(),
6835
+ searchIndexed: boolean().optional()
6483
6836
  });
6484
6837
  object({ workspace: workspaceSlugSchema });
6485
6838
  const moveSpaceOutput = object({
@@ -6487,6 +6840,11 @@ const moveSpaceOutput = object({
6487
6840
  moved: array(spaceIdSchema)
6488
6841
  });
6489
6842
  object({ password: string().min(1).max(200) });
6843
+ const spacePasswordOutput = object({ password: string().nullable() });
6844
+ const customLinksOutput = object({
6845
+ used: number$1().int(),
6846
+ cap: number$1().int().nullable()
6847
+ });
6490
6848
  const unlockSpaceOutput = object({
6491
6849
  token: string(),
6492
6850
  exp: number$1().int()
@@ -6575,7 +6933,8 @@ const listSpacesOutput = object({ spaces: array(spaceSchema) });
6575
6933
  object({
6576
6934
  q: string().trim().min(1).max(200),
6577
6935
  workspace: workspaceSlugSchema.optional(),
6578
- limit: number().int().min(1).max(50).default(10)
6936
+ limit: number().int().min(1).max(50).default(10),
6937
+ status: _enum(["active", "archived"]).default("active")
6579
6938
  });
6580
6939
  const findSpacesOutput = object({ spaces: array(spaceSchema.extend({
6581
6940
  /** Pages (HTML and Markdown files) in its latest version. */
@@ -6584,7 +6943,7 @@ const findSpacesOutput = object({ spaces: array(spaceSchema.extend({
6584
6943
  score: number$1(),
6585
6944
  /** Close enough to publish into without being told (topicMatch in find.ts). */
6586
6945
  strong: boolean(),
6587
- /** The page whose title matched better than the space's name, if any. */
6946
+ /** The page whose title matched at least as well as the space's name, if any. */
6588
6947
  page: string().nullable(),
6589
6948
  /** That page's path in the space ("plans/pricing.html"), for a link straight to it. */
6590
6949
  pagePath: string().nullable().optional()
@@ -6652,7 +7011,8 @@ const listVersionsOutput = object({ versions: array(versionSchema) });
6652
7011
  const getVersionOutput = object({
6653
7012
  version: versionSchema,
6654
7013
  files: array(fileEntrySchema),
6655
- diff: diffSchema
7014
+ diff: diffSchema,
7015
+ pagePictures: record(string(), string()).optional()
6656
7016
  });
6657
7017
  const getFileOutput = object({
6658
7018
  versionNumber: number$1().int(),
@@ -6971,6 +7331,7 @@ const AGENT_NAMES = {
6971
7331
  opencode: "OpenCode",
6972
7332
  cli: "CLI",
6973
7333
  discord: "Discord",
7334
+ slack: "Slack",
6974
7335
  mobile: "the mobile app",
6975
7336
  claude: "Claude",
6976
7337
  chatgpt: "ChatGPT",
@@ -6983,6 +7344,68 @@ const agentLabel = (via) => AGENT_NAMES[via] ?? via;
6983
7344
  * hand ("cli"), or our own mobile app ("mobile"). Their reads count as reading, and notifications don't add "via ...".
6984
7345
  */
6985
7346
  const isPersonVia = (via) => via === null || via === "cli" || via === "mobile";
7347
+ const slackSpaceSchema = object({
7348
+ id: string(),
7349
+ name: string(),
7350
+ visibility: visibilitySchema
7351
+ });
7352
+ const slackSpaceIds = array(string()).min(1).max(500);
7353
+ const slackConnectRequestOutput = object({
7354
+ userCode: string(),
7355
+ status: _enum([
7356
+ "pending",
7357
+ "approved",
7358
+ "denied",
7359
+ "expired"
7360
+ ]),
7361
+ expiresAt: number$1(),
7362
+ teamName: string(),
7363
+ channelName: string(),
7364
+ isPrivate: boolean(),
7365
+ askedBy: string(),
7366
+ workspaces: array(object({
7367
+ slug: string(),
7368
+ name: string(),
7369
+ canShare: boolean(),
7370
+ following: array(string()),
7371
+ spaces: array(slackSpaceSchema)
7372
+ })),
7373
+ others: number$1().int(),
7374
+ problem: _enum([
7375
+ "shared",
7376
+ "removed",
7377
+ "archived"
7378
+ ]).nullable()
7379
+ });
7380
+ object({
7381
+ approve: boolean(),
7382
+ workspaces: array(object({
7383
+ slug: string(),
7384
+ spaceIds: slackSpaceIds
7385
+ })).max(50).default([])
7386
+ });
7387
+ const slackChannelSchema = object({
7388
+ id: string(),
7389
+ teamName: string(),
7390
+ channelName: string().nullable(),
7391
+ isPrivate: boolean(),
7392
+ stopped: _enum([
7393
+ "shared",
7394
+ "removed",
7395
+ "archived"
7396
+ ]).nullable(),
7397
+ needsApprover: boolean(),
7398
+ spaces: number$1().int(),
7399
+ spaceIds: array(string()).optional(),
7400
+ addedBy: userSchema.nullable(),
7401
+ createdAt: number$1()
7402
+ });
7403
+ const listSlackChannelsOutput = object({
7404
+ installUrl: string(),
7405
+ channels: array(slackChannelSchema),
7406
+ spaces: array(slackSpaceSchema).optional()
7407
+ });
7408
+ object({ spaceIds: slackSpaceIds });
6986
7409
  const discordId = string().regex(/^\d{5,25}$/);
6987
7410
  const discordName = string().trim().min(1).max(100);
6988
7411
  const discordPersonSchema = object({
@@ -7206,7 +7629,8 @@ const spacePageOutput = object({
7206
7629
  revisions: record(string(), array(commentRevisionSchema)),
7207
7630
  discord: array(discordLinkSchema),
7208
7631
  muted: boolean().nullable().optional(),
7209
- mentionPeople: array(userSchema).nullable().optional()
7632
+ mentionPeople: array(userSchema).nullable().optional(),
7633
+ pagePictures: record(string(), string()).optional()
7210
7634
  }).nullable()
7211
7635
  });
7212
7636
  //#endregion
@@ -7559,13 +7983,16 @@ const customDomainStatusSchema = _enum([
7559
7983
  ]);
7560
7984
  const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
7561
7985
  /** Hosts nobody may connect: ours, and the shared hosting ones a customer can't own. */
7562
- const NOT_CONNECTABLE = [
7986
+ const NOT_CONNECTABLE = [.../* @__PURE__ */ new Set([
7563
7987
  USER_CONTENT_DOMAIN,
7564
- "cloudtifact.com",
7988
+ "usecloudy.ai",
7989
+ SERVICE_DOMAIN,
7990
+ ...OWN_SITE_DOMAINS,
7991
+ ...OWN_USER_CONTENT_DOMAINS,
7565
7992
  "workers.dev",
7566
7993
  "pages.dev",
7567
7994
  "localhost"
7568
- ].filter(Boolean);
7995
+ ])].filter(Boolean);
7569
7996
  /** Lowercased, trimmed, without a scheme, path or trailing dot: what someone pasted, as a hostname. */
7570
7997
  function normalizeHostname(input) {
7571
7998
  let h = input.trim().toLowerCase();
@@ -7814,10 +8241,14 @@ function createClient(opts) {
7814
8241
  devLogin: (input) => call("POST", "/v1/auth/dev-login", devLoginOutput, input),
7815
8242
  createEmbedToken: () => call("POST", "/v1/auth/embed-token", embedTokenOutput),
7816
8243
  createVisitorLink: () => call("POST", "/v1/auth/visitor-link", embedTokenOutput),
8244
+ createSignInCarry: (state) => call("POST", "/v1/auth/carry", signInCarryOutput, { state }),
8245
+ redeemSignInCarry: (ticket) => call("POST", "/v1/auth/carry/redeem", signInCarryRedeemOutput, { ticket }),
7817
8246
  /** With the identity provider's session token as this client's token: swaps it for a browser sign-in. */
7818
8247
  createSession: (input = {}) => call("POST", "/v1/sessions", createSessionOutput, input),
7819
8248
  me: () => call("GET", "/v1/me", meOutput),
7820
8249
  updatePreferences: (input) => call("PATCH", "/v1/me/preferences", preferencesSchema, input),
8250
+ atLink: () => call("GET", "/v1/me/at-link", atLinkSchema),
8251
+ updateAtLink: (input) => call("PUT", "/v1/me/at-link", atLinkSchema, input),
7821
8252
  emailPreferences: () => call("GET", "/v1/me/email-preferences", emailPreferencesSchema),
7822
8253
  updateEmailPreferences: (input) => call("PATCH", "/v1/me/email-preferences", emailPreferencesSchema, input),
7823
8254
  notificationSettings: () => call("GET", "/v1/me/notifications", notificationSettingsSchema),
@@ -7840,6 +8271,12 @@ function createClient(opts) {
7840
8271
  cancelDeletionFromLink: (ticket) => send("POST", "/v1/auth/cancel-deletion", { ticket }),
7841
8272
  blockUser: (userId) => send("POST", "/v1/me/blocks", { userId }),
7842
8273
  unblockUser: (userId) => send("DELETE", `/v1/me/blocks/${enc(userId)}`),
8274
+ /** Reports a comment to Cloudy's staff. */
8275
+ reportComment: (id, input) => send("POST", `/v1/comments/${enc(id)}/report`, input),
8276
+ /** Reports a whole space (what its pages show) to Cloudy's staff. */
8277
+ reportSpace: (id, input) => send("POST", `${space(id)}/report`, input),
8278
+ /** App Review's sign-in: works only for the review accounts the server names. */
8279
+ reviewSignIn: (input) => call("POST", "/v1/auth/review-sign-in", reviewSignInOutput, input),
7843
8280
  registerPushDevice: (input) => send("POST", "/v1/me/push-devices", input),
7844
8281
  unregisterPushDevice: (token) => send("DELETE", `/v1/me/push-devices/${enc(token)}`),
7845
8282
  cliLoginStart: (input = {}) => call("POST", "/v1/auth/cli/start", cliLoginStartOutput, input),
@@ -7874,6 +8311,7 @@ function createClient(opts) {
7874
8311
  const params = new URLSearchParams({ q: query.q });
7875
8312
  if (query.workspace) params.set("workspace", query.workspace);
7876
8313
  if (query.limit) params.set("limit", String(query.limit));
8314
+ if (query.status) params.set("status", query.status);
7877
8315
  return call("GET", `/v1/spaces/find?${params}`, findSpacesOutput);
7878
8316
  },
7879
8317
  createSpace: (input) => call("POST", "/v1/spaces", spaceSchema, input),
@@ -7898,6 +8336,8 @@ function createClient(opts) {
7898
8336
  if (query.v) q.set("v", query.v);
7899
8337
  return call("GET", `${space(id)}/page${q.size ? `?${q}` : ""}`, spacePageOutput);
7900
8338
  },
8339
+ spacePassword: (id) => call("GET", `${space(id)}/password`, spacePasswordOutput),
8340
+ customLinks: (id) => call("GET", `${space(id)}/custom-links`, customLinksOutput),
7901
8341
  unlockSpace: (id, input) => call("POST", `${space(id)}/unlock`, unlockSpaceOutput, input),
7902
8342
  recordView: (id, input) => call("POST", `${space(id)}/views`, null, input),
7903
8343
  seen: (id, input) => call("POST", `${space(id)}/seen`, null, input),
@@ -8021,6 +8461,11 @@ function createClient(opts) {
8021
8461
  listDiscordChannels: (slug) => call("GET", `/v1/workspaces/${enc(slug)}/discord`, listDiscordChannelsOutput),
8022
8462
  setDiscordChannel: (slug, channelId, input) => send("PUT", `/v1/workspaces/${enc(slug)}/discord/${enc(channelId)}`, input),
8023
8463
  disconnectDiscordChannel: (slug, channelId) => send("DELETE", `/v1/workspaces/${enc(slug)}/discord/${enc(channelId)}`),
8464
+ slackConnectRequest: (userCode) => call("GET", `/v1/slack/connects/${enc(userCode)}`, slackConnectRequestOutput),
8465
+ slackConnectDecide: (userCode, input) => send("POST", `/v1/slack/connects/${enc(userCode)}/decide`, input),
8466
+ listSlackChannels: (slug) => call("GET", `/v1/workspaces/${enc(slug)}/slack`, listSlackChannelsOutput),
8467
+ setSlackChannel: (slug, id, input) => send("PUT", `/v1/workspaces/${enc(slug)}/slack/${enc(id)}`, input),
8468
+ disconnectSlackChannel: (slug, id) => send("DELETE", `/v1/workspaces/${enc(slug)}/slack/${enc(id)}`),
8024
8469
  listDiscordLinks: (spaceId) => call("GET", `/v1/spaces/${enc(spaceId)}/discord`, listDiscordLinksOutput),
8025
8470
  discordChat: (spaceId, threadId, all = false) => call("GET", `/v1/spaces/${enc(spaceId)}/discord/${enc(threadId)}${all ? "?all=1" : ""}`, discordChatOutput),
8026
8471
  unlinkDiscordThread: (spaceId, threadId) => send("DELETE", `/v1/spaces/${enc(spaceId)}/discord/${enc(threadId)}`),
@@ -8045,8 +8490,8 @@ function createClient(opts) {
8045
8490
  if (query.before) q.set("before", String(query.before));
8046
8491
  if (query.before && query.beforeId) q.set("beforeId", query.beforeId);
8047
8492
  if (query.limit) q.set("limit", String(query.limit));
8048
- const tail = q.size ? `?${q}` : "";
8049
- return call("GET", `/v1/workspaces/${enc(slug)}/audit${tail}`, listAuditOutput);
8493
+ q.set("v", String(2));
8494
+ return call("GET", `/v1/workspaces/${enc(slug)}/audit?${q}`, listAuditOutput);
8050
8495
  }
8051
8496
  };
8052
8497
  }
@@ -8595,365 +9040,133 @@ function* encodeListItemValueLines(value, depth, options) {
8595
9040
  if (isEncodablePrimitive(value)) yield indentedListItem(depth, encodePrimitive(value, options.delimiter), options.indentSize);
8596
9041
  else if (isJsonArray(value)) if (isArrayOfPrimitives(value)) yield indentedListItem(depth, encodeInlineArrayLine(value, options.delimiter), options.indentSize);
8597
9042
  else {
8598
- yield indentedListItem(depth, formatHeader(value.length, { delimiter: options.delimiter }), options.indentSize);
8599
- for (const item of value) yield* encodeListItemValueLines(item, depth + 1, options);
8600
- }
8601
- else if (isJsonObject(value)) yield* encodeObjectAsListItemLines(value, depth, options);
8602
- }
8603
- function indentedLine(depth, content, indentSize) {
8604
- return " ".repeat(indentSize * depth) + content;
8605
- }
8606
- function indentedListItem(depth, content, indentSize) {
8607
- return indentedLine(depth, "- " + content, indentSize);
8608
- }
8609
- /**
8610
- * Applies a replacer function to a `JsonValue` and all its descendants.
8611
- *
8612
- * The replacer is called for the root (key='', path=[]), every object property
8613
- * (key = property name), and every array element (key = string index).
8614
- */
8615
- function applyReplacer(root, replacer) {
8616
- const replacedRoot = replacer("", root, []);
8617
- if (replacedRoot === void 0) return transformChildren(root, replacer, []);
8618
- return transformReplaced(root, replacedRoot, replacer, []);
8619
- }
8620
- /**
8621
- * Resolves a replacer's (non-`undefined`) return value at a single position.
8622
- *
8623
- * A `RawString` only stands in for a primitive: returned for an object or
8624
- * array value, it is ignored and the original container is traversed normally.
8625
- */
8626
- function transformReplaced(original, replaced, replacer, path) {
8627
- if (isRawString(replaced) && !isEncodablePrimitive(original)) return transformChildren(original, replacer, path);
8628
- return transformChildren(normalizeValue(replaced), replacer, path);
8629
- }
8630
- function transformChildren(value, replacer, path) {
8631
- if (isJsonObject(value)) return transformObject(value, replacer, path);
8632
- if (isJsonArray(value)) return transformArray(value, replacer, path);
8633
- return value;
8634
- }
8635
- function transformObject(obj, replacer, path) {
8636
- const result = {};
8637
- for (const [key, value] of Object.entries(obj)) {
8638
- const childPath = [...path, key];
8639
- const replacedValue = replacer(key, value, childPath);
8640
- if (replacedValue === void 0) continue;
8641
- setOwnProperty(result, key, transformReplaced(value, replacedValue, replacer, childPath));
8642
- }
8643
- return result;
8644
- }
8645
- function transformArray(arr, replacer, path) {
8646
- const result = [];
8647
- for (let i = 0; i < arr.length; i++) {
8648
- const value = arr[i];
8649
- const childPath = [...path, i];
8650
- const replacedValue = replacer(String(i), value, childPath);
8651
- if (replacedValue === void 0) continue;
8652
- result.push(transformReplaced(value, replacedValue, replacer, childPath));
8653
- }
8654
- return result;
8655
- }
8656
- /**
8657
- * Encodes a JavaScript value into TOON format string.
8658
- *
8659
- * @param input Any JavaScript value (objects, arrays, primitives)
8660
- * @param options Optional encoding configuration
8661
- * @returns TOON formatted string
8662
- *
8663
- * @example
8664
- * ```ts
8665
- * encode({ name: 'Ada', age: 30 })
8666
- * // name: Ada
8667
- * // age: 30
8668
- *
8669
- * encode({ users: [{ id: 1 }, { id: 2 }] })
8670
- * // users[2]{id}:
8671
- * // 1
8672
- * // 2
8673
- *
8674
- * encode({ tags: [] })
8675
- * // tags: []
8676
- *
8677
- * encode(data, { indentSize: 4 })
8678
- * ```
8679
- */
8680
- function encode(input, options) {
8681
- return Array.from(encodeLines(input, options)).join("\n");
8682
- }
8683
- /**
8684
- * Encodes a JavaScript value into TOON format as a sequence of lines.
8685
- *
8686
- * This function yields TOON lines one at a time without building the full string,
8687
- * making it suitable for streaming large outputs to files, HTTP responses, or process stdout.
8688
- *
8689
- * @param input Any JavaScript value (objects, arrays, primitives)
8690
- * @param options Optional encoding configuration
8691
- * @returns Iterable of TOON lines (without trailing newlines)
8692
- *
8693
- * @example
8694
- * ```ts
8695
- * // Stream to stdout
8696
- * for (const line of encodeLines({ name: 'Ada', age: 30 })) {
8697
- * console.log(line)
8698
- * }
8699
- *
8700
- * // Collect to array
8701
- * const lines = Array.from(encodeLines(data))
8702
- *
8703
- * // Equivalent to encode()
8704
- * const toonString = Array.from(encodeLines(data, options)).join('\n')
8705
- * ```
8706
- */
8707
- function encodeLines(input, options) {
8708
- const normalizedValue = normalizeValue(input);
8709
- const resolvedOptions = resolveOptions(options);
8710
- return encodeJsonValue(resolvedOptions.replacer ? applyReplacer(normalizedValue, resolvedOptions.replacer) : normalizedValue, resolvedOptions, 0);
8711
- }
8712
- function resolveOptions(options) {
8713
- const delimiter = options?.delimiter ?? DEFAULT_DELIMITER;
8714
- assertValidDelimiter(delimiter);
8715
- return {
8716
- indentSize: options?.indentSize ?? options?.indent ?? 2,
8717
- delimiter,
8718
- replacer: options?.replacer
8719
- };
8720
- }
8721
- //#endregion
8722
- //#region ../contract/src/toon.ts
8723
- const toToon = (value) => encode(value);
8724
- //#endregion
8725
- //#region src/config.ts
8726
- const DEFAULT_API_URL = PUBLIC_URLS.api;
8727
- const REPO_CONFIG_FILE = ".cloudtifact.json";
8728
- function homeDir(env = process.env) {
8729
- return env.CLOUDTIFACT_HOME || os.homedir();
8730
- }
8731
- function globalConfigDir(env = process.env) {
8732
- if (env.CLOUDTIFACT_CONFIG_DIR) return env.CLOUDTIFACT_CONFIG_DIR;
8733
- const xdg = env.XDG_CONFIG_HOME || path.join(homeDir(env), ".config");
8734
- return path.join(xdg, "cloudtifact");
8735
- }
8736
- function globalConfigPath(env = process.env) {
8737
- return path.join(globalConfigDir(env), "config.json");
8738
- }
8739
- async function readGlobalConfig(env = process.env) {
8740
- const file = globalConfigPath(env);
8741
- if (!existsSync(file)) return {};
8742
- try {
8743
- const data = JSON.parse(await readFile(file, "utf8"));
8744
- return data && typeof data === "object" ? data : {};
8745
- } catch {
8746
- throw new Error(`Could not parse ${file}. Fix or delete it, then run \`cloudy login\`.`);
8747
- }
8748
- }
8749
- async function writeGlobalConfig(config, env = process.env) {
8750
- const dir = globalConfigDir(env);
8751
- await mkdir(dir, {
8752
- recursive: true,
8753
- mode: 448
8754
- });
8755
- const file = globalConfigPath(env);
8756
- await writeFile(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 384 });
8757
- await chmod(file, 384);
8758
- }
8759
- async function clearGlobalConfig(env = process.env) {
8760
- await rm(globalConfigPath(env), { force: true });
8761
- }
8762
- /** env CLOUDTIFACT_API_URL > config file > default. */
8763
- function resolveApiUrl(config, env = process.env) {
8764
- return (env.CLOUDTIFACT_API_URL || config.apiUrl || DEFAULT_API_URL).replace(/\/+$/, "");
8765
- }
8766
- /** The API the saved token was issued by: the apiUrl saved with it (`login` always saves both), else the default. */
8767
- function tokenApiUrl(config) {
8768
- return (config.apiUrl || DEFAULT_API_URL).replace(/\/+$/, "");
8769
- }
8770
- /**
8771
- * The saved token, but only for the API it came from. CLOUDTIFACT_API_URL can point the CLI at another API; the
8772
- * token is never sent there (that API could keep it and use it against ours). For another API you're signed out.
8773
- */
8774
- function savedTokenFor(config, apiUrl) {
8775
- return config.token && sameApi(tokenApiUrl(config), apiUrl) ? config.token : void 0;
8776
- }
8777
- function sameApi(a, b) {
8778
- const norm = (u) => {
8779
- try {
8780
- return new URL(u).href.replace(/\/+$/, "");
8781
- } catch {
8782
- return u.replace(/\/+$/, "");
8783
- }
8784
- };
8785
- return norm(a) === norm(b);
8786
- }
8787
- const sameAccount = (a, b) => a.handle === b.handle && sameApi(a.apiUrl, b.apiUrl);
8788
- /** The active account (the top-level fields), if signed in. Very old configs saved a token without a handle: "". */
8789
- function activeAccount(config) {
8790
- if (!config.token) return void 0;
8791
- const { token, handle = "", workspace } = config;
8792
- return {
8793
- apiUrl: tokenApiUrl(config),
8794
- token,
8795
- handle,
8796
- ...workspace ? { workspace } : {}
8797
- };
8798
- }
8799
- /** Every signed-in account, the active one first. Configs from before `accounts` hold just the active one. */
8800
- function accountsOf(config) {
8801
- const active = activeAccount(config);
8802
- const others = (config.accounts ?? []).filter((a) => !active || !sameAccount(a, active));
8803
- return active ? [active, ...others] : others;
8804
- }
8805
- /** Adds or updates an account and makes it the active one. */
8806
- function withActiveAccount(config, account) {
8807
- const { apiUrl, token, handle, workspace } = account;
8808
- const others = accountsOf(config).filter((a) => !sameAccount(a, account));
8809
- const { workspace: _w, ...rest } = config;
8810
- return {
8811
- ...rest,
8812
- apiUrl,
8813
- token,
8814
- handle,
8815
- ...workspace ? { workspace } : {},
8816
- accounts: [account, ...others]
8817
- };
8818
- }
8819
- /** Updates an account in place (its default workspace, say), active or not. */
8820
- function withAccountUpdated(config, account) {
8821
- const active = activeAccount(config);
8822
- if (active && sameAccount(active, account)) return withActiveAccount(config, account);
8823
- return {
8824
- ...config,
8825
- accounts: accountsOf(config).map((a) => sameAccount(a, account) ? account : a)
8826
- };
8827
- }
8828
- /** Forgets an account. If it was the active one, the next signed-in account becomes active. */
8829
- function withoutAccount(config, account) {
8830
- const left = accountsOf(config).filter((a) => !sameAccount(a, account));
8831
- const directories = Object.fromEntries(Object.entries(config.directories ?? {}).filter(([, h]) => h !== account.handle || left.some((a) => a.handle === h)));
8832
- const { apiUrl: _a, token: _t, handle: _h, workspace: _w, accounts: _l, directories: _d, ...rest } = config;
8833
- const base = {
8834
- ...rest,
8835
- ...Object.keys(directories).length ? { directories } : {}
8836
- };
8837
- const [next] = left;
8838
- return next ? withActiveAccount({
8839
- ...base,
8840
- accounts: left
8841
- }, next) : base;
8842
- }
8843
- /** The account a folder is bound to (`cloudy switch <handle> --here`): the nearest bound folder above `from`. */
8844
- function boundHandle(config, from = process.cwd()) {
8845
- const dirs = config.directories ?? {};
8846
- let dir = path.resolve(from);
8847
- for (;;) {
8848
- const handle = dirs[dir];
8849
- if (handle) return {
8850
- handle,
8851
- dir
8852
- };
8853
- const parent = path.dirname(dir);
8854
- if (parent === dir) return null;
8855
- dir = parent;
9043
+ yield indentedListItem(depth, formatHeader(value.length, { delimiter: options.delimiter }), options.indentSize);
9044
+ for (const item of value) yield* encodeListItemValueLines(item, depth + 1, options);
8856
9045
  }
9046
+ else if (isJsonObject(value)) yield* encodeObjectAsListItemLines(value, depth, options);
8857
9047
  }
8858
- /** The folder `switch --here` binds: the repo root (or git root) above `from`, else `from`. */
8859
- function bindingRoot(from = process.cwd()) {
8860
- return findInitRoot(from);
9048
+ function indentedLine(depth, content, indentSize) {
9049
+ return " ".repeat(indentSize * depth) + content;
8861
9050
  }
8862
- /** Walks up from `from` to the nearest directory holding .cloudtifact.json. */
8863
- function findRepoRoot(from = process.cwd()) {
8864
- let dir = path.resolve(from);
8865
- for (;;) {
8866
- if (existsSync(path.join(dir, ".cloudtifact.json"))) return dir;
8867
- const parent = path.dirname(dir);
8868
- if (parent === dir) return null;
8869
- dir = parent;
8870
- }
9051
+ function indentedListItem(depth, content, indentSize) {
9052
+ return indentedLine(depth, "- " + content, indentSize);
8871
9053
  }
8872
- /** Where `init` should write: the git root above `from`, else `from`. */
8873
- function findInitRoot(from = process.cwd()) {
8874
- let dir = path.resolve(from);
8875
- for (;;) {
8876
- if (existsSync(path.join(dir, ".git")) || existsSync(path.join(dir, ".cloudtifact.json"))) return dir;
8877
- const parent = path.dirname(dir);
8878
- if (parent === dir) return path.resolve(from);
8879
- dir = parent;
8880
- }
9054
+ /**
9055
+ * Applies a replacer function to a `JsonValue` and all its descendants.
9056
+ *
9057
+ * The replacer is called for the root (key='', path=[]), every object property
9058
+ * (key = property name), and every array element (key = string index).
9059
+ */
9060
+ function applyReplacer(root, replacer) {
9061
+ const replacedRoot = replacer("", root, []);
9062
+ if (replacedRoot === void 0) return transformChildren(root, replacer, []);
9063
+ return transformReplaced(root, replacedRoot, replacer, []);
8881
9064
  }
8882
9065
  /**
8883
- * The project work belongs to, recorded on each version: CLOUDTIFACT_PROJECT, else the name of the git repo above
8884
- * `from` (a worktree counts as its main repo), else null.
9066
+ * Resolves a replacer's (non-`undefined`) return value at a single position.
9067
+ *
9068
+ * A `RawString` only stands in for a primitive: returned for an object or
9069
+ * array value, it is ignored and the original container is traversed normally.
8885
9070
  */
8886
- function projectName(from = process.cwd(), env = process.env) {
8887
- const named = env.CLOUDTIFACT_PROJECT?.trim();
8888
- if (named) return named.slice(0, 100);
8889
- let dir = path.resolve(from);
8890
- for (;;) {
8891
- const git = path.join(dir, ".git");
8892
- if (existsSync(git)) {
8893
- try {
8894
- const m = /^gitdir:\s*(.+)$/m.exec(readFileSync(git, "utf8"));
8895
- const main = m?.[1] ? /^(.*)[\\/]\.git[\\/]worktrees[\\/]/.exec(m[1].trim()) : null;
8896
- if (main?.[1]) return path.basename(main[1]);
8897
- } catch {}
8898
- return path.basename(dir);
8899
- }
8900
- const parent = path.dirname(dir);
8901
- if (parent === dir) return null;
8902
- dir = parent;
8903
- }
9071
+ function transformReplaced(original, replaced, replacer, path) {
9072
+ if (isRawString(replaced) && !isEncodablePrimitive(original)) return transformChildren(original, replacer, path);
9073
+ return transformChildren(normalizeValue(replaced), replacer, path);
8904
9074
  }
8905
- function parseRepoConfig(raw, file = REPO_CONFIG_FILE) {
8906
- const bad = (why) => /* @__PURE__ */ new Error(`${file}: ${why}`);
8907
- if (!raw || typeof raw !== "object") throw bad("expected a JSON object");
8908
- const { dir, targets } = raw;
8909
- if (typeof dir !== "string" || !dir) throw bad("\"dir\" must be a non-empty string");
8910
- if (!Array.isArray(targets)) throw bad("\"targets\" must be an array");
8911
- return {
8912
- dir,
8913
- targets: targets.map((t, i) => {
8914
- if (!t || typeof t !== "object" || typeof t.spaceId !== "string") throw bad(`targets[${i}].spaceId must be a string`);
8915
- const { spaceId, label } = t;
8916
- return label ? {
8917
- spaceId,
8918
- label
8919
- } : { spaceId };
8920
- })
8921
- };
9075
+ function transformChildren(value, replacer, path) {
9076
+ if (isJsonObject(value)) return transformObject(value, replacer, path);
9077
+ if (isJsonArray(value)) return transformArray(value, replacer, path);
9078
+ return value;
8922
9079
  }
8923
- async function readRepoConfig(root) {
8924
- const file = path.join(root, REPO_CONFIG_FILE);
8925
- let raw;
8926
- try {
8927
- raw = JSON.parse(await readFile(file, "utf8"));
8928
- } catch (err) {
8929
- throw new Error(`Could not read ${file}: ${err.message}`);
9080
+ function transformObject(obj, replacer, path) {
9081
+ const result = {};
9082
+ for (const [key, value] of Object.entries(obj)) {
9083
+ const childPath = [...path, key];
9084
+ const replacedValue = replacer(key, value, childPath);
9085
+ if (replacedValue === void 0) continue;
9086
+ setOwnProperty(result, key, transformReplaced(value, replacedValue, replacer, childPath));
8930
9087
  }
8931
- return parseRepoConfig(raw, file);
8932
- }
8933
- async function writeRepoConfig(root, config) {
8934
- await writeFile(path.join(root, REPO_CONFIG_FILE), `${JSON.stringify(config, null, 2)}\n`);
9088
+ return result;
8935
9089
  }
8936
- const realOrSelf = (p) => {
8937
- try {
8938
- return realpathSync(p);
8939
- } catch {
8940
- return p;
9090
+ function transformArray(arr, replacer, path) {
9091
+ const result = [];
9092
+ for (let i = 0; i < arr.length; i++) {
9093
+ const value = arr[i];
9094
+ const childPath = [...path, i];
9095
+ const replacedValue = replacer(String(i), value, childPath);
9096
+ if (replacedValue === void 0) continue;
9097
+ result.push(transformReplaced(value, replacedValue, replacer, childPath));
8941
9098
  }
8942
- };
8943
- async function loadRepo(from = process.cwd()) {
8944
- const root = findRepoRoot(from);
8945
- if (!root) throw new Error(`No ${REPO_CONFIG_FILE} found here or above. Run \`cloudy init\` first.`);
8946
- const config = await readRepoConfig(root);
8947
- const docsDir = path.resolve(root, config.dir);
8948
- const rel = path.relative(realOrSelf(root), realOrSelf(docsDir));
8949
- if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`"dir" in ${REPO_CONFIG_FILE} must be inside the repo (got "${config.dir}")`);
9099
+ return result;
9100
+ }
9101
+ /**
9102
+ * Encodes a JavaScript value into TOON format string.
9103
+ *
9104
+ * @param input Any JavaScript value (objects, arrays, primitives)
9105
+ * @param options Optional encoding configuration
9106
+ * @returns TOON formatted string
9107
+ *
9108
+ * @example
9109
+ * ```ts
9110
+ * encode({ name: 'Ada', age: 30 })
9111
+ * // name: Ada
9112
+ * // age: 30
9113
+ *
9114
+ * encode({ users: [{ id: 1 }, { id: 2 }] })
9115
+ * // users[2]{id}:
9116
+ * // 1
9117
+ * // 2
9118
+ *
9119
+ * encode({ tags: [] })
9120
+ * // tags: []
9121
+ *
9122
+ * encode(data, { indentSize: 4 })
9123
+ * ```
9124
+ */
9125
+ function encode(input, options) {
9126
+ return Array.from(encodeLines(input, options)).join("\n");
9127
+ }
9128
+ /**
9129
+ * Encodes a JavaScript value into TOON format as a sequence of lines.
9130
+ *
9131
+ * This function yields TOON lines one at a time without building the full string,
9132
+ * making it suitable for streaming large outputs to files, HTTP responses, or process stdout.
9133
+ *
9134
+ * @param input Any JavaScript value (objects, arrays, primitives)
9135
+ * @param options Optional encoding configuration
9136
+ * @returns Iterable of TOON lines (without trailing newlines)
9137
+ *
9138
+ * @example
9139
+ * ```ts
9140
+ * // Stream to stdout
9141
+ * for (const line of encodeLines({ name: 'Ada', age: 30 })) {
9142
+ * console.log(line)
9143
+ * }
9144
+ *
9145
+ * // Collect to array
9146
+ * const lines = Array.from(encodeLines(data))
9147
+ *
9148
+ * // Equivalent to encode()
9149
+ * const toonString = Array.from(encodeLines(data, options)).join('\n')
9150
+ * ```
9151
+ */
9152
+ function encodeLines(input, options) {
9153
+ const normalizedValue = normalizeValue(input);
9154
+ const resolvedOptions = resolveOptions(options);
9155
+ return encodeJsonValue(resolvedOptions.replacer ? applyReplacer(normalizedValue, resolvedOptions.replacer) : normalizedValue, resolvedOptions, 0);
9156
+ }
9157
+ function resolveOptions(options) {
9158
+ const delimiter = options?.delimiter ?? DEFAULT_DELIMITER;
9159
+ assertValidDelimiter(delimiter);
8950
9160
  return {
8951
- root,
8952
- config,
8953
- docsDir
9161
+ indentSize: options?.indentSize ?? options?.indent ?? 2,
9162
+ delimiter,
9163
+ replacer: options?.replacer
8954
9164
  };
8955
9165
  }
8956
9166
  //#endregion
9167
+ //#region ../contract/src/toon.ts
9168
+ const toToon = (value) => encode(value);
9169
+ //#endregion
8957
9170
  //#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
8958
9171
  /**
8959
9172
  * CommanderError class
@@ -12631,7 +12844,14 @@ async function pushTarget(client, target, initial, opts = {}) {
12631
12844
  let files = initial;
12632
12845
  let uploaded = 0;
12633
12846
  const planAndUpload = async () => {
12634
- const manifest = manifestOf(files);
12847
+ const sent = manifestOf(files);
12848
+ const ours = new Set(sent.map((f) => f.path));
12849
+ const kept = opts.keep ? (await opts.keep()).filter((f) => !ours.has(f.path)) : [];
12850
+ const manifest = [...sent, ...kept.map(({ path, sha256, size }) => ({
12851
+ path,
12852
+ sha256,
12853
+ size
12854
+ }))];
12635
12855
  const bySha = new Map(files.map((f) => [f.sha256, f]));
12636
12856
  const plan = await client.pushPlan(target.spaceId, {
12637
12857
  files: manifest,
@@ -12856,6 +13076,7 @@ async function bundleHtmlFile(file) {
12856
13076
  warnings.push(`skipped ${ref}: ${why}`);
12857
13077
  return null;
12858
13078
  };
13079
+ if (ref.endsWith("/") || ref === ".") return null;
12859
13080
  const rel = resolveInside(fromRel, ref);
12860
13081
  if (!rel) return skip(`outside ${path.basename(base)}/`);
12861
13082
  if (rel === entryRel || picked.has(rel)) return null;
@@ -12915,10 +13136,14 @@ async function publishToSpace(client, spaceId, bundle, opts) {
12915
13136
  ...f,
12916
13137
  path: prefix + f.path
12917
13138
  })) : bundle.files;
13139
+ const keep = opts.keepOthers ? async () => {
13140
+ return (await client.getSpace(spaceId)).latestVersion > 0 ? (await client.getVersion(spaceId, "latest")).files : [];
13141
+ } : void 0;
12918
13142
  return pushTarget(client, { spaceId }, files, {
12919
13143
  message: opts.message,
12920
13144
  prefix,
12921
- project: opts.project
13145
+ project: opts.project,
13146
+ keep
12922
13147
  });
12923
13148
  }
12924
13149
  /**
@@ -12984,7 +13209,7 @@ function lookupArtifact(map, absPath, apiUrl) {
12984
13209
  * /<slug>/, leftover /<id>@<n>/, old /p/<id>/) and signed page links (/t/<token>/, old /s/<token>/).
12985
13210
  * A signed token names its space in its first part; the API still checks access, so reading it
12986
13211
  * without the signing key is safe. Returns null when there is no space in it (a workspace link
12987
- * /w/<slug>, a typo).
13212
+ * /w/<slug>, a person URL /@handle or /u/handle, a typo).
12988
13213
  */
12989
13214
  function spaceIdFrom(input) {
12990
13215
  const ref = input.trim();
@@ -12999,6 +13224,7 @@ function spaceIdFrom(input) {
12999
13224
  return null;
13000
13225
  }
13001
13226
  const [first = "", second = ""] = segments;
13227
+ if (parsePersonHandle(first) || first === "u" && parsePersonHandleFromU(second)) return null;
13002
13228
  if (first === "t") return tokenSpace(second);
13003
13229
  if (first === "s" || first === "r" || first === "p") return idPart(second) ?? (first === "s" ? tokenSpace(second) : null);
13004
13230
  return idPart(first) ?? (looksLikeSlug(first) ? first : null);
@@ -13048,7 +13274,7 @@ function tokenSpace(token) {
13048
13274
  //#endregion
13049
13275
  //#region src/version.ts
13050
13276
  /** This CLI's version, from package.json at build time (tsdown.config.ts). Unbuilt (tests, tsx): "0.0.0-dev". */
13051
- const VERSION = "0.3.2";
13277
+ const VERSION = "0.3.5";
13052
13278
  /**
13053
13279
  * Sent on every API request, so the API can tell which CLI version is calling (and one day tell an old one to
13054
13280
  * upgrade). Without it Node sends just "node", which is what 0.2.2 and older send. The sign-in page shows it too.
@@ -13522,7 +13748,7 @@ function mergeCursorHooks(settings, command = HOOK_COMMAND) {
13522
13748
  status
13523
13749
  };
13524
13750
  }
13525
- async function readJson(file) {
13751
+ async function readJson$1(file) {
13526
13752
  if (!existsSync(file)) return {};
13527
13753
  const text = await readFile(file, "utf8");
13528
13754
  if (!text.trim()) return {};
@@ -13545,7 +13771,7 @@ const hookFiles = (root) => ({
13545
13771
  });
13546
13772
  async function installHook(harness, root) {
13547
13773
  const file = hookFiles(root)[harness];
13548
- const current = await readJson(file);
13774
+ const current = await readJson$1(file);
13549
13775
  if (harness === "cursor") {
13550
13776
  const { settings, status } = mergeCursorHooks(current);
13551
13777
  if (status !== "unchanged") await writeJson(file, settings);
@@ -13632,7 +13858,7 @@ function removeRulesHooks(settings) {
13632
13858
  async function installRulesHooks(harness, root) {
13633
13859
  if (harness === "cursor") return null;
13634
13860
  const file = hookFiles(root)[harness];
13635
- let current = await readJson(file);
13861
+ let current = await readJson$1(file);
13636
13862
  let added = false;
13637
13863
  for (const event of RULES_EVENTS) {
13638
13864
  const r = mergeEventHook(current, event);
@@ -13654,7 +13880,7 @@ async function uninstallRulesHooks(harness, root) {
13654
13880
  file,
13655
13881
  removed: 0
13656
13882
  };
13657
- const { settings, removed } = removeRulesHooks(await readJson(file));
13883
+ const { settings, removed } = removeRulesHooks(await readJson$1(file));
13658
13884
  if (removed) await writeJson(file, settings);
13659
13885
  return {
13660
13886
  harness,
@@ -13665,7 +13891,7 @@ async function uninstallRulesHooks(harness, root) {
13665
13891
  /** Whether the repo's Claude Code or Codex settings run our command when a session starts. False on any doubt. */
13666
13892
  async function hasRulesHooks(root) {
13667
13893
  for (const harness of ["claude", "codex"]) {
13668
- const groups = (await readJson(hookFiles(root)[harness]).catch(() => ({}))).hooks?.SessionStart;
13894
+ const groups = (await readJson$1(hookFiles(root)[harness]).catch(() => ({}))).hooks?.SessionStart;
13669
13895
  if (Array.isArray(groups) && groups.some((g) => g?.hooks?.some((h) => isOurs(h?.command)))) return true;
13670
13896
  }
13671
13897
  return false;
@@ -13912,6 +14138,136 @@ async function revokeSavedToken(client) {
13912
14138
  }
13913
14139
  }
13914
14140
  //#endregion
14141
+ //#region src/plugin-migrate.ts
14142
+ /**
14143
+ * The Claude Code plugin was called `cloudtifact` (cloudtifact@cloudtifact, /cloudtifact:publish) until CLI 0.3.4;
14144
+ * it is `cloudy` now (cloudy@cloudy, /cloudy:publish). Both come from the same marketplace repo, which now calls
14145
+ * itself `cloudy` and still lists the old plugin so old installs keep working. `cloudy skill install` moves an old
14146
+ * install over: it backs up Claude Code's plugin files, uninstalls the old plugin, removes the old marketplace
14147
+ * entry, adds the repo again (Claude Code then registers it as `cloudy`) and installs cloudy@cloudy.
14148
+ *
14149
+ * The order matters: Claude Code won't add a marketplace source it already has under another name, so the old
14150
+ * entry has to go before the new one can be added.
14151
+ */
14152
+ const OLD_PLUGIN = "cloudtifact@cloudtifact";
14153
+ const NEW_PLUGIN = "cloudy@cloudy";
14154
+ const MARKETPLACE_REPO = "Cloudtifact/plugins";
14155
+ /** Runs `claude <args>`. Never throws. Two minutes each: adding a marketplace clones it from GitHub. */
14156
+ const runClaude = (args) => new Promise((resolve) => {
14157
+ execFile("claude", args, {
14158
+ timeout: 12e4,
14159
+ shell: process.platform === "win32",
14160
+ env: process.env
14161
+ }, (err, stdout, stderr) => resolve({
14162
+ ok: !err,
14163
+ out: `${stdout}${stderr}`.trim()
14164
+ }));
14165
+ });
14166
+ async function readJson(file) {
14167
+ try {
14168
+ return JSON.parse(await readFile(file, "utf8"));
14169
+ } catch {
14170
+ return null;
14171
+ }
14172
+ }
14173
+ function claudePaths(home) {
14174
+ const plugins = path.join(home, ".claude", "plugins");
14175
+ return {
14176
+ installed: path.join(plugins, "installed_plugins.json"),
14177
+ marketplaces: path.join(plugins, "known_marketplaces.json"),
14178
+ settings: path.join(home, ".claude", "settings.json")
14179
+ };
14180
+ }
14181
+ /** The old plugin's installs (one per scope), from installed_plugins.json. Empty when it isn't installed. */
14182
+ async function oldClaudePlugin(home) {
14183
+ const json = await readJson(claudePaths(home).installed);
14184
+ const entries = (json?.plugins ?? json)?.[OLD_PLUGIN];
14185
+ return Array.isArray(entries) ? entries : [];
14186
+ }
14187
+ const MANUAL = [
14188
+ ` /plugin uninstall ${OLD_PLUGIN}`,
14189
+ " /plugin marketplace remove cloudtifact",
14190
+ ` /plugin marketplace add ${MARKETPLACE_REPO}`,
14191
+ ` /plugin install ${NEW_PLUGIN}`
14192
+ ];
14193
+ /**
14194
+ * Moves a user-scope install of cloudtifact@cloudtifact to cloudy@cloudy (see the top of this file). Installs in a
14195
+ * project or local scope are left alone and listed with the commands to run there. `check` only reports.
14196
+ */
14197
+ async function moveClaudePlugin(home, opts) {
14198
+ const installs = await oldClaudePlugin(home);
14199
+ if (!installs.length) return {
14200
+ state: "none",
14201
+ lines: []
14202
+ };
14203
+ const user = installs.some((i) => (i.scope ?? "user") === "user");
14204
+ const elsewhere = installs.filter((i) => (i.scope ?? "user") !== "user");
14205
+ const elsewhereLines = elsewhere.length ? [`Claude Code: ${OLD_PLUGIN} is also installed in ${elsewhere.map((i) => i.projectPath ?? i.scope).join(", ")}. In each, run:`, ...MANUAL] : [];
14206
+ if (opts.check || !user) return {
14207
+ state: "manual",
14208
+ lines: [...user ? [`Claude Code: ${OLD_PLUGIN} is installed. It is called ${NEW_PLUGIN} now; run \`cloudy skill install\` to switch.`] : [], ...elsewhereLines]
14209
+ };
14210
+ const run = opts.run ?? runClaude;
14211
+ if (!(await run(["--version"])).ok) return {
14212
+ state: "manual",
14213
+ lines: [`Claude Code: ${OLD_PLUGIN} is installed, but the claude command isn't on PATH. In Claude Code, run:`, ...MANUAL]
14214
+ };
14215
+ const paths = claudePaths(home);
14216
+ const backup = path.join(opts.backupDir, "claude");
14217
+ await mkdir(backup, { recursive: true });
14218
+ for (const f of [
14219
+ paths.installed,
14220
+ paths.marketplaces,
14221
+ paths.settings
14222
+ ]) if (existsSync(f)) await copyFile(f, path.join(backup, path.basename(f)));
14223
+ const steps = [[
14224
+ "plugin",
14225
+ "uninstall",
14226
+ OLD_PLUGIN,
14227
+ "--scope",
14228
+ "user"
14229
+ ]];
14230
+ const known = await readJson(paths.marketplaces) ?? {};
14231
+ const old = known.cloudtifact;
14232
+ const ours = (s) => /cloudtifact\/plugins/i.test(`${s?.repo ?? ""} ${s?.url ?? ""}`);
14233
+ const installed = (await readJson(paths.installed))?.plugins ?? {};
14234
+ const others = Object.keys(installed).filter((k) => k.endsWith("@cloudtifact") && k !== "cloudtifact@cloudtifact");
14235
+ if (old && ours(old.source) && !others.length && !elsewhere.length) steps.push([
14236
+ "plugin",
14237
+ "marketplace",
14238
+ "remove",
14239
+ "cloudtifact"
14240
+ ]);
14241
+ if (!Object.entries(known).some(([name, m]) => name === "cloudy" && ours(m.source))) steps.push([
14242
+ "plugin",
14243
+ "marketplace",
14244
+ "add",
14245
+ MARKETPLACE_REPO
14246
+ ]);
14247
+ if (!installed["cloudy@cloudy"]) steps.push([
14248
+ "plugin",
14249
+ "install",
14250
+ NEW_PLUGIN,
14251
+ "--scope",
14252
+ "user"
14253
+ ]);
14254
+ for (const args of steps) {
14255
+ const r = await run(args);
14256
+ if (!r.ok) return {
14257
+ state: "failed",
14258
+ lines: [
14259
+ `Claude Code: \`claude ${args.join(" ")}\` failed: ${r.out.split("\n").pop() || "no output"}`,
14260
+ `Your plugin settings are backed up in ${backup}. To finish by hand, in Claude Code run:`,
14261
+ ...MANUAL
14262
+ ]
14263
+ };
14264
+ }
14265
+ return {
14266
+ state: "moved",
14267
+ lines: [`Claude Code: replaced ${OLD_PLUGIN} with ${NEW_PLUGIN} (commands are /cloudy:publish, /cloudy:comments, /cloudy:status). Restart Claude Code to load it. Backup: ${backup}`, ...elsewhereLines]
14268
+ };
14269
+ }
14270
+ //#endregion
13915
14271
  //#region src/prompt.ts
13916
14272
  const interactive = () => !!process.stdin.isTTY && !!process.stdout.isTTY;
13917
14273
  async function ask(question, fallback = "") {
@@ -14310,6 +14666,12 @@ const SETTINGS = [
14310
14666
  option: "--guest-comments <on|off>",
14311
14667
  label: "People who are not signed in can comment",
14312
14668
  get: (s) => s.guestComments
14669
+ },
14670
+ {
14671
+ flag: "search",
14672
+ option: "--search <on|off>",
14673
+ label: "Show its pages in search engines",
14674
+ get: (s) => s.searchIndexed ?? false
14313
14675
  }
14314
14676
  ];
14315
14677
  /**
@@ -14338,6 +14700,7 @@ function settingsPatch(opts) {
14338
14700
  if (value === void 0) continue;
14339
14701
  const on = onOff(value, s.option);
14340
14702
  if (s.flag === "pagesShowData") patch.viewers = { dbRead: on };
14703
+ else if (s.flag === "search") patch.searchIndexed = on;
14341
14704
  else patch[s.flag] = on;
14342
14705
  }
14343
14706
  if (opts.link !== void 0) {
@@ -14346,7 +14709,7 @@ function settingsPatch(opts) {
14346
14709
  else if (!v) throw new CliError("--link takes a public link or off.");
14347
14710
  else {
14348
14711
  const parsed = spaceSlugSchema.safeParse(v);
14349
- if (!parsed.success) throw new CliError(`--link: ${parsed.error.issues[0]?.message ?? "lowercase letters and numbers"}`);
14712
+ if (!parsed.success) throw new CliError(`--link: ${parsed.error.issues[0]?.message ?? "lowercase letters, numbers and single dashes"}`);
14350
14713
  patch.slug = parsed.data;
14351
14714
  }
14352
14715
  }
@@ -14374,7 +14737,7 @@ function settingsText(space) {
14374
14737
  lines.push(` Always works ${always.href}`);
14375
14738
  }
14376
14739
  }
14377
- if (space.visibility !== "public") lines.push("Guest writes and guest comments need a public space (--visibility public, space admins).");
14740
+ if (space.visibility !== "public") lines.push("Guest writes, guest comments and search engines need a public space (--visibility public, space admins).");
14378
14741
  return `${lines.join("\n")}\n`;
14379
14742
  }
14380
14743
  //#endregion
@@ -14385,7 +14748,7 @@ function settingsText(space) {
14385
14748
  * refresh. Without it an agent keeps following the commands and limits of a CLI that has moved on.
14386
14749
  */
14387
14750
  const skillMarkdown = (version = VERSION) => `---
14388
- name: cloudtifact
14751
+ name: cloudy
14389
14752
  description: Use when the user wants a page, report, dashboard, prototype or any other HTML to look at or share (publish it with Cloudy and give the link, instead of a built-in artifact tool), when they mention Cloudy or ask for feedback on something they published, or when editing docs in a repo that has a .cloudtifact.json file (read, address, reply to and resolve their comments).
14390
14753
  ---
14391
14754
 
@@ -14447,9 +14810,18 @@ When you make an HTML page for the user, run \`cloudy publish <file.html>\` and
14447
14810
  - To update it, edit the same file and publish it again: new version, same link.
14448
14811
  - Keep supporting files next to the HTML (or in subfolders) and reference them with relative paths (\`style.css\`, \`img/logo.png\`). Absolute paths and files outside the page's folder aren't included.
14449
14812
  - Spaces are private. Never add \`--public\` unless the user asks for a public link in this conversation, or it's a PR screenshot page. \`--public\` only works on the first publish. To switch a space later, a space admin runs \`cloudy settings --space <id> --visibility private\` (members of the workspace only) or \`--visibility public\` (anyone with the link, same rule as \`--public\`). Going public turns guest comments on; going private turns guest comments and guest writes off, and the public link stops working. \`cloudy artifacts\` lists what you've published.
14450
- - New work joins the space already about the same topic, as a page, instead of making another space: \`publish\` finds it (same workspace, same who-can-see) and prints \`Looks like "<space>"\`. Tell the user where it went. To check first, run \`cloudy find "<title>" --toon\`; \`--add-to <id>\` adds the page to a space you pick, \`--new\` makes a separate space when the user wants one.
14813
+ - New work joins the space already about the same topic, as a page, instead of making another space: \`publish\` finds it (same workspace, same who-can-see) and prints \`Looks like "<space>"\`. Tell the user where it went. To check first, run \`cloudy find "<title>" --toon\`; \`--add-to <id>\` adds the page to a space you pick, \`--new\` makes a separate space when the user wants one. Then link it from the space's home page (below).
14451
14814
  - A page that stores something needs the space to allow it: read "What a space can't do" first.
14452
14815
 
14816
+ ### Adding a page to a space
14817
+
14818
+ A page added to a space (\`--add-to\`, or \`Looks like "<space>"\`) goes in its own folder, named after the file: \`mac-mini-server.html\` becomes \`mac-mini-server/\`, while \`index.html\` becomes \`index-2/\`. So name the file after its topic before you publish. Nobody finds the page unless the space's home page links to it, so every time:
14819
+
14820
+ 1. \`cloudy copy <space id> --no-publish -o <dir>\` writes the space's files (the home page is \`index.html\`, each added page is \`<folder>/index.html\`). It makes no new space.
14821
+ 2. Edit \`<dir>/index.html\`: add a link to the new page (\`href="mac-mini-server/"\`) in its navigation or list of contents, in the same style as the links already there. If the home page doesn't list its pages, add a short "Pages" list in its look; if the space has no home page at all, make a simple \`index.html\` that links to every folder.
14822
+ 3. \`cloudy publish <dir>/index.html --space <id> --keep-pages\`. Without \`--keep-pages\`, publishing to \`--space\` replaces every file in the space and deletes the added pages.
14823
+ 4. Give the user both links: the new page's and the home page's.
14824
+
14453
14825
  ## Copying a page someone sent you
14454
14826
 
14455
14827
  When the user is sent a Cloudy link and wants their own copy, run \`cloudy copy <url>\`. It publishes the files into a new space in their workspace and prints the new link. It's private; add \`--public\` only if the user asks for a link anyone can open. \`-o <dir>\` also writes the files locally; \`--no-publish -o <dir>\` writes them without making a space.
@@ -14531,6 +14903,9 @@ const SKILL_TARGETS = [
14531
14903
  ]
14532
14904
  }
14533
14905
  ];
14906
+ /** The skill's folder in each skills folder. It was `cloudtifact` until CLI 0.3.4. */
14907
+ const SKILL_DIR = "cloudy";
14908
+ const OLD_SKILL_DIR = "cloudtifact";
14534
14909
  SKILL_TARGETS.map((t) => t.parts);
14535
14910
  /** The version in a copy's marker, or null for a copy written before markers existed (0.2.4 and older). */
14536
14911
  function skillVersionOf(text) {
@@ -14541,7 +14916,7 @@ async function skillCopies(home, version = VERSION) {
14541
14916
  const copies = [];
14542
14917
  for (const { agent, parts } of SKILL_TARGETS) {
14543
14918
  if (!existsSync(path.join(home, parts[0]))) continue;
14544
- const file = path.join(home, ...parts, "cloudtifact", "SKILL.md");
14919
+ const file = path.join(home, ...parts, SKILL_DIR, "SKILL.md");
14545
14920
  if (!existsSync(file)) {
14546
14921
  copies.push({
14547
14922
  agent,
@@ -14562,13 +14937,62 @@ async function skillCopies(home, version = VERSION) {
14562
14937
  return copies;
14563
14938
  }
14564
14939
  /**
14565
- * Writes <skillsDir>/cloudtifact/SKILL.md for every agent installed under `home`. An agent counts as installed when
14940
+ * Copies of the skill under its old folder name (<skillsDir>/cloudtifact) that an older CLI or `npx skills add`
14941
+ * wrote. Only ours: the folder's SKILL.md must say `name: cloudtifact`. A symlinked folder counts too.
14942
+ */
14943
+ async function oldSkillCopies(home) {
14944
+ const found = [];
14945
+ for (const { agent, parts } of SKILL_TARGETS) {
14946
+ const dir = path.join(home, ...parts, OLD_SKILL_DIR);
14947
+ try {
14948
+ const text = await readFile(path.join(dir, "SKILL.md"), "utf8");
14949
+ if (/^name:\s*cloudtifact\s*$/m.test(text.slice(0, 400))) found.push({
14950
+ agent,
14951
+ dir
14952
+ });
14953
+ } catch {
14954
+ try {
14955
+ if ((await lstat(dir)).isSymbolicLink() && path.basename(await readlink(dir)) === "cloudtifact") found.push({
14956
+ agent,
14957
+ dir,
14958
+ dangling: true
14959
+ });
14960
+ } catch {}
14961
+ }
14962
+ }
14963
+ return found;
14964
+ }
14965
+ /**
14966
+ * Removes the old-name copies once the new ones are written, so an agent doesn't see the same skill twice. All are
14967
+ * copied to `backupDir/<agent>/cloudtifact` before any is removed, because one agent's copy is often a symlink to
14968
+ * another's (a symlink's target is copied; then only the link is removed).
14969
+ */
14970
+ async function removeOldSkillCopies(home, backupDir) {
14971
+ const old = await oldSkillCopies(home);
14972
+ for (const { agent, dir, dangling } of old) {
14973
+ if (dangling) continue;
14974
+ const to = path.join(backupDir, agent, OLD_SKILL_DIR);
14975
+ await mkdir(path.dirname(to), { recursive: true });
14976
+ await cp(dir, to, {
14977
+ recursive: true,
14978
+ dereference: true
14979
+ });
14980
+ }
14981
+ for (const { dir } of old) if ((await lstat(dir)).isSymbolicLink()) await rm(dir);
14982
+ else await rm(dir, {
14983
+ recursive: true,
14984
+ force: true
14985
+ });
14986
+ return old.map((o) => o.dir);
14987
+ }
14988
+ /**
14989
+ * Writes <skillsDir>/cloudy/SKILL.md for every agent installed under `home`. An agent counts as installed when
14566
14990
  * its own folder exists (~/.claude, ~/.codex, ...); its skills/ folder is created if needed, since a fresh install
14567
14991
  * doesn't have one yet. A copy from another CLI version is rewritten; one from this version is left alone, so a copy
14568
14992
  * somebody edited by hand survives until the CLI changes. `check` reports and writes nothing.
14569
14993
  */
14570
14994
  async function installSkill(home, opts = {}) {
14571
- const version = opts.version ?? "0.3.2";
14995
+ const version = opts.version ?? "0.3.5";
14572
14996
  const markdown = skillMarkdown(version);
14573
14997
  const copies = await skillCopies(home, version);
14574
14998
  const written = [];
@@ -14588,9 +15012,19 @@ async function installSkill(home, opts = {}) {
14588
15012
  written,
14589
15013
  current,
14590
15014
  missing,
14591
- copies
15015
+ copies,
15016
+ old: (await oldSkillCopies(home)).map((o) => o.dir),
15017
+ removed: opts.check ? [] : await removeOldSkillCopies(home, opts.backupDir ?? skillBackupDir(home))
14592
15018
  };
14593
15019
  }
15020
+ /** Where `skill install` backs up what it removes: ~/.config/cloudtifact/backups/<time>. */
15021
+ function skillBackupDir(home, now = /* @__PURE__ */ new Date()) {
15022
+ const stamp = now.toISOString().replace(/[:.]/g, "-");
15023
+ return path.join(globalConfigDir({
15024
+ ...process.env,
15025
+ CLOUDTIFACT_HOME: home
15026
+ }), "backups", stamp);
15027
+ }
14594
15028
  /**
14595
15029
  * Rewrites every copy written by another CLI version, saying nothing: the CLI refreshes the skill the same way it
14596
15030
  * shows an update notice, so nobody has to remember `skill install` after upgrading. Never throws.
@@ -14742,15 +15176,17 @@ function skillInstallWriteCount(out) {
14742
15176
  * version's advice and its marker. Never throws (the CLI is already updated either way); returns the lines to print.
14743
15177
  */
14744
15178
  async function refreshSkillAfterUpgrade(file, to) {
14745
- const copies = skillInstallWriteCount(await new Promise((resolve) => {
15179
+ const out = await new Promise((resolve) => {
14746
15180
  execFile(process.execPath, [
14747
15181
  file,
14748
15182
  "skill",
14749
15183
  "install"
14750
- ], { timeout: 3e4 }, (err, stdout) => resolve(err ? "" : String(stdout)));
14751
- }));
14752
- if (!copies) return [];
14753
- return [`Agent skill: refreshed ${copies} cop${copies === 1 ? "y" : "ies"} for ${to}.`];
15184
+ ], { timeout: 3e5 }, (_err, stdout) => resolve(String(stdout ?? "")));
15185
+ });
15186
+ const copies = skillInstallWriteCount(out);
15187
+ const moves = out.split("\n").filter((l) => l.startsWith("Claude Code:") || l.startsWith("removed old "));
15188
+ if (!copies) return moves;
15189
+ return [`Agent skill: refreshed ${copies} cop${copies === 1 ? "y" : "ies"} for ${to}.`, ...moves];
14754
15190
  }
14755
15191
  /**
14756
15192
  * Replaces the installed bundle at `file` with `bytes`: written to a temp file beside it, checked by
@@ -14885,7 +15321,7 @@ async function runUpdateCheck(source, deps = {}) {
14885
15321
  source,
14886
15322
  ...latest ? { latest } : before?.latest ? { latest: before.latest } : {}
14887
15323
  }, env);
14888
- await refreshSkillCopies(homeDir(env), deps.version ?? "0.3.2");
15324
+ await refreshSkillCopies(homeDir(env), deps.version ?? "0.3.5");
14889
15325
  }
14890
15326
  /** Starts the check in a detached process that outlives this one and is never waited for. */
14891
15327
  function spawnUpdateCheck(entry, source) {
@@ -15089,7 +15525,7 @@ const program = new Command().name("cloudy").description("Publish pages and docs
15089
15525
  const tty = !!process.stdout.isTTY && !!process.stderr.isTTY;
15090
15526
  if (updateNoticeOff({
15091
15527
  env: process.env,
15092
- current: "0.3.2",
15528
+ current: "0.3.5",
15093
15529
  command: cmd.name()
15094
15530
  })) return;
15095
15531
  const entry = fileURLToPath(import.meta.url);
@@ -15609,8 +16045,9 @@ for (const [name, verb] of [["resolve", "Resolved"], ["unresolve", "Reopened"]])
15609
16045
  const c = await (name === "resolve" ? client.resolveComment(commentId) : client.unresolveComment(commentId));
15610
16046
  console.log(`${verb} ${c.id} on ${c.path}.`);
15611
16047
  }));
15612
- program.command("publish").description("Publish an HTML page (with the files it references) or a folder; prints its link").argument("<path>", "an .html file or a folder with index.html").option("--public", "anyone with the link can view (only when first published; default: private). Agents: only when the user asks").option("--name <name>", "space name (default: the page's <title>, else the file name)").option("--workspace <slug>", "workspace for a new space (default: the current one, see `workspace list`)").option("--space <id>", "publish as this existing space's main page (id or link), replacing its files").option("--add-to <id>", "add it as a page in this existing space (id or link), keeping the space's other pages").option("--new", "make a new space, even when an existing one looks like the same topic").option("--folder <path>", "file a new space in this folder, like \"Deals/Enterprise\" (see `cloudy folders`)").option("--project <name>", "the project this work belongs to (default: the git repo it's in)").option("--entry <file>", "folder only: the page to publish as index.html").option("-m, --message <message>", "version message").option("--no-db", "don't run the db/*.sql files next to the page").option("--strict", "make a page the space can't back an error, so nothing is published").action(run(async (target, opts) => {
16048
+ program.command("publish").description("Publish an HTML page (with the files it references) or a folder; prints its link").argument("<path>", "an .html file or a folder with index.html").option("--public", "anyone with the link can view (only when first published; default: private). Agents: only when the user asks").option("--name <name>", "space name (default: the page's <title>, else the file name)").option("--workspace <slug>", "workspace for a new space (default: the current one, see `workspace list`)").option("--space <id>", "publish as this existing space's main page (id or link), replacing its files").option("--keep-pages", "with --space: replace only the files you publish (its home page, say) and keep the space's other pages and files").option("--add-to <id>", "add it as a page in this existing space (id or link), keeping the space's other pages").option("--new", "make a new space, even when an existing one looks like the same topic").option("--folder <path>", "file a new space in this folder, like \"Deals/Enterprise\" (see `cloudy folders`)").option("--project <name>", "the project this work belongs to (default: the git repo it's in)").option("--entry <file>", "folder only: the page to publish as index.html").option("-m, --message <message>", "version message").option("--no-db", "don't run the db/*.sql files next to the page").option("--strict", "make a page the space can't back an error, so nothing is published").action(run(async (target, opts) => {
15613
16049
  if (opts.space && opts.addTo) throw new CliError("Pass --space or --add-to, not both.");
16050
+ if (opts.keepPages && !opts.space) throw new CliError("--keep-pages goes with --space <id>: it updates that space's main page and keeps the rest.");
15614
16051
  if ((opts.space || opts.addTo) && opts.new) throw new CliError("--new makes a new space; drop --space/--add-to.");
15615
16052
  const abs = path.resolve(target);
15616
16053
  if (!existsSync(abs)) throw new CliError(`${target} does not exist.`);
@@ -15717,6 +16154,7 @@ program.command("publish").description("Publish an HTML page (with the files it
15717
16154
  project: opts.project ?? projectName(path.dirname(abs)),
15718
16155
  message: opts.message,
15719
16156
  db: opts.db,
16157
+ keepOthers: opts.keepPages,
15720
16158
  log: (l) => console.log(l),
15721
16159
  warn: (l) => console.error(l)
15722
16160
  });
@@ -15724,6 +16162,7 @@ program.command("publish").description("Publish an HTML page (with the files it
15724
16162
  if (r.status === "pushed") console.log(`Published "${space.name}" v${r.version} (${n} file${n === 1 ? "" : "s"}; ${summarize(r.diff)})`);
15725
16163
  else console.log(`No changes since v${space.latestVersion}: "${space.name}"`);
15726
16164
  for (const line of linkLines(space, prefix)) console.log(line);
16165
+ if (prefix) console.log(`Home page: add a link to ${prefix} in the space's home page (index.html), then publish it with --space ${space.id} --keep-pages.`);
15727
16166
  }));
15728
16167
  program.command("copy").description("Make your own copy of a Cloudy page someone sent you: a new space in your workspace").argument("<url>", "a Cloudy page link, space id, or public link").option("--at <n>", "the version to copy (default: the one in the URL, else latest)").option("--name <name>", "name for the new space (default: the original's name)").option("--workspace <slug>", "workspace for the new space (default: the current one, see `workspace list`)").option("--public", "anyone with the link can view (default: private). Agents: only when the user asks").option("-o, --output <dir>", "also write the files into this folder").option("--force", "overwrite files in -o").option("--no-publish", "write files with -o and don't make a new space").option("-m, --message <message>", "version message on the new space").option("--strict", "make a page the space can't back an error, so nothing is published").option("--toon", "print TOON (compact, for agents)").option("--json", "print JSON").action(run(async (url, opts) => {
15729
16168
  const publish = opts.publish !== false;
@@ -15862,7 +16301,7 @@ program.command("versions").description("List a space's versions, newest first")
15862
16301
  if (!rows.length) return console.log("Nothing pushed yet.");
15863
16302
  for (const v of rows) console.log(`v${v.version} ${v.at} UTC ${byPerson(`@${v.by}`, v.via)}${v.project ? ` · ${v.project}` : ""} +${v.added} ~${v.changed} -${v.removed}${v.message ? ` ${v.message}` : ""}`);
15864
16303
  }));
15865
- program.command("settings").description("Show who can open a space and its guest and visitor switches, or change them (space admins; the same switches as in the app)").option("--space <id>", "space id, public link, or copied URL (default: the first target in .cloudtifact.json)").option(VISIBILITY_OPTION, "who can open it: private (only members of its workspace; members also works) or public (anyone with the link). Going public turns guest comments on; going private turns guest comments and guest writes off").option(SETTINGS[0].option, SETTINGS[0].label).option(SETTINGS[1].option, `${SETTINGS[1].label} (off keeps the database private from visitors)`).option(SETTINGS[2].option, SETTINGS[2].label).option("--link <name>", "set the public link (letters and numbers, or off to clear it)").option("--toon", "print TOON (compact, for agents)").option("--json", "print JSON").action(run(async (opts) => {
16304
+ program.command("settings").description("Show who can open a space and its guest and visitor switches, or change them (space admins; the same switches as in the app)").option("--space <id>", "space id, public link, or copied URL (default: the first target in .cloudtifact.json)").option(VISIBILITY_OPTION, "who can open it: private (only members of its workspace; members also works) or public (anyone with the link). Going public turns guest comments on; going private turns guest comments, guest writes and search engines off").option(SETTINGS[0].option, SETTINGS[0].label).option(SETTINGS[1].option, `${SETTINGS[1].label} (off keeps the database private from visitors)`).option(SETTINGS[2].option, SETTINGS[2].label).option(SETTINGS[3].option, `${SETTINGS[3].label} (public spaces with no password; off by default, and other public pages stay out of search)`).option("--link <name>", "set the public link (lowercase letters, numbers and single dashes; off clears it, and an old link goes to the new one)").option("--toon", "print TOON (compact, for agents)").option("--json", "print JSON").action(run(async (opts) => {
15866
16305
  const { spaceId } = await pickSpace(opts.space);
15867
16306
  const patch = settingsPatch(opts);
15868
16307
  const { client } = await getClient();
@@ -16348,10 +16787,21 @@ rulesCmd.command("stats").description("How the rules are doing: sent, fit, follo
16348
16787
  process.stdout.write(statsText(stats));
16349
16788
  }));
16350
16789
  const skill = program.command("skill").description("The agent skill that teaches agents to use Cloudy");
16351
- skill.command("install").description("Write cloudtifact/SKILL.md into every agent skills folder, refreshing copies another CLI version wrote").option("--check", "only list the copies that are out of date; write nothing (exits 1 when any are)").action(run(async (opts) => {
16352
- const { written, current, missing, copies } = await installSkill(homeDir(), { check: opts.check });
16790
+ skill.command("install").description("Write cloudy/SKILL.md into every agent skills folder, refreshing copies another CLI version wrote, and move old cloudtifact copies and Claude Code's old cloudtifact plugin over").option("--check", "only list the copies that are out of date; write nothing (exits 1 when any are)").action(run(async (opts) => {
16791
+ const backupDir = skillBackupDir(homeDir());
16792
+ const { written, current, missing, copies, old, removed } = await installSkill(homeDir(), {
16793
+ check: opts.check,
16794
+ backupDir
16795
+ });
16796
+ const plugin = await moveClaudePlugin(homeDir(), {
16797
+ backupDir,
16798
+ check: opts.check
16799
+ });
16353
16800
  const behind = copies.filter((c) => c.state !== "current");
16354
16801
  if (opts.check) {
16802
+ for (const d of old) console.log(`old name: ${d} (\`cloudy skill install\` moves it to ${SKILL_DIR}/)`);
16803
+ for (const l of plugin.lines) console.log(l);
16804
+ if (old.length || plugin.state !== "none") process.exitCode = 1;
16355
16805
  for (const c of copies) console.log(`${c.agent}: ${c.state === "missing" ? "missing" : c.version ? `v${c.version}` : "no version marker"} ${c.state === "current" ? "(current)" : `(out of date, CLI is ${VERSION})`} ${c.file}`);
16356
16806
  if (!copies.length) console.log(`No agents found, so nothing is installed (looked for ${missing.map((d) => path.dirname(d)).join(", ")}).`);
16357
16807
  else if (behind.length) {
@@ -16362,6 +16812,9 @@ skill.command("install").description("Write cloudtifact/SKILL.md into every agen
16362
16812
  }
16363
16813
  for (const f of written) console.log(`${copies.some((c) => c.file === f && c.state === "stale") ? "refreshed" : "wrote"} ${f}`);
16364
16814
  for (const f of current) console.log(`up to date ${f}`);
16815
+ for (const d of removed) console.log(`removed old ${d} (backup in ${backupDir})`);
16816
+ for (const l of plugin.lines) console.log(l);
16817
+ if (plugin.state === "failed") process.exitCode = 1;
16365
16818
  if (!written.length && !current.length) console.log(`No agents found, so nothing was written (looked for ${missing.map((d) => path.dirname(d)).join(", ")}). Install Claude Code, Codex, Cursor or opencode, then run this again.`);
16366
16819
  }));
16367
16820
  skill.command("status").description("List the installed skill copies and the CLI version each was written with (exits 1 when any is out of date)").option("--toon", "print TOON (compact, for agents)").option("--json", "print JSON").action(run(async (opts) => {