@foleo/cli 0.1.48 → 0.1.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { workspaceCommand, WORKSPACE_HELP } from "./workspaces.js";
2
+ import { loadDefaultWorkspace, saveDefaultWorkspace, } from "./workspace-default.js";
3
+ import { moveCommand, MOVE_HELP } from "./move.js";
4
+ import { loadWorkspaceBinding, saveWorkspaceBinding, } from "./workspace-binding.js";
5
+ import { pathWorkspaceCommand, PATH_WORKSPACE_HELP } from "./path-workspace.js";
6
+ import { CliEditContext, cliStateRoot } from "./edit-context.js";
7
+ import { sharedCommand, SHARED_HELP } from "./shared.js";
8
+ import { membersCommand, MEMBERS_HELP } from "./members.js";
9
+ import { readEditsFile, workspaceCommand, WORKSPACE_HELP, } from "./workspaces.js";
3
10
  import { spawn } from "node:child_process";
4
11
  import { createHash, randomUUID } from "node:crypto";
5
12
  import { constants } from "node:fs";
@@ -10,6 +17,7 @@ import { tmpdir } from "node:os";
10
17
  import { createServer } from "node:http";
11
18
  import { dirname, join, relative, resolve, sep } from "node:path";
12
19
  import { fileURLToPath, pathToFileURL } from "node:url";
20
+ import { parseArgs } from "node:util";
13
21
  import { FoleoError, LocalError, renderFailure, toFoleoError, UsageError, } from "./errors.js";
14
22
  import { auditImages } from "./images.js";
15
23
  import { optimizeImages, } from "./image-encoder.js";
@@ -195,17 +203,70 @@ export async function runCli(argv, deps = {
195
203
  stdout: (message) => process.stdout.write(message),
196
204
  stderr: (message) => process.stderr.write(message),
197
205
  }) {
198
- const wantsJson = argv.includes("--json");
206
+ let wantsJson = argv.includes("--json");
199
207
  let activeDeps = deps;
200
208
  try {
201
209
  const global = parseGlobalFlags(argv);
202
- const commandDeps = global.environment
210
+ const [command, ...rest] = global.argv;
211
+ const optionTokens = [...rest];
212
+ if (command === "edit")
213
+ for (let i = 0; i < rest.length; i++)
214
+ if (EDIT_LITERAL_FLAGS.has(rest[i]) && i + 1 < rest.length)
215
+ optionTokens[++i] = "";
216
+ wantsJson = optionTokens.includes("--json");
217
+ const selectedDeps = global.environment
203
218
  ? { ...deps, env: { ...deps.env, FOLEO_ENV: global.environment } }
204
219
  : deps;
220
+ const commandDeps = { ...selectedDeps };
221
+ const explicitWorkspace = global.workspace;
222
+ const defaultWorkspace = global.argv[0] === "login"
223
+ ? null
224
+ : await defaultWorkspaceFor(commandDeps);
225
+ const selectedWorkspace = explicitWorkspace ?? defaultWorkspace ?? undefined;
226
+ if (selectedWorkspace && !isTreeId(selectedWorkspace))
227
+ commandDeps.credentialWorkspace = selectedWorkspace;
228
+ else if (defaultWorkspace)
229
+ commandDeps.credentialWorkspace = defaultWorkspace;
230
+ const isLogin = global.argv[0] === "login";
231
+ const bindings = new Map();
232
+ commandDeps.fetch = async (input, init) => {
233
+ const url = input instanceof Request ? input.url : String(input);
234
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
235
+ const bearer = headers.get("authorization")?.match(/^Bearer (.+)$/u)?.[1];
236
+ if (bearer &&
237
+ url.startsWith(apiBase(commandDeps) + "/") &&
238
+ !isLogin &&
239
+ global.argv[0] !== "use" &&
240
+ selectedWorkspace &&
241
+ !isTreeId(selectedWorkspace)) {
242
+ let bound = bindings.get(bearer) ?? (await boundWorkspace(commandDeps, bearer));
243
+ if (!bound) {
244
+ const meResponse = await selectedDeps.fetch(`${apiBase(commandDeps)}/me`, { headers: { authorization: `Bearer ${bearer}` } });
245
+ if (!meResponse.ok)
246
+ throw apiResponseError(meResponse.status, await meResponse.json());
247
+ bound = workspaceFromMe(await meResponse.json());
248
+ }
249
+ if (!bound)
250
+ throw new LocalError("workspace_unknown", "Cannot determine this login's workspace.", { next: `Run foleo login --workspace ${selectedWorkspace}.` });
251
+ bindings.set(bearer, bound);
252
+ if (bound !== selectedWorkspace)
253
+ throw workspaceMismatch(bound, selectedWorkspace);
254
+ headers.set("Foleo-Workspace", selectedWorkspace);
255
+ }
256
+ return selectedWorkspace &&
257
+ !isLogin &&
258
+ global.argv[0] !== "use" &&
259
+ bearer &&
260
+ !isTreeId(selectedWorkspace)
261
+ ? selectedDeps.fetch(input, {
262
+ ...init,
263
+ headers: Object.fromEntries(headers),
264
+ })
265
+ : selectedDeps.fetch(input, init);
266
+ };
205
267
  activeDeps = commandDeps;
206
268
  jsonOutputs.set(commandDeps, wantsJson);
207
- const [command, ...rest] = global.argv;
208
- if (rest.includes("--optimize-images") &&
269
+ if (optionTokens.includes("--optimize-images") &&
209
270
  !["publish", "update"].includes(command ?? "")) {
210
271
  throw new UsageError("--optimize-images applies to an HTML bundle folder", "image_optimization_not_applicable");
211
272
  }
@@ -215,7 +276,13 @@ export async function runCli(argv, deps = {
215
276
  command === "-h" ||
216
277
  (command === "settings" &&
217
278
  (rest.includes("--help") || rest.includes("-h")))) {
218
- commandDeps.stdout(help() + "\n" + WORKSPACE_HELP);
279
+ commandDeps.stdout(PATH_WORKSPACE_HELP +
280
+ "\n" +
281
+ help() +
282
+ "\n" +
283
+ WORKSPACE_HELP +
284
+ "\n" +
285
+ MEMBERS_HELP);
219
286
  return 0;
220
287
  }
221
288
  if (command === "--version" || command === "-v" || command === "version") {
@@ -232,12 +299,15 @@ export async function runCli(argv, deps = {
232
299
  // cannot plan now refuses the flag rather than ignoring it (spec 089 §D).
233
300
  // Commands in the set below reach their own guard, which names the
234
301
  // operation and stays stable for callers already matching on it.
235
- if (rest.includes("--dry-run") && !DRY_RUN_AWARE_COMMANDS.has(command)) {
236
- throw new UsageError(`--dry-run is not supported by \`foleo ${command}\`. Only \`publish\` on an HTML bundle can plan.`, "dry_run_unsupported", { operation: command });
302
+ if (optionTokens.includes("--dry-run") &&
303
+ !DRY_RUN_AWARE_COMMANDS.has(command) &&
304
+ command !== "edit" &&
305
+ !(command === "workspace" && rest[0] === "edit")) {
306
+ throw new UsageError(`--dry-run is not supported by \`foleo ${command}\`. Use \`foleo edit\`, \`foleo workspace edit\`, or the HTML bundle workflow to preview changes.`, "dry_run_unsupported", { operation: command });
237
307
  }
238
308
  // Same shape as the --dry-run guard: a runtime profile on a command that
239
309
  // cannot send one must fail rather than be silently ignored.
240
- if (rest.includes("--runtime-profile") &&
310
+ if (optionTokens.includes("--runtime-profile") &&
241
311
  !RUNTIME_PROFILE_COMMANDS.has(command)) {
242
312
  throw runtimeProfileNotApplicable({
243
313
  operation: describeArgvToken(command),
@@ -246,6 +316,10 @@ export async function runCli(argv, deps = {
246
316
  if (command === "workspace" ||
247
317
  command === "capabilities" ||
248
318
  command === "approval") {
319
+ if (optionTokens.includes("--help") || optionTokens.includes("-h")) {
320
+ commandDeps.stdout(WORKSPACE_HELP);
321
+ return 0;
322
+ }
249
323
  return await workspaceCommand(command === "capabilities"
250
324
  ? ["capabilities", ...rest]
251
325
  : command === "approval"
@@ -267,15 +341,142 @@ export async function runCli(argv, deps = {
267
341
  }
268
342
  : { headers: { authorization: `Bearer ${credential.token}` } });
269
343
  if (!response.ok)
270
- throw apiResponseError(response.status, await response.json());
344
+ throw apiResponseError(response.status, await response.json(), true);
271
345
  return response;
272
346
  },
273
347
  });
274
348
  }
349
+ if ([
350
+ "save",
351
+ "edit",
352
+ "read",
353
+ "share",
354
+ "ls",
355
+ "search",
356
+ "history",
357
+ "recent",
358
+ "move",
359
+ "trash",
360
+ "undo",
361
+ ].includes(command) ||
362
+ (command === "list" &&
363
+ (rest.some((arg) => arg.startsWith("/")) ||
364
+ rest.includes("--workspace") ||
365
+ rest.includes("--view") ||
366
+ rest.includes("--observe-subtree") ||
367
+ selectedWorkspace !== undefined))) {
368
+ if (optionTokens.includes("--help") || optionTokens.includes("-h")) {
369
+ commandDeps.stdout(PATH_WORKSPACE_HELP);
370
+ return 0;
371
+ }
372
+ const credential = await resolveCredentialWithSource(commandDeps);
373
+ if (!credential)
374
+ throw new LocalError("credential_missing", "No Foleo credential found.", { next: "Sign in or set FOLEO_TOKEN." });
375
+ const sessionAt = optionTokens.indexOf("--session"), session = sessionAt >= 0 ? (rest[sessionAt + 1] ?? "default") : "default";
376
+ return await pathWorkspaceCommand(command === "list" ? "ls" : command, rest, {
377
+ stdout: commandDeps.stdout,
378
+ readStdin: async () => {
379
+ if (commandDeps.readStdin)
380
+ return commandDeps.readStdin();
381
+ const chunks = [];
382
+ let size = 0;
383
+ for await (const chunk of process.stdin) {
384
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
385
+ size += bytes.length;
386
+ if (size > 65536)
387
+ throw new UsageError("Use foleo workspace put for large or binary input.", "transport_requires_advanced");
388
+ chunks.push(bytes);
389
+ }
390
+ try {
391
+ return new TextDecoder("utf-8", {
392
+ fatal: true,
393
+ ignoreBOM: true,
394
+ }).decode(Buffer.concat(chunks));
395
+ }
396
+ catch {
397
+ throw new UsageError("Use foleo workspace put for binary input.", "transport_requires_advanced");
398
+ }
399
+ },
400
+ state: new CliEditContext(cliStateRoot(commandDeps.env), apiBase(commandDeps) +
401
+ ":" +
402
+ createHash("sha256").update(credential.token).digest("hex") +
403
+ ":" +
404
+ session),
405
+ request: async (path, init) => {
406
+ const response = await commandDeps.fetch(apiBase(commandDeps) + path, {
407
+ ...init,
408
+ headers: {
409
+ ...Object.fromEntries(new Headers(init?.headers)),
410
+ authorization: `Bearer ${credential.token}`,
411
+ },
412
+ });
413
+ return response;
414
+ },
415
+ });
416
+ }
417
+ if (command === "mv") {
418
+ if (rest.includes("--help") || rest.includes("-h")) {
419
+ commandDeps.stdout(MOVE_HELP);
420
+ return 0;
421
+ }
422
+ if (selectedWorkspace) {
423
+ const credential = await resolveCredentialWithSource(commandDeps);
424
+ if (credential) {
425
+ const bound = (await boundWorkspace(commandDeps, credential.token)) ??
426
+ workspaceFromMe(await requestJson(commandDeps, "/me", {
427
+ method: "GET",
428
+ body: undefined,
429
+ }));
430
+ if (!bound)
431
+ throw new LocalError("workspace_unknown", "Cannot verify this login’s source workspace.");
432
+ if (bound !== selectedWorkspace)
433
+ throw workspaceMismatch(bound, selectedWorkspace);
434
+ }
435
+ }
436
+ return await moveCommand(rest, {
437
+ stdout: commandDeps.stdout,
438
+ stderr: commandDeps.stderr,
439
+ ...(commandDeps.confirm ? { confirm: commandDeps.confirm } : {}),
440
+ ...(commandDeps.sleep ? { sleep: commandDeps.sleep } : {}),
441
+ request: (path, method, body) => requestJson(commandDeps, path, { method, body }),
442
+ });
443
+ }
444
+ if (command === "shared")
445
+ return await sharedCommand(rest, {
446
+ stdout: commandDeps.stdout,
447
+ request: (path) => requestJson(commandDeps, path, { method: "GET", body: undefined }),
448
+ });
449
+ if (command === "members" || command === "invites")
450
+ return await membersCommand(command, rest, {
451
+ stdout: commandDeps.stdout,
452
+ ...(commandDeps.confirm ? { confirm: commandDeps.confirm } : {}),
453
+ request: (path, method, body) => requestJson(commandDeps, path, { method, body }),
454
+ workspace: async () => {
455
+ const credential = await resolveCredentialWithSource(commandDeps);
456
+ if (!credential)
457
+ throw new LocalError("credential_missing", "Sign in first.");
458
+ const bound = (await boundWorkspace(commandDeps, credential.token)) ??
459
+ workspaceFromMe(await requestJson(commandDeps, "/me", {
460
+ method: "GET",
461
+ body: undefined,
462
+ }));
463
+ if (!bound)
464
+ throw new LocalError("workspace_unknown", "Run foleo login --workspace <handle>.");
465
+ if (selectedWorkspace && selectedWorkspace !== bound)
466
+ throw workspaceMismatch(bound, selectedWorkspace);
467
+ return bound;
468
+ },
469
+ });
470
+ if (command === "use")
471
+ return await useWorkspace(rest, commandDeps);
472
+ if (command === "workspaces")
473
+ return await workspaceOrganizations(rest, commandDeps);
275
474
  if (command === "publish")
276
475
  return await publish(rest, commandDeps);
277
476
  if (command === "update")
278
477
  return await update(rest, commandDeps);
478
+ if (command === "republish")
479
+ return await republish(rest, commandDeps);
279
480
  if (command === "name")
280
481
  return await nameCommand(rest, commandDeps);
281
482
  if (command === "names")
@@ -326,8 +527,13 @@ export async function runCli(argv, deps = {
326
527
  return await settingsCommand(rest, commandDeps);
327
528
  if (command === "limits")
328
529
  return await limitsCommand(rest, commandDeps);
530
+ if (command === "login" &&
531
+ (rest.includes("--help") || rest.includes("-h"))) {
532
+ commandDeps.stdout("Usage: foleo login [--workspace <handle>] [--no-browser] [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]\nThe sign-in URL is always printed to stderr; --no-browser skips opening it. The approving browser must be on this computer (the callback is local).\nThe browser confirms the workspace. This replaces only the chosen workspace login for this API.\n");
533
+ return 0;
534
+ }
329
535
  if (command === "login")
330
- return await login(rest, commandDeps);
536
+ return await login(rest, commandDeps, explicitWorkspace);
331
537
  if (command === "logout")
332
538
  return await logout(rest, commandDeps);
333
539
  if (command === "list")
@@ -675,6 +881,12 @@ async function doctor(args, deps) {
675
881
  checks.push({ key: "credential", status: "pass" });
676
882
  try {
677
883
  const me = await requestJsonWithToken(deps, "/me", credential.token, { method: "GET", body: undefined });
884
+ const handle = workspaceFromMe(me) ?? (await boundWorkspace(deps, credential.token));
885
+ checks.push({
886
+ key: "workspace",
887
+ status: handle ? "pass" : "warn",
888
+ message: handle ?? "Unknown; run foleo login to record the bound workspace.",
889
+ });
678
890
  const bootstrapRequired = me.bootstrapRequired === true;
679
891
  const scopes = stringArray(me.scopes);
680
892
  const entitlements = stringArray(me.entitlements);
@@ -731,6 +943,7 @@ async function doctor(args, deps) {
731
943
  checks.push(await updateCheck(deps, version));
732
944
  const result = {
733
945
  ok: !checks.some((check) => check.status === "fail"),
946
+ workspaceHandle: checks.find((check) => check.key === "workspace" && check.status === "pass")?.message ?? null,
734
947
  cliVersion: version,
735
948
  environment: info.name,
736
949
  apiOrigin: new URL(info.apiBase).origin,
@@ -748,10 +961,12 @@ function stringArray(value) {
748
961
  ? value
749
962
  : [];
750
963
  }
751
- async function login(args, deps) {
964
+ async function login(args, deps, workspace) {
965
+ if (workspace && isTreeId(workspace))
966
+ throw new UsageError("login --workspace requires a handle, not a tree ID.");
752
967
  const parsed = parseFlags(args, { allowLoginScopeFlags: true });
753
968
  if (parsed.positionals.length > 0)
754
- throw new Error("Usage: foleo login [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]");
969
+ throw new Error("Usage: foleo login [--workspace <handle>] [--no-browser] [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]");
755
970
  const base = apiBase(deps);
756
971
  const workspaceScopes = [
757
972
  ...(parsed.allowWorkspaces || parsed.allowWorkspaceSharing
@@ -776,13 +991,20 @@ async function login(args, deps) {
776
991
  const verifyStore = deps.verifyCredentialStore ?? verifyKeychainWritable;
777
992
  const saveCredential = deps.saveCredential ?? saveKeychainCredential;
778
993
  const deleteCredential = deps.deleteCredential ?? deleteKeychainCredential;
994
+ const storeCredential = (token) => credentialHandle
995
+ ? saveCredential(base, token, credentialHandle)
996
+ : saveCredential(base, token);
997
+ const clearCredential = () => credentialHandle
998
+ ? deleteCredential(base, credentialHandle)
999
+ : deleteCredential(base);
779
1000
  const createCallback = deps.createBrowserCallback ?? createLoopbackCallback;
780
1001
  const openUrl = deps.openUrl ?? openBrowser;
781
1002
  await verifyStore(base);
782
1003
  // The Keychain entry this login overwrites holds the only copy of the
783
1004
  // previous key's token. Keep it, so a failed login can put it back and a
784
1005
  // successful one can revoke that key instead of stranding it (ADR 0044).
785
- const previousToken = await (deps.loadCredential ?? loadKeychainCredential)(base);
1006
+ let credentialHandle = workspace;
1007
+ let previousToken = null;
786
1008
  const nonce = createHash("sha256").update(randomUUID()).digest("hex");
787
1009
  const callback = await createCallback(nonce);
788
1010
  let appSessionToken = null;
@@ -793,14 +1015,23 @@ async function login(args, deps) {
793
1015
  nonce,
794
1016
  callbackUrl: callback.callbackUrl,
795
1017
  clientKind: "cli",
1018
+ ...(workspace ? { workspaceHandle: workspace } : {}),
796
1019
  ...(workspaceScopes.length ? { workspaceScopes } : {}),
797
1020
  });
798
- deps.stderr("Opening Foleo sign-in in your browser...\n");
799
- try {
800
- await openUrl(start.authorizeUrl);
1021
+ if (workspace) {
1022
+ const authorize = new URL(start.authorizeUrl);
1023
+ // The server stores this hint with request_id; query hints are not binding authority.
1024
+ start.authorizeUrl = authorize.href;
801
1025
  }
802
- catch {
803
- deps.stderr(`Open this URL to continue:\n${start.authorizeUrl}\n`);
1026
+ deps.stderr(`Open this link to sign in: ${start.authorizeUrl}\n`);
1027
+ if (!parsed.noBrowser) {
1028
+ deps.stderr("Opening Foleo sign-in in your browser...\n");
1029
+ try {
1030
+ await openUrl(start.authorizeUrl);
1031
+ }
1032
+ catch {
1033
+ // The URL above also works when the browser cannot be opened.
1034
+ }
804
1035
  }
805
1036
  const code = await callback.waitForCode();
806
1037
  const exchanged = await requestPublicJson(deps, "/desktop/handoff/exchange", {
@@ -810,6 +1041,11 @@ async function login(args, deps) {
810
1041
  sessionTtlSeconds: 600,
811
1042
  });
812
1043
  appSessionToken = exchanged.token;
1044
+ credentialHandle =
1045
+ exchanged.org.kind === "shared" ? exchanged.org.handle : workspace;
1046
+ previousToken = await (deps.loadCredential ?? loadKeychainCredential)(base, credentialHandle);
1047
+ if (workspace && exchanged.org.handle !== workspace)
1048
+ throw workspaceMismatch(exchanged.org.handle, workspace);
813
1049
  const key = await requestJsonWithToken(deps, "/keys", appSessionToken, {
814
1050
  method: "POST",
815
1051
  body: {
@@ -817,22 +1053,37 @@ async function login(args, deps) {
817
1053
  // `--allow-delete` is now redundant and accepted silently, so existing
818
1054
  // scripts and docs keep working.
819
1055
  scopes: [
820
- ...CLI_KEY_SCOPES,
821
- ...(parsed.allowPurge ? ["artifacts:purge"] : []),
1056
+ ...CLI_KEY_SCOPES.filter((scope) => exchanged.actor?.role === "viewer"
1057
+ ? scope === "artifacts:read"
1058
+ : ["publisher", "admin"].includes(exchanged.actor?.role ?? "")
1059
+ ? ![
1060
+ "artifacts:delete",
1061
+ "artifacts:purge",
1062
+ "keys:read",
1063
+ ].includes(scope)
1064
+ : true),
1065
+ ...(parsed.allowPurge &&
1066
+ !["viewer", "publisher", "admin"].includes(exchanged.actor?.role ?? "")
1067
+ ? ["artifacts:purge"]
1068
+ : []),
822
1069
  ...workspaceScopes.filter((scope) => exchanged.approvedWorkspaceScopes?.includes(scope)),
823
1070
  ],
824
1071
  deferredActivation: true,
825
1072
  },
826
1073
  });
827
1074
  try {
828
- await saveCredential(base, key.token);
1075
+ await storeCredential(key.token);
829
1076
  await requestJsonWithToken(deps, `/keys/${encodeURIComponent(key.id)}/activate`, appSessionToken, { method: "POST", body: {} });
1077
+ await (deps.saveWorkspaceBinding ??
1078
+ ((api, token, handle) => saveWorkspaceBinding(deps.env, api, token, handle)))(base, key.token, exchanged.org.handle);
1079
+ if (!workspace && credentialHandle)
1080
+ await persistDefaultWorkspace(deps, credentialHandle);
830
1081
  }
831
1082
  catch (error) {
832
1083
  const restored = previousToken !== null &&
833
- (await saveCredential(base, previousToken).then(() => true, () => false));
1084
+ (await storeCredential(previousToken).then(() => true, () => false));
834
1085
  if (!restored) {
835
- await deleteCredential(base).catch(() => undefined);
1086
+ await clearCredential().catch(() => undefined);
836
1087
  // The previous token is now gone from the Keychain for good. Retire its
837
1088
  // key while this process still holds the token, or it stays live with
838
1089
  // no one able to use or revoke it.
@@ -847,6 +1098,7 @@ async function login(args, deps) {
847
1098
  loginResult = {
848
1099
  ok: true,
849
1100
  org: exchanged.org.handle,
1101
+ workspaceHandle: exchanged.org.handle,
850
1102
  keyId: key.id,
851
1103
  scopes: key.scopes,
852
1104
  replacedCredential: previousToken === null
@@ -919,7 +1171,18 @@ async function logout(args, deps) {
919
1171
  throw new Error("Usage: foleo logout [--no-revoke] [--json]");
920
1172
  const base = apiBase(deps);
921
1173
  announceApi(deps, parsed.json);
922
- const token = await (deps.loadCredential ?? loadKeychainCredential)(base);
1174
+ let credentialHandle = deps.credentialWorkspace;
1175
+ const load = deps.loadCredential ?? loadKeychainCredential;
1176
+ let token = credentialHandle
1177
+ ? await load(base, credentialHandle)
1178
+ : await load(base);
1179
+ if (!token && credentialHandle) {
1180
+ const legacy = await (deps.loadCredential ?? loadKeychainCredential)(base);
1181
+ if (legacy && (await boundWorkspace(deps, legacy)) === credentialHandle) {
1182
+ token = legacy;
1183
+ credentialHandle = undefined;
1184
+ }
1185
+ }
923
1186
  const revocation = token === null
924
1187
  ? null
925
1188
  : noRevoke
@@ -927,7 +1190,11 @@ async function logout(args, deps) {
927
1190
  : await revokeOwnCredential(deps, token);
928
1191
  if (token !== null) {
929
1192
  try {
930
- await (deps.deleteCredential ?? deleteKeychainCredential)(base);
1193
+ const remove = deps.deleteCredential ?? deleteKeychainCredential;
1194
+ if (credentialHandle)
1195
+ await remove(base, credentialHandle);
1196
+ else
1197
+ await remove(base);
931
1198
  }
932
1199
  catch (error) {
933
1200
  throw new LocalError("keychain_delete_failed", `Unable to remove the CLI credential from macOS Keychain: ${errorMessage(error)}`, {
@@ -1056,7 +1323,7 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
1056
1323
  const entryHtml = entryFile
1057
1324
  ? new TextDecoder("utf-8").decode(entryFile.bytes)
1058
1325
  : undefined;
1059
- const derived = name ??
1326
+ let derived = name ??
1060
1327
  deriveArtifactName(root, entryHtml, {
1061
1328
  minLength: ARTIFACT_NAME_MIN_LENGTH,
1062
1329
  maxLength: ARTIFACT_NAME_MAX_LENGTH,
@@ -1082,15 +1349,40 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
1082
1349
  let cost = null;
1083
1350
  let executable = false;
1084
1351
  let reclaimable = false;
1352
+ const address = parsed.address ?? "vanity";
1353
+ let previewUrl = address === "vanity" ? artifactPreviewUrl(derived, deps) : null;
1085
1354
  try {
1086
- const result = await requestJson(deps, `/subdomains/${encodeURIComponent(derived)}`, { method: "GET", body: undefined });
1087
- availability = result.status;
1088
- reclaimable = isReclaimableByCaller(result);
1355
+ if (address === "scoped") {
1356
+ const query = new URLSearchParams({ address, name: derived });
1357
+ const result = await fetchPublishAddressPreview(query, deps);
1358
+ if (!result.label || !result.previewUrl) {
1359
+ if (result.errorCode)
1360
+ throw new FoleoError({
1361
+ code: result.errorCode,
1362
+ message: "Foleo could not find an available workspace-scoped address.",
1363
+ source: "api",
1364
+ ...(result.next ? { next: result.next } : {}),
1365
+ });
1366
+ refuseUnavailableName(derived, result.status, "Choose a different --name and preview it with --address scoped.");
1367
+ throw new FoleoError({
1368
+ code: "address_preview_unavailable",
1369
+ message: "The server did not return a candidate address.",
1370
+ source: "api",
1371
+ });
1372
+ }
1373
+ derived = result.suggestedSlug ?? result.slug ?? derived;
1374
+ previewUrl = result.previewUrl;
1375
+ reclaimable = isReclaimableByCaller(result);
1376
+ // The server can choose a suffixed scoped label if the exact slug is taken.
1377
+ availability = reclaimable ? "cooldown" : "available";
1378
+ }
1379
+ else {
1380
+ const result = await requestJson(deps, `/subdomains/${encodeURIComponent(derived)}`, { method: "GET", body: undefined });
1381
+ availability = result.status;
1382
+ reclaimable = isReclaimableByCaller(result);
1383
+ refuseUnavailableName(derived, availability, "Choose a different --name and check it first: foleo name-check <label> --json");
1384
+ }
1089
1385
  checkedAt = new Date((deps.now ?? Date.now)()).toISOString();
1090
- // Spec 089 L859: an unavailable name is a failure, not a plan — it gets
1091
- // the same stable error object a real create would fail with, not a
1092
- // buried `plan.name.availability` field an agent has to know to check.
1093
- refuseUnavailableName(derived, availability, "Choose a different --name and check it first: foleo name-check <label> --json");
1094
1386
  const usage = await requestJson(deps, "/usage", {
1095
1387
  method: "GET",
1096
1388
  body: undefined,
@@ -1130,7 +1422,6 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
1130
1422
  availability = "unknown";
1131
1423
  deps.stderr("Not signed in: this plan is bundle-only and cannot tell you whether the name is free. Run `foleo login` and plan again before publishing.\n");
1132
1424
  }
1133
- const previewUrl = artifactPreviewUrl(derived, deps);
1134
1425
  const plan = {
1135
1426
  ok: true,
1136
1427
  warnings,
@@ -1147,15 +1438,13 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
1147
1438
  checkedAt,
1148
1439
  },
1149
1440
  url: previewUrl,
1150
- // Spec 103: HTML names are vanity labels today; handle-scoped agent
1151
- // addresses (ADR 0049) are a separate, later class.
1152
1441
  address: {
1153
- class: "vanity",
1442
+ class: address,
1154
1443
  hostname: previewUrl === null ? null : new URL(previewUrl).hostname,
1155
1444
  },
1156
1445
  nameQuota: {
1157
- [NAME_QUOTA_DIMENSIONS.claimsPerDay]: 1,
1158
- [NAME_QUOTA_DIMENSIONS.activeNames]: 1,
1446
+ [NAME_QUOTA_DIMENSIONS.claimsPerDay]: address === "scoped" ? 0 : 1,
1447
+ [NAME_QUOTA_DIMENSIONS.activeNames]: address === "scoped" ? 0 : 1,
1159
1448
  },
1160
1449
  title: resolvedTitle,
1161
1450
  visibility: resolvedVisibility.value,
@@ -1210,10 +1499,10 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
1210
1499
  }
1211
1500
  async function htmlPublish(args, deps) {
1212
1501
  resolveUploadRate(deps);
1213
- const parsed = parseFlags(args);
1502
+ const parsed = parseFlags(args, { allowPublishAddress: true });
1214
1503
  const root = parsed.positionals[0];
1215
1504
  if (!root || parsed.positionals.length !== 1 || !parsed.acceptHostingRisk)
1216
- throw new Error("Usage: foleo html-publish <bundle-root> --accept-hosting-risk --name <label> [--settings <json>] [--password-stdin] [--publish-separately] [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--dry-run] [--json]\nHosted HTML is executable and may run JavaScript, show forms, or initiate downloads. A human must inspect the source and explicitly approve this risk; an agent must not infer approval.");
1505
+ throw new Error("Usage: foleo html-publish <bundle-root> --accept-hosting-risk --name <slug|label> [--address scoped|vanity] [--settings <json>] [--password-stdin] [--publish-separately] [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--dry-run] [--json]\nHosted HTML is executable and may run JavaScript, show forms, or initiate downloads. A human must inspect the source and explicitly approve this risk; an agent must not infer approval.");
1217
1506
  const settings = { ...(parsed.settings ?? {}) };
1218
1507
  // A dry run may omit --name to obtain a derived suggestion; a real create
1219
1508
  // may not (spec 089 §B).
@@ -1257,7 +1546,10 @@ async function htmlPublish(args, deps) {
1257
1546
  settings.password = password;
1258
1547
  }
1259
1548
  announceApi(deps, parsed.json);
1260
- const result = await publishBundle(root, deps, null, true, parsed.publishSeparately, settings, htmlWireOptions(parsed));
1549
+ const result = await publishBundle(root, deps, null, true, parsed.publishSeparately, settings, {
1550
+ ...htmlWireOptions(parsed),
1551
+ ...(parsed.address ? { address: parsed.address } : {}),
1552
+ });
1261
1553
  writeResult(deps, result, parsed.json);
1262
1554
  return 0;
1263
1555
  }
@@ -1751,6 +2043,7 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
1751
2043
  uploadId: upload.uploadId,
1752
2044
  manifestHash: upload.manifestHash,
1753
2045
  hostingRiskAcknowledged,
2046
+ ...(wire.address ? { address: wire.address } : {}),
1754
2047
  source,
1755
2048
  ...(publishSeparately ? { allowDuplicate: true } : {}),
1756
2049
  ...(settings && Object.keys(settings).length > 0
@@ -2281,15 +2574,50 @@ async function boundedReadFileBytes(path, maxBytes, realBase) {
2281
2574
  }
2282
2575
  return result;
2283
2576
  }
2577
+ function fetchPublishAddressPreview(query, deps) {
2578
+ return requestJson(deps, "/artifacts/address-preview?" + query, {
2579
+ method: "GET",
2580
+ body: undefined,
2581
+ });
2582
+ }
2583
+ async function previewPublishAddress(args, deps) {
2584
+ const query = new URLSearchParams();
2585
+ for (let i = 0; i < args.length; i++) {
2586
+ const flag = args[i];
2587
+ if (flag === "--json" || flag === "--preview")
2588
+ continue;
2589
+ const field = flag.slice(2);
2590
+ const value = args[++i];
2591
+ if (!["--address", "--name", "--title"].includes(flag) ||
2592
+ query.has(field) ||
2593
+ !value?.trim() ||
2594
+ value.startsWith("--"))
2595
+ throw new UsageError(PUBLISH_PREVIEW_USAGE);
2596
+ query.set(field, value);
2597
+ }
2598
+ if (!query.has("address"))
2599
+ query.set("address", "scoped");
2600
+ if (!["scoped", "vanity"].includes(query.get("address")) ||
2601
+ (!query.has("name") && !query.has("title")))
2602
+ throw new UsageError(PUBLISH_PREVIEW_USAGE);
2603
+ const result = await fetchPublishAddressPreview(query, deps);
2604
+ deps.stdout(JSON.stringify(result, null, 2) + "\n");
2605
+ return 0;
2606
+ }
2607
+ const PUBLISH_PREVIEW_USAGE = "Usage: foleo publish --preview [--address scoped|vanity] (--name <label> | --title <title>) [--json]";
2284
2608
  async function publish(args, deps) {
2609
+ if (args[0] === "--preview")
2610
+ return previewPublishAddress(args, deps);
2285
2611
  resolveUploadRate(deps);
2286
- const parsed = parseFlags(args);
2612
+ const parsed = parseFlags(args, { allowPublishAddress: true });
2287
2613
  const file = parsed.positionals[0];
2288
2614
  if (!file || parsed.positionals.length !== 1)
2289
- throw new Error("Usage: foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--accept-hosting-risk] [--name <label>] [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json]\nAn HTML site bundle also requires --name <label>; Markdown does not.");
2615
+ throw new Error("Usage: foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--accept-hosting-risk] [--name <slug|label>] [--address scoped|vanity] [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json]\nAn HTML site bundle also requires --name <label>; Markdown does not.");
2290
2616
  const isDirectory = await pathIsDirectory(file, deps);
2291
2617
  if (parsed.optimizeImages && !isDirectory)
2292
2618
  throw new UsageError("--optimize-images applies to an HTML bundle folder", "image_optimization_not_applicable");
2619
+ if (!isDirectory && parsed.address !== undefined)
2620
+ throw new UsageError("--address applies only to creating or previewing an HTML publication.", "address_not_applicable");
2293
2621
  if (!isDirectory && parsed.dryRun) {
2294
2622
  throw new UsageError("--dry-run is only implemented for HTML site bundles (a directory with --accept-hosting-risk). A Markdown publish is not previewable yet; run it without --dry-run, or use `foleo publish <dir> --accept-hosting-risk --name <label> --dry-run`.", "dry_run_unsupported", { sourceFormat: "markdown" });
2295
2623
  }
@@ -2328,7 +2656,59 @@ async function publish(args, deps) {
2328
2656
  writeResult(deps, withImageReport(result, assets?.warnings ?? []), parsed.json);
2329
2657
  return 0;
2330
2658
  }
2659
+ const ARTIFACT_EDIT_USAGE = "Usage: foleo update <id> --edits <json-file> --base-content-hash <sha256> --revision <etag> --idempotency-key <key> [--json]";
2660
+ async function updateMarkdownEdits(args, deps) {
2661
+ const [id, ...rest] = args;
2662
+ const values = new Map();
2663
+ let json = false;
2664
+ for (let i = 0; i < rest.length; i++) {
2665
+ const flag = rest[i];
2666
+ if (flag === "--json") {
2667
+ json = true;
2668
+ continue;
2669
+ }
2670
+ const value = rest[++i];
2671
+ if (![
2672
+ "--edits",
2673
+ "--base-content-hash",
2674
+ "--revision",
2675
+ "--idempotency-key",
2676
+ ].includes(flag) ||
2677
+ values.has(flag) ||
2678
+ !value ||
2679
+ value.startsWith("--"))
2680
+ throw new UsageError(ARTIFACT_EDIT_USAGE);
2681
+ values.set(flag, value);
2682
+ }
2683
+ const file = values.get("--edits");
2684
+ const baseContentHash = values.get("--base-content-hash");
2685
+ const revision = artifactRevision(values.get("--revision"));
2686
+ const key = values.get("--idempotency-key");
2687
+ if (!id ||
2688
+ !file ||
2689
+ !baseContentHash ||
2690
+ !/^[0-9a-f]{64}$/u.test(baseContentHash) ||
2691
+ !revision ||
2692
+ !key ||
2693
+ !/^[\x21-\x7e]{8,200}$/u.test(key))
2694
+ throw new UsageError(ARTIFACT_EDIT_USAGE);
2695
+ const edits = await readEditsFile(file);
2696
+ const result = await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
2697
+ method: "PUT",
2698
+ headers: artifactMutationHeaders(revision, key),
2699
+ body: {
2700
+ sourceFormat: "markdown",
2701
+ edits,
2702
+ baseContentHash,
2703
+ stagedAssets: [],
2704
+ },
2705
+ });
2706
+ writeResult(deps, result, json);
2707
+ return 0;
2708
+ }
2331
2709
  async function update(args, deps) {
2710
+ if (args[1] === "--edits")
2711
+ return updateMarkdownEdits(args, deps);
2332
2712
  resolveUploadRate(deps);
2333
2713
  const parsed = parseFlags(args);
2334
2714
  const [id, file] = parsed.positionals;
@@ -2664,6 +3044,44 @@ async function uploadMarkdownAssets(markdownPath, markdown, deps, json, reuseFro
2664
3044
  },
2665
3045
  };
2666
3046
  }
3047
+ const REPUBLISH_USAGE = "Usage: foleo republish <id> --revision <etag> --idempotency-key <key> [--acknowledge-access-widening] [--json]";
3048
+ async function republish(args, deps) {
3049
+ const parsed = (() => {
3050
+ try {
3051
+ return parseArgs({
3052
+ args,
3053
+ allowPositionals: true,
3054
+ options: {
3055
+ revision: { type: "string" },
3056
+ "idempotency-key": { type: "string" },
3057
+ "acknowledge-access-widening": { type: "boolean" },
3058
+ json: { type: "boolean" },
3059
+ },
3060
+ });
3061
+ }
3062
+ catch {
3063
+ throw new UsageError(REPUBLISH_USAGE);
3064
+ }
3065
+ })();
3066
+ const [id] = parsed.positionals;
3067
+ const revision = artifactRevision(parsed.values.revision);
3068
+ const key = parsed.values["idempotency-key"];
3069
+ if (!id ||
3070
+ parsed.positionals.length !== 1 ||
3071
+ revision === null ||
3072
+ !key ||
3073
+ !/^[\x21-\x7e]{8,200}$/u.test(key))
3074
+ throw new UsageError(REPUBLISH_USAGE);
3075
+ const result = await withRateLimitRetry(deps, "republishing the artifact", () => requestJson(deps, `/artifacts/${encodeURIComponent(id)}/republish`, {
3076
+ method: "POST",
3077
+ body: parsed.values["acknowledge-access-widening"]
3078
+ ? accessWideningField(true)
3079
+ : undefined,
3080
+ headers: artifactMutationHeaders(revision, key),
3081
+ }));
3082
+ writeResult(deps, result, parsed.values.json === true);
3083
+ return 0;
3084
+ }
2667
3085
  async function unpublish(args, deps) {
2668
3086
  const parsed = parseFlags(args);
2669
3087
  const id = parsed.positionals[0];
@@ -3291,11 +3709,12 @@ async function whoami(args, deps) {
3291
3709
  method: "GET",
3292
3710
  body: undefined,
3293
3711
  });
3712
+ const workspaceHandle = workspaceFromMe(result) ?? (await boundWorkspace(deps, credential.token));
3294
3713
  if (parsed.json) {
3295
- deps.stdout(`${JSON.stringify({ ...(isRecord(result) ? result : { me: result }), credentialSource: credential.source, environment: environmentInfo(deps) }, null, 2)}\n`);
3714
+ deps.stdout(`${JSON.stringify({ workspaceHandle, ...(isRecord(result) ? result : { me: result }), credentialSource: credential.source, environment: environmentInfo(deps) }, null, 2)}\n`);
3296
3715
  return 0;
3297
3716
  }
3298
- deps.stdout(`${whoamiText(result, credential.source)}Environment: ${environmentInfo(deps).name}\nAPI: ${environmentInfo(deps).apiBase}\n`);
3717
+ deps.stdout(`${whoamiText(result, credential.source)}Workspace: ${workspaceHandle ?? "unknown (run foleo login)"}\nEnvironment: ${environmentInfo(deps).name}\nAPI: ${environmentInfo(deps).apiBase}\n`);
3299
3718
  return 0;
3300
3719
  }
3301
3720
  function environmentCommand(args, deps) {
@@ -3541,7 +3960,8 @@ async function requestJsonWithToken(deps, path, token, init) {
3541
3960
  const key = init.headers?.["idempotency-key"];
3542
3961
  const receiptWrite = key &&
3543
3962
  (init.method === "POST" || init.method === "PUT") &&
3544
- /^\/(?:artifacts(?:\/html)?|docs)(?:\/[^/]+)?$/u.test(path);
3963
+ (/^\/(?:artifacts(?:\/html)?|docs)(?:\/[^/]+)?$/u.test(path) ||
3964
+ /^\/artifacts\/[^/]+\/republish$/u.test(path));
3545
3965
  let response;
3546
3966
  let body;
3547
3967
  for (let retry = 0;; retry++) {
@@ -3604,7 +4024,7 @@ async function requestJsonWithToken(deps, path, token, init) {
3604
4024
  class ApiRequestError extends FoleoError {
3605
4025
  status;
3606
4026
  body;
3607
- constructor(status, code, body) {
4027
+ constructor(status, code, body, workspace = false) {
3608
4028
  const next = apiErrorNext(body);
3609
4029
  const envelope = isRecord(body) && isRecord(body.error) ? body.error : null;
3610
4030
  // Spec 103: preserve the server's `retryable` verbatim, and carry the
@@ -3616,7 +4036,14 @@ class ApiRequestError extends FoleoError {
3616
4036
  : null;
3617
4037
  super({
3618
4038
  code,
3619
- message: code === "bundle_new_files_limit" &&
4039
+ message: (code === "bundle_new_files_limit" ||
4040
+ code === "site_move_out_unavailable" ||
4041
+ (workspace &&
4042
+ ![
4043
+ "approval_required",
4044
+ "input_required",
4045
+ "acknowledgement_required",
4046
+ ].includes(code))) &&
3620
4047
  typeof envelope?.message === "string"
3621
4048
  ? envelope.message
3622
4049
  : code === "matching_source_exists"
@@ -3650,9 +4077,11 @@ class ApiRequestError extends FoleoError {
3650
4077
  .filter((field) => envelope[field] !== undefined)
3651
4078
  .map((field) => [field, envelope[field]])),
3652
4079
  }
3653
- : references === null
3654
- ? {}
3655
- : { context: { references } }),
4080
+ : references !== null
4081
+ ? { context: { references } }
4082
+ : workspace && isRecord(envelope?.details)
4083
+ ? { context: envelope.details }
4084
+ : {}),
3656
4085
  });
3657
4086
  this.name = "ApiRequestError";
3658
4087
  this.status = status;
@@ -3764,8 +4193,8 @@ allowReplay = false) {
3764
4193
  throw new ApiRequestError(response.status, apiErrorCode(body, response.status), body);
3765
4194
  }
3766
4195
  }
3767
- function apiResponseError(status, body) {
3768
- return new ApiRequestError(status, apiErrorCode(body, status), body);
4196
+ function apiResponseError(status, body, workspace = false) {
4197
+ return new ApiRequestError(status, apiErrorCode(body, status), body, workspace);
3769
4198
  }
3770
4199
  function apiBase(deps) {
3771
4200
  const selected = deps.env.FOLEO_ENV ?? "production";
@@ -3828,38 +4257,42 @@ async function resolveCredentialWithSource(deps) {
3828
4257
  if (deps.env.FOLEO_TOKEN)
3829
4258
  return { token: deps.env.FOLEO_TOKEN, source: "env" };
3830
4259
  const base = apiBase(deps);
3831
- const cliToken = await (deps.loadCredential ?? loadKeychainCredential)(base);
4260
+ const load = deps.loadCredential ?? loadKeychainCredential;
4261
+ const cliToken = deps.credentialWorkspace
4262
+ ? ((await load(base, deps.credentialWorkspace)) ?? (await load(base)))
4263
+ : await load(base);
3832
4264
  if (cliToken)
3833
4265
  return { token: cliToken, source: "cli-keychain" };
3834
4266
  return null;
3835
4267
  }
3836
- function keychainAccount(apiBaseUrl) {
3837
- return createHash("sha256").update(apiBaseUrl).digest("hex");
4268
+ export function keychainAccount(apiBaseUrl, handle) {
4269
+ return (createHash("sha256").update(apiBaseUrl).digest("hex") +
4270
+ (handle ? `:workspace:${handle}` : ""));
3838
4271
  }
3839
4272
  async function keyringAsyncEntry() {
3840
4273
  const module = (await Function("specifier", "return import(specifier)")("@napi-rs/keyring"));
3841
4274
  return module.AsyncEntry;
3842
4275
  }
3843
- async function keychainEntry(apiBaseUrl, suffix = "") {
4276
+ async function keychainEntry(apiBaseUrl, handle, suffix = "") {
3844
4277
  const AsyncEntry = await keyringAsyncEntry();
3845
- return new AsyncEntry(KEYCHAIN_SERVICE, `${keychainAccount(apiBaseUrl)}${suffix}`);
4278
+ return new AsyncEntry(KEYCHAIN_SERVICE, `${keychainAccount(apiBaseUrl, handle)}${suffix}`);
3846
4279
  }
3847
- async function loadKeychainCredential(apiBaseUrl) {
4280
+ async function loadKeychainCredential(apiBaseUrl, handle) {
3848
4281
  try {
3849
- return (await (await keychainEntry(apiBaseUrl)).getPassword()) ?? null;
4282
+ return ((await (await keychainEntry(apiBaseUrl, handle)).getPassword()) ?? null);
3850
4283
  }
3851
4284
  catch {
3852
4285
  return null;
3853
4286
  }
3854
4287
  }
3855
- async function saveKeychainCredential(apiBaseUrl, token) {
3856
- await (await keychainEntry(apiBaseUrl)).setPassword(token);
4288
+ async function saveKeychainCredential(apiBaseUrl, token, handle) {
4289
+ await (await keychainEntry(apiBaseUrl, handle)).setPassword(token);
3857
4290
  }
3858
- async function deleteKeychainCredential(apiBaseUrl) {
3859
- await (await keychainEntry(apiBaseUrl)).deleteCredential();
4291
+ async function deleteKeychainCredential(apiBaseUrl, handle) {
4292
+ await (await keychainEntry(apiBaseUrl, handle)).deleteCredential();
3860
4293
  }
3861
4294
  async function verifyKeychainWritable(apiBaseUrl) {
3862
- const entry = await keychainEntry(apiBaseUrl, ":probe");
4295
+ const entry = await keychainEntry(apiBaseUrl, undefined, ":probe");
3863
4296
  const probe = `foleo_probe_${randomUUID()}`;
3864
4297
  try {
3865
4298
  await entry.setPassword(probe);
@@ -4227,10 +4660,12 @@ function parseFlags(args, options = {}) {
4227
4660
  let acceptHostingRisk = false;
4228
4661
  let publishSeparately = false;
4229
4662
  let allowDelete = false;
4663
+ let noBrowser = false;
4230
4664
  let allowPurge = false;
4231
4665
  let allowWorkspaces = false;
4232
4666
  let allowWorkspaceSharing = false;
4233
4667
  let name;
4668
+ let address;
4234
4669
  let dryRun = false;
4235
4670
  let optimizeImages;
4236
4671
  let previous;
@@ -4257,6 +4692,13 @@ function parseFlags(args, options = {}) {
4257
4692
  throw new UsageError("--name requires a value", "name_missing");
4258
4693
  continue;
4259
4694
  }
4695
+ if (arg === "--address" && options.allowPublishAddress) {
4696
+ const value = args[++i];
4697
+ if (address || (value !== "scoped" && value !== "vanity"))
4698
+ throw new UsageError("--address requires one of scoped or vanity.", "address_invalid");
4699
+ address = value;
4700
+ continue;
4701
+ }
4260
4702
  if (arg === "--optimize-images") {
4261
4703
  optimizeImages = true;
4262
4704
  continue;
@@ -4386,6 +4828,12 @@ function parseFlags(args, options = {}) {
4386
4828
  throw new Error("--cursor requires a value");
4387
4829
  continue;
4388
4830
  }
4831
+ if (arg === "--no-browser") {
4832
+ if (!options.allowLoginScopeFlags)
4833
+ throw new UsageError("--no-browser is valid only with login");
4834
+ noBrowser = true;
4835
+ continue;
4836
+ }
4389
4837
  if (arg === "--allow-delete") {
4390
4838
  if (!options.allowLoginScopeFlags)
4391
4839
  throw new Error("--allow-delete is valid only with login");
@@ -4430,10 +4878,12 @@ function parseFlags(args, options = {}) {
4430
4878
  acceptHostingRisk,
4431
4879
  publishSeparately,
4432
4880
  allowDelete,
4881
+ noBrowser,
4433
4882
  allowPurge,
4434
4883
  allowWorkspaces,
4435
4884
  allowWorkspaceSharing,
4436
4885
  ...(name === undefined ? {} : { name }),
4886
+ ...(address === undefined ? {} : { address }),
4437
4887
  dryRun,
4438
4888
  optimizeImages,
4439
4889
  ...(previous === undefined ? {} : { previous }),
@@ -4444,13 +4894,228 @@ function parseFlags(args, options = {}) {
4444
4894
  ...(cursor === undefined ? {} : { cursor }),
4445
4895
  };
4446
4896
  }
4897
+ async function defaultWorkspaceFor(deps) {
4898
+ return (deps.loadDefaultWorkspace ?? ((api) => loadDefaultWorkspace(deps.env, api)))(apiBase(deps));
4899
+ }
4900
+ async function persistDefaultWorkspace(deps, handle) {
4901
+ await (deps.saveDefaultWorkspace ??
4902
+ ((api, h) => saveDefaultWorkspace(deps.env, api, h)))(apiBase(deps), handle);
4903
+ }
4904
+ async function useWorkspace(args, deps) {
4905
+ const handles = args.filter((a) => a !== "--json");
4906
+ if (handles.length !== 1 || !/^[a-z0-9-]{1,63}$/u.test(handles[0]))
4907
+ throw new UsageError("Usage: foleo use <handle> [--json]");
4908
+ const handle = handles[0], base = apiBase(deps), load = deps.loadCredential ?? loadKeychainCredential;
4909
+ const named = await load(base, handle), legacy = named ? null : await load(base), token = named ?? legacy;
4910
+ if (!token)
4911
+ throw new LocalError("credential_missing", `Run foleo login --workspace ${handle}.`);
4912
+ // Deliberately bypass the command's current default header. Live identity must
4913
+ // match before persisting the hint, even if local binding metadata is stale.
4914
+ const response = await deps.fetch(base + "/me", {
4915
+ headers: { authorization: `Bearer ${token}`, "Foleo-Workspace": handle },
4916
+ });
4917
+ if (!response.ok)
4918
+ throw apiResponseError(response.status, await response.json());
4919
+ const bound = workspaceFromMe(await response.json());
4920
+ if (bound !== handle)
4921
+ throw workspaceMismatch(bound ?? "unknown", handle);
4922
+ await (deps.saveWorkspaceBinding ??
4923
+ ((api, token, h) => saveWorkspaceBinding(deps.env, api, token, h)))(base, token, handle);
4924
+ await persistDefaultWorkspace(deps, handle);
4925
+ deps.stdout(args.includes("--json")
4926
+ ? JSON.stringify({ defaultWorkspaceHandle: handle }) + "\n"
4927
+ : `Default workspace: ${handle}\n`);
4928
+ return 0;
4929
+ }
4930
+ function isTreeId(value) {
4931
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(value);
4932
+ }
4933
+ function workspaceFromMe(value) {
4934
+ const org = nestedRecord(value, "org");
4935
+ return ((org ? stringField(org, "handle") : null) ??
4936
+ (isRecord(value) ? stringField(value, "orgHandle") : null));
4937
+ }
4938
+ async function boundWorkspace(deps, token) {
4939
+ return (deps.loadWorkspaceBinding ??
4940
+ ((api, credential) => loadWorkspaceBinding(deps.env, api, credential)))(apiBase(deps), token);
4941
+ }
4942
+ function workspaceMismatch(bound, requested) {
4943
+ return new LocalError("workspace_mismatch", `This login is for ${bound}. Run foleo login --workspace ${requested}.`, {
4944
+ next: `Run foleo login --workspace ${requested}.`,
4945
+ context: {
4946
+ boundWorkspaceHandle: bound,
4947
+ requestedWorkspaceHandle: requested,
4948
+ },
4949
+ });
4950
+ }
4951
+ const WORKSPACES_HELP = `Usage: foleo workspaces [ls] [--json]
4952
+ foleo workspaces create <name> [--address <handle>] [--mutation-id <id>] [--json]
4953
+ Lists workspace addresses, names, roles, stored logins and the default; * marks the active login.
4954
+ foleo use <handle> [--json]
4955
+ Requires workspace read consent (create also needs write): foleo login --allow-workspaces.
4956
+ Creation keeps this login in its current workspace. To use the new one:
4957
+ foleo login --workspace <handle>
4958
+ `;
4959
+ async function workspaceOrganizations(args, deps) {
4960
+ if (args.includes("--help") || args.includes("-h")) {
4961
+ deps.stdout(WORKSPACES_HELP);
4962
+ return 0;
4963
+ }
4964
+ const flags = new Map();
4965
+ const positional = [];
4966
+ for (let i = 0; i < args.length; i++) {
4967
+ const arg = args[i];
4968
+ if (arg === "--json")
4969
+ continue;
4970
+ if (arg.startsWith("--")) {
4971
+ const value = args[++i];
4972
+ if (!["--address", "--mutation-id"].includes(arg) ||
4973
+ !value ||
4974
+ value.startsWith("--") ||
4975
+ flags.has(arg))
4976
+ throw new UsageError(WORKSPACES_HELP);
4977
+ flags.set(arg, value);
4978
+ }
4979
+ else
4980
+ positional.push(arg);
4981
+ }
4982
+ const create = positional[0] === "create";
4983
+ if (create
4984
+ ? positional.length !== 2
4985
+ : positional.length > 1 ||
4986
+ (positional.length === 1 && positional[0] !== "ls") ||
4987
+ flags.size > 0)
4988
+ throw new UsageError(WORKSPACES_HELP);
4989
+ const name = positional[1]?.trim();
4990
+ const handle = flags.get("--address") ??
4991
+ name
4992
+ ?.normalize("NFKD")
4993
+ .replace(/[\u0300-\u036f]/gu, "")
4994
+ .toLowerCase()
4995
+ .replace(/[^a-z0-9]+/gu, "-")
4996
+ .replace(/^-+|-+$/gu, "");
4997
+ if (create &&
4998
+ (!name || name.length > 120 || !handle || !/^[a-z0-9-]+$/u.test(handle)))
4999
+ throw new UsageError("Use a name (1–120 characters) and --address with a lowercase handle.");
5000
+ try {
5001
+ if (create) {
5002
+ const result = await requestJson(deps, "/me/workspaces", {
5003
+ method: "POST",
5004
+ body: {
5005
+ name,
5006
+ handle,
5007
+ clientMutationId: flags.get("--mutation-id") ?? randomUUID(),
5008
+ },
5009
+ });
5010
+ if (args.includes("--json"))
5011
+ deps.stdout(JSON.stringify(result, null, 2) + "\n");
5012
+ else
5013
+ deps.stdout(`Created ${result.workspace.name}: ${result.workspace.handle}.foleo.site\nThis login stays in ${result.boundWorkspaceHandle}. Run foleo login --workspace ${result.workspace.handle} to work in the new workspace.\n`);
5014
+ }
5015
+ else {
5016
+ const listing = await requestJson(deps, "/me/workspaces", { method: "GET", body: undefined });
5017
+ const workspaces = Array.isArray(listing) ? listing : listing.workspaces;
5018
+ const credential = await resolveCredentialWithSource(deps);
5019
+ let bound = !Array.isArray(listing)
5020
+ ? listing.boundWorkspaceHandle
5021
+ : credential
5022
+ ? await boundWorkspace(deps, credential.token)
5023
+ : null;
5024
+ if (!bound)
5025
+ bound = workspaceFromMe(await requestJson(deps, "/me", { method: "GET", body: undefined }));
5026
+ const defaultHandle = (await defaultWorkspaceFor(deps)) ??
5027
+ workspaces.find((w) => w.kind === "personal")?.handle ??
5028
+ bound;
5029
+ const stored = new Map();
5030
+ const load = deps.loadCredential ?? loadKeychainCredential;
5031
+ const legacy = await load(apiBase(deps));
5032
+ const legacyHandle = legacy ? await boundWorkspace(deps, legacy) : null;
5033
+ for (const w of workspaces)
5034
+ stored.set(w.handle, !!(await load(apiBase(deps), w.handle)) ||
5035
+ (legacy !== null &&
5036
+ (legacyHandle === w.handle ||
5037
+ (!legacyHandle && w.kind === "personal"))));
5038
+ if (args.includes("--json"))
5039
+ deps.stdout(JSON.stringify({
5040
+ defaultWorkspaceHandle: defaultHandle,
5041
+ workspaces: workspaces.map((w) => ({
5042
+ ...w,
5043
+ bound: w.handle === bound,
5044
+ storedLogin: stored.get(w.handle),
5045
+ default: w.handle === defaultHandle,
5046
+ })),
5047
+ boundWorkspaceHandle: bound,
5048
+ }, null, 2) + "\n");
5049
+ else {
5050
+ for (const w of workspaces)
5051
+ deps.stdout(`${w.handle === bound ? "*" : " "} ${w.handle}\t${w.name}\t${w.role}\t${stored.get(w.handle) ? "logged in" : "no stored login"}${w.handle === defaultHandle ? " (default)" : ""}\n`);
5052
+ deps.stdout(bound
5053
+ ? `* This login is bound to ${bound}.\n`
5054
+ : "Bound workspace unknown; run foleo whoami.\n");
5055
+ }
5056
+ }
5057
+ }
5058
+ catch (error) {
5059
+ if (error instanceof FoleoError && error.code === "session_required")
5060
+ throw new LocalError("session_required", "This server does not allow CLI credentials to list or create workspaces yet.", {
5061
+ next: "Use Foleo's web workspace picker. CLI access needs server support.",
5062
+ });
5063
+ throw error;
5064
+ }
5065
+ return 0;
5066
+ }
5067
+ const EDIT_LITERAL_FLAGS = new Set(["--find", "--replace"]);
4447
5068
  function parseGlobalFlags(argv) {
4448
- const selected = argv.filter((arg) => ["--production", "--staging", "--local"].includes(arg));
5069
+ let workspace;
5070
+ const filtered = [];
5071
+ const editLiteralValues = new Set();
5072
+ for (let i = 0; i < argv.length; i++) {
5073
+ if (EDIT_LITERAL_FLAGS.has(argv[i]) &&
5074
+ filtered.find((arg) => !["--production", "--staging", "--local"].includes(arg)) === "edit" &&
5075
+ argv[i + 1] !== undefined) {
5076
+ filtered.push(argv[i], argv[++i]);
5077
+ editLiteralValues.add(filtered.length - 1);
5078
+ continue;
5079
+ }
5080
+ if (argv[i] !== "--workspace") {
5081
+ filtered.push(argv[i]);
5082
+ continue;
5083
+ }
5084
+ const value = argv[++i];
5085
+ if (workspace ||
5086
+ !value ||
5087
+ (!isTreeId(value) && !/^[a-z0-9-]+$/u.test(value)))
5088
+ throw new UsageError("--workspace requires one lowercase handle or UUID tree ID.");
5089
+ workspace = value;
5090
+ }
5091
+ const command = filtered.find((arg) => !["--production", "--staging", "--local"].includes(arg));
5092
+ if (workspace && isTreeId(workspace)) {
5093
+ if (![
5094
+ "save",
5095
+ "edit",
5096
+ "read",
5097
+ "share",
5098
+ "ls",
5099
+ "list",
5100
+ "search",
5101
+ "history",
5102
+ "recent",
5103
+ "move",
5104
+ "trash",
5105
+ "undo",
5106
+ ].includes(command ?? ""))
5107
+ throw new UsageError("A UUID --workspace tree ID is supported only on cloud-file commands.");
5108
+ filtered.push("--workspace", workspace);
5109
+ }
5110
+ const selected = filtered.filter((arg, index) => !editLiteralValues.has(index) &&
5111
+ ["--production", "--staging", "--local"].includes(arg));
4449
5112
  if (new Set(selected).size > 1)
4450
5113
  throw new Error("Choose only one of --production, --staging, or --local");
4451
5114
  const environment = selected[0]?.slice(2);
4452
5115
  return {
4453
- argv: argv.filter((arg) => !["--production", "--staging", "--local"].includes(arg)),
5116
+ ...(workspace ? { workspace } : {}),
5117
+ argv: filtered.filter((arg, index) => editLiteralValues.has(index) ||
5118
+ !["--production", "--staging", "--local"].includes(arg)),
4454
5119
  ...(environment ? { environment } : {}),
4455
5120
  };
4456
5121
  }
@@ -4458,10 +5123,20 @@ function help() {
4458
5123
  return [
4459
5124
  "Usage:",
4460
5125
  " foleo --help",
4461
- " foleo login [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]",
5126
+ " foleo login [--workspace <handle>] [--no-browser] [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]",
5127
+ " Login always prints the sign-in URL to stderr; --no-browser skips opening it.",
5128
+ " The approving browser must be on this computer (the callback is local).",
4462
5129
  " foleo logout [--no-revoke] [--json]",
4463
- " Workspace access is offered only to invited alpha accounts; browser consent starts unchecked.",
5130
+ " Workspace access is offered only to invited alpha accounts; role-permitted requested browser permissions start checked; untick to decline.",
4464
5131
  " --allow-workspaces requests read + write; --allow-workspace-sharing requests share + read.",
5132
+ SHARED_HELP,
5133
+ " foleo mv <path> --to-workspace <handle> [--to <folder>] [--yes] [--json]",
5134
+ MOVE_HELP,
5135
+ " foleo workspaces [ls] [--json]",
5136
+ " foleo workspaces create <name> [--address <handle>] [--mutation-id <id>] [--json]",
5137
+ " --workspace <handle> chooses its stored login and sends Foleo-Workspace; each credential must match.",
5138
+ " foleo use <handle> sets the default for this API; foleo workspaces shows stored logins.",
5139
+ " Cloud-file commands also accept a UUID tree ID in --workspace.",
4465
5140
  " foleo whoami [--json]",
4466
5141
  " foleo doctor [--json]",
4467
5142
  " foleo skill get|path",
@@ -4470,8 +5145,14 @@ function help() {
4470
5145
  " foleo list [--kind <kind>] [--format <format>] [--runtime <class>] [--limit <n>] [--json]",
4471
5146
  " foleo get <id> [--json]",
4472
5147
  " foleo export <id> <dir> [--force] [--json] (source and assets; SHA-256 verified)",
5148
+ " " + PUBLISH_PREVIEW_USAGE.replace("Usage: ", ""),
4473
5149
  " foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--acknowledge-access-widening] [--json]",
4474
- " foleo publish <dir> --accept-hosting-risk --name <label> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--dry-run] [--json]",
5150
+ " foleo publish <dir> --accept-hosting-risk --name <slug|label> [--address scoped|vanity] [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--dry-run] [--json]",
5151
+ " " + ARTIFACT_EDIT_USAGE.replace("Usage: ", ""),
5152
+ " " + REPUBLISH_USAGE.replace("Usage: ", ""),
5153
+ " foleo approval get <id> [--json]",
5154
+ " foleo approval commit <id> --idempotency-key <key> [--json]",
5155
+ " For a staged publication, open the Foleo review link, check approval status, then commit.",
4475
5156
  " foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json]",
4476
5157
  " foleo update <id> <file.md> --version <version> [--acknowledge-access-widening] [--json] (compatibility)",
4477
5158
  " Identical updates may return unchanged: true; revision/ETag stay unchanged. Retry an interrupted request with the same idempotency key.",