@usehandout/cli 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/handout.mjs CHANGED
@@ -5120,7 +5120,7 @@ var recursive = new WeakMap();
5120
5120
  var NONE = 0;
5121
5121
  var ASSUMED = 1;
5122
5122
  var PROVEN = 2;
5123
- function isRecursive(inst, stack, resolve2) {
5123
+ function isRecursive(inst, stack, resolve3) {
5124
5124
  const cached2 = recursive.get(inst);
5125
5125
  if (cached2 !== void 0)
5126
5126
  return cached2 ? PROVEN : NONE;
@@ -5130,7 +5130,7 @@ function isRecursive(inst, stack, resolve2) {
5130
5130
  let result2 = NONE;
5131
5131
  const check2 = (child) => {
5132
5132
  if (result2 !== PROVEN && child?._zod) {
5133
- const answer = isRecursive(child, stack, resolve2);
5133
+ const answer = isRecursive(child, stack, resolve3);
5134
5134
  if (answer > result2)
5135
5135
  result2 = answer;
5136
5136
  }
@@ -5141,7 +5141,7 @@ function isRecursive(inst, stack, resolve2) {
5141
5141
  const desc = Object.getOwnPropertyDescriptor(sh, key);
5142
5142
  if (spread && !desc.enumerable)
5143
5143
  continue;
5144
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve2) : NONE;
5144
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
5145
5145
  if (child > answer)
5146
5146
  answer = child;
5147
5147
  }
@@ -5204,7 +5204,7 @@ function isRecursive(inst, stack, resolve2) {
5204
5204
  check2(def.output);
5205
5205
  break;
5206
5206
  case "lazy": {
5207
- const inner = def._cachedInner ?? (resolve2 ? inst._zod.innerType : void 0);
5207
+ const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
5208
5208
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
5209
5209
  break;
5210
5210
  }
@@ -19652,7 +19652,6 @@ var ReportAppeal = external_exports.object({
19652
19652
  statement: external_exports.string().max(APPEAL_STATEMENT_MAX_LENGTH).optional(),
19653
19653
  counterNotice: CounterNotice.optional(),
19654
19654
  dueAt: external_exports.string().optional(),
19655
- escalatedAt: external_exports.string().optional(),
19656
19655
  forwardedAt: external_exports.string().optional(),
19657
19656
  forwardedBy: external_exports.string().optional(),
19658
19657
  restoreAfter: external_exports.string().optional(),
@@ -19689,14 +19688,13 @@ var ReportRecord = external_exports.object({
19689
19688
  receiptTo: external_exports.string().optional(),
19690
19689
  acknowledgedAt: external_exports.string().optional(),
19691
19690
  acknowledgedBy: external_exports.string().optional(),
19692
- ackEscalatedAt: external_exports.string().optional(),
19693
- overdueEscalatedAt: external_exports.string().optional(),
19694
19691
  evidence: external_exports.array(EvidenceItem).optional(),
19695
19692
  appeal: ReportAppeal.optional()
19696
19693
  }).refine((report) => report.targetType === "url" ? report.submittedUrl !== void 0 && report.documentId === void 0 && report.collectionId === void 0 : report.workspaceId !== void 0 && (report.targetType === "document" ? report.documentId !== void 0 && report.collectionId === void 0 : report.collectionId !== void 0 && report.documentId === void 0), {
19697
19694
  message: "A report names exactly one target: documentId for a document, collectionId for a collection."
19698
19695
  });
19699
19696
  var ContentType = external_exports.enum(["html", "markdown", "pdf"]);
19697
+ var DefaultFormat = ContentType;
19700
19698
  function isBinaryContentType(contentType) {
19701
19699
  return contentType === "pdf";
19702
19700
  }
@@ -19772,7 +19770,32 @@ var MAX_LABELS_PER_DOCUMENT = 10;
19772
19770
  var MAX_LABELS_MESSAGE = "A document can have at most 10 labels.";
19773
19771
  var MAX_SUGGESTED_LABELS = 30;
19774
19772
  var MAX_SUGGESTED_LABELS_MESSAGE = `A workspace can have at most ${MAX_SUGGESTED_LABELS} suggested labels.`;
19773
+ var SEED_SUGGESTED_LABELS = [
19774
+ "plan",
19775
+ "spec",
19776
+ "report",
19777
+ "review",
19778
+ "guide",
19779
+ "notes",
19780
+ "proposal",
19781
+ "prototype"
19782
+ ];
19775
19783
  var SuggestedLabels = external_exports.array(DocumentLabel).max(MAX_SUGGESTED_LABELS, MAX_SUGGESTED_LABELS_MESSAGE);
19784
+ function normalizeSuggestedLabels(labels) {
19785
+ const seen = new Set();
19786
+ const result2 = [];
19787
+ for (const label of labels) {
19788
+ const trimmed = label.trim();
19789
+ if (trimmed === "")
19790
+ continue;
19791
+ const key = trimmed.toLowerCase();
19792
+ if (seen.has(key))
19793
+ continue;
19794
+ seen.add(key);
19795
+ result2.push(trimmed);
19796
+ }
19797
+ return result2;
19798
+ }
19776
19799
  var PASSWORD_MIN_LENGTH = 4;
19777
19800
  var PASSWORD_MAX_LENGTH = 128;
19778
19801
  var TITLE_MAX_LENGTH = 512;
@@ -19803,13 +19826,6 @@ function documentUrl(appHost, handle, slug) {
19803
19826
  }
19804
19827
  var ULID_BODY = ULID_PATTERN.source.slice(1, -1);
19805
19828
  var DOCUMENT_OBJECT_PREFIX = new RegExp(`^documents/${ULID_BODY}/${ULID_BODY}/$`);
19806
- var ApprovalMode = external_exports.enum(["none", "owner"]);
19807
- var EditLease = external_exports.strictObject({
19808
- holderUid: external_exports.string(),
19809
- holderEmail: external_exports.string(),
19810
- acquiredAt: external_exports.string(),
19811
- expiresAt: external_exports.string()
19812
- });
19813
19829
  var DocumentRecord = external_exports.object({
19814
19830
  id: Ulid,
19815
19831
  workspaceId: Ulid,
@@ -19819,8 +19835,6 @@ var DocumentRecord = external_exports.object({
19819
19835
  contentType: ContentType,
19820
19836
  exposure: Exposure,
19821
19837
  allowlist: external_exports.array(external_exports.string()).optional(),
19822
- approvalMode: ApprovalMode.optional(),
19823
- editLease: EditLease.optional(),
19824
19838
  unlisted: external_exports.boolean().optional(),
19825
19839
  publicDirectory: external_exports.boolean().optional(),
19826
19840
  objectKey: external_exports.string(),
@@ -19974,6 +19988,7 @@ var AckRecord = external_exports.object({
19974
19988
  });
19975
19989
  var FollowCadence = external_exports.enum(["immediate", "daily", "weekly"]);
19976
19990
  var Theme = external_exports.enum(["system", "light", "dark"]);
19991
+ var DEFAULT_UNLISTED = true;
19977
19992
  var ONBOARDING_LAST_STEP = 4;
19978
19993
  var PreferencesRecord = external_exports.object({
19979
19994
  uid: external_exports.string(),
@@ -19999,17 +20014,19 @@ var PreferencesRecord = external_exports.object({
19999
20014
  defaultNotifyOnView: external_exports.boolean().optional(),
20000
20015
  defaultRequestAcknowledgment: external_exports.boolean().optional(),
20001
20016
  defaultCommentsEnabled: external_exports.boolean().optional(),
20002
- defaultApprovalMode: ApprovalMode.optional(),
20017
+ defaultFormat: DefaultFormat.optional(),
20003
20018
  onboardedWorkspaceIds: external_exports.array(Ulid).optional(),
20004
20019
  onboardingStep: external_exports.number().int().min(0).max(ONBOARDING_LAST_STEP).optional(),
20005
20020
  cliConnectedAt: external_exports.string().optional(),
20006
20021
  ageConfirmedAt: external_exports.string().optional(),
20007
20022
  plusConfirmationSentFor: external_exports.string().optional(),
20023
+ signupCountedAt: external_exports.string().optional(),
20008
20024
  deletionRequestedAt: external_exports.string().optional(),
20009
20025
  suspendedAt: external_exports.string().nullable().default(null),
20010
20026
  suspendedReason: external_exports.string().nullable().default(null),
20011
20027
  planGrant: external_exports.enum(["friends", "internal"]).optional(),
20012
20028
  planGrantReason: external_exports.string().optional(),
20029
+ planGrantedAt: external_exports.string().optional(),
20013
20030
  billingPlan: external_exports.literal("plus").optional(),
20014
20031
  stripeCustomerId: external_exports.string().optional(),
20015
20032
  stripeSubscriptionId: external_exports.string().optional(),
@@ -20180,6 +20197,12 @@ function limitsFor(plan) {
20180
20197
  var HANDLE_MIN_LENGTH = 3;
20181
20198
  var HANDLE_MAX_LENGTH = 32;
20182
20199
  var HANDLE_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
20200
+ var HANDLE_SHAPE = `[a-z0-9-]{${HANDLE_MIN_LENGTH},${HANDLE_MAX_LENGTH}}`;
20201
+ var PUBLIC_PATH_SHAPES = Object.freeze({
20202
+ collection: `^/${HANDLE_SHAPE}/c/[^/]+$`,
20203
+ document: `^/${HANDLE_SHAPE}/[^/]+$`,
20204
+ workspace: `^/${HANDLE_SHAPE}$`
20205
+ });
20183
20206
  var RESERVED_HANDLES = new Set([
20184
20207
  "app",
20185
20208
  "api",
@@ -20436,7 +20459,11 @@ var PatchWorkspaceRequest = external_exports.object({
20436
20459
  suggestedLabels: SuggestedLabels.optional(),
20437
20460
  expectedUpdatedAt: IsoInstant.optional()
20438
20461
  });
20439
- var LabelUsage = external_exports.object({ label: external_exports.string(), count: external_exports.number().int().nonnegative() });
20462
+ var LabelUsage = external_exports.object({
20463
+ label: external_exports.string(),
20464
+ count: external_exports.number().int().nonnegative(),
20465
+ matchesCollection: external_exports.object({ slug: external_exports.string(), name: external_exports.string() }).optional()
20466
+ });
20440
20467
  var WorkspaceLabelsResponse = external_exports.object({
20441
20468
  suggested: external_exports.array(LabelUsage),
20442
20469
  other: external_exports.array(LabelUsage),
@@ -20530,8 +20557,8 @@ var CreateDocumentRequest = external_exports.object({
20530
20557
  interactiveConnectSrc: ConnectSrc.optional(),
20531
20558
  originalFilename: external_exports.string().max(ORIGINAL_FILENAME_MAX_LENGTH).optional(),
20532
20559
  retainVersions: external_exports.number().int().min(1).optional(),
20533
- commentsEnabled: external_exports.boolean().optional(),
20534
- approvalMode: ApprovalMode.optional()
20560
+ collection: SlugRef.nullable().optional(),
20561
+ commentsEnabled: external_exports.boolean().optional()
20535
20562
  });
20536
20563
  var HtmlLintCode = external_exports.enum([
20537
20564
  "stripped-tag",
@@ -20541,7 +20568,8 @@ var HtmlLintCode = external_exports.enum([
20541
20568
  "fixed-position",
20542
20569
  "data-uri-image",
20543
20570
  "blocked-external-images",
20544
- "interactive-unsanitized"
20571
+ "interactive-unsanitized",
20572
+ "pdf_no_text"
20545
20573
  ]);
20546
20574
  var HtmlLintWarning = external_exports.object({
20547
20575
  code: HtmlLintCode,
@@ -20556,7 +20584,8 @@ var CreateDocumentResponse = external_exports.object({
20556
20584
  version: external_exports.literal(1),
20557
20585
  invitesSent: external_exports.array(external_exports.string()).optional(),
20558
20586
  invitesFailed: external_exports.array(external_exports.string()).optional(),
20559
- warnings: external_exports.array(HtmlLintWarning).optional()
20587
+ warnings: external_exports.array(HtmlLintWarning).optional(),
20588
+ collectionAdded: external_exports.literal(false).optional()
20560
20589
  });
20561
20590
  var DocumentCollectionRef = external_exports.object({ slug: external_exports.string(), name: external_exports.string() });
20562
20591
  var ListDocumentsItem = external_exports.object({
@@ -20627,7 +20656,6 @@ var SharedWithMeResponse = page(SharedDocumentItem);
20627
20656
  var EditAwareness = external_exports.object({
20628
20657
  currentVersion: external_exports.number().int().min(1),
20629
20658
  lastEditorEmail: external_exports.string().optional(),
20630
- lease: EditLease.optional(),
20631
20659
  pendingProposals: external_exports.number().int().nonnegative()
20632
20660
  });
20633
20661
  var OwnerDocumentResponse = DocumentRecord.omit({
@@ -20666,8 +20694,7 @@ var PatchDocumentRequest = external_exports.object({
20666
20694
  interactive: external_exports.boolean().optional(),
20667
20695
  interactiveConnectSrc: ConnectSrc.optional(),
20668
20696
  retainVersions: external_exports.number().int().min(1).nullable().optional(),
20669
- commentsEnabled: external_exports.boolean().optional(),
20670
- approvalMode: ApprovalMode.optional()
20697
+ commentsEnabled: external_exports.boolean().optional()
20671
20698
  });
20672
20699
  var PublishVersionRequest = external_exports.object({
20673
20700
  title: external_exports.string().max(TITLE_MAX_LENGTH).optional(),
@@ -21214,7 +21241,8 @@ var ReaderSearchItem = external_exports.object({
21214
21241
  }).extend(ReaderItemMeta.shape);
21215
21242
  var ReaderSearchResponse = external_exports.object({
21216
21243
  query: external_exports.string(),
21217
- items: external_exports.array(ReaderSearchItem)
21244
+ items: external_exports.array(ReaderSearchItem),
21245
+ nextCursor: external_exports.string().optional()
21218
21246
  });
21219
21247
  var BrowseResponse = external_exports.object({
21220
21248
  documents: external_exports.array(CatalogDocumentItem),
@@ -21288,18 +21316,12 @@ var RejectProposalResponse = external_exports.object({
21288
21316
  proposalId: Ulid,
21289
21317
  status: ProposalStatus
21290
21318
  });
21291
- var EditLeaseResponse = external_exports.object({
21292
- id: Ulid,
21293
- slug: external_exports.string(),
21294
- lease: EditLease.optional()
21295
- });
21296
21319
  var EditContextResponse = external_exports.object({
21297
21320
  id: Ulid,
21298
21321
  slug: external_exports.string(),
21299
21322
  canEdit: external_exports.boolean(),
21300
21323
  isOwner: external_exports.boolean(),
21301
21324
  needsApproval: external_exports.boolean(),
21302
- approvalMode: ApprovalMode,
21303
21325
  awareness: EditAwareness
21304
21326
  });
21305
21327
  var SettingsResponse = external_exports.object({
@@ -21317,11 +21339,26 @@ var SettingsResponse = external_exports.object({
21317
21339
  defaultRequestAcknowledgment: external_exports.boolean().optional(),
21318
21340
  weeklyDigest: external_exports.boolean().optional(),
21319
21341
  defaultCommentsEnabled: external_exports.boolean().optional(),
21320
- defaultApprovalMode: ApprovalMode.optional(),
21342
+ defaultFormat: DefaultFormat.optional(),
21321
21343
  onboardedWorkspaceIds: external_exports.array(Ulid).optional(),
21322
21344
  onboardingStep: external_exports.number().int().min(0).max(ONBOARDING_LAST_STEP).optional(),
21323
21345
  keepReadingHistory: external_exports.boolean().optional()
21324
21346
  });
21347
+ var PUBLISHING_DEFAULT_KEYS = [
21348
+ "defaultWorkspaceId",
21349
+ "defaultFormat",
21350
+ "defaultExposure",
21351
+ "defaultUnlisted",
21352
+ "defaultCollectionSlug",
21353
+ "defaultLabels",
21354
+ "defaultAllowSourceDownload",
21355
+ "defaultNotifyOnView",
21356
+ "defaultRequestAcknowledgment",
21357
+ "defaultCommentsEnabled"
21358
+ ];
21359
+ function hasChosenPublishingDefault(settings) {
21360
+ return PUBLISHING_DEFAULT_KEYS.some((key) => key === "defaultUnlisted" ? settings.defaultUnlisted !== void 0 && settings.defaultUnlisted !== DEFAULT_UNLISTED : settings[key] !== void 0);
21361
+ }
21325
21362
  var MeResponse = external_exports.object({
21326
21363
  uid: external_exports.string(),
21327
21364
  email: external_exports.string().nullable(),
@@ -21360,7 +21397,7 @@ var PatchSettingsRequest = external_exports.object({
21360
21397
  defaultRequestAcknowledgment: external_exports.boolean().nullable().optional(),
21361
21398
  weeklyDigest: external_exports.boolean().optional(),
21362
21399
  defaultCommentsEnabled: external_exports.boolean().nullable().optional(),
21363
- defaultApprovalMode: ApprovalMode.nullable().optional(),
21400
+ defaultFormat: DefaultFormat.nullable().optional(),
21364
21401
  onboardedWorkspaceId: Ulid.optional(),
21365
21402
  onboardingStep: external_exports.number().int().min(0).max(ONBOARDING_LAST_STEP).nullable().optional(),
21366
21403
  keepReadingHistory: external_exports.boolean().optional()
@@ -21717,9 +21754,6 @@ function describeAwareness(awareness) {
21717
21754
  const parts = [`v${awareness.currentVersion}`];
21718
21755
  if (awareness.lastEditorEmail !== void 0)
21719
21756
  parts.push(`last edited by ${awareness.lastEditorEmail}`);
21720
- if (awareness.lease !== void 0) {
21721
- parts.push(`lease held by ${awareness.lease.holderEmail} until ${awareness.lease.expiresAt}`);
21722
- }
21723
21757
  if (awareness.pendingProposals > 0) {
21724
21758
  parts.push(plural2(awareness.pendingProposals, "pending proposal"));
21725
21759
  }
@@ -22054,8 +22088,8 @@ var cachedVersion;
22054
22088
  function bundledVersion() {
22055
22089
  if (cachedVersion !== void 0)
22056
22090
  return cachedVersion;
22057
- if ("1.4.0".length > 0) {
22058
- cachedVersion = "1.4.0";
22091
+ if ("1.6.0".length > 0) {
22092
+ cachedVersion = "1.6.0";
22059
22093
  return cachedVersion;
22060
22094
  }
22061
22095
  try {
@@ -22220,18 +22254,17 @@ async function readLocalConfig(env = process.env) {
22220
22254
  const config2 = {};
22221
22255
  if (typeof record2["host"] === "string" && record2["host"].trim() !== "")
22222
22256
  config2.host = record2["host"];
22223
- if (typeof record2["defaultWorkspace"] === "string" && record2["defaultWorkspace"] !== "") {
22224
- config2.defaultWorkspace = record2["defaultWorkspace"];
22225
- }
22226
- if (record2["credentials"] === "file" || record2["credentials"] === "keychain") {
22227
- config2.credentials = record2["credentials"];
22228
- }
22257
+ if (record2["noKeychain"] === true)
22258
+ config2.noKeychain = true;
22259
+ if (record2["setupTipShown"] === true)
22260
+ config2.setupTipShown = true;
22229
22261
  return config2;
22230
22262
  }
22263
+ var LOCAL_CONFIG_KEYS = ["host", "noKeychain", "setupTipShown"];
22231
22264
  async function writeLocalConfig(patch, env = process.env) {
22232
22265
  const current = await readLocalConfig(env);
22233
22266
  const merged = { ...current };
22234
- for (const key of ["host", "defaultWorkspace", "credentials"]) {
22267
+ for (const key of LOCAL_CONFIG_KEYS) {
22235
22268
  if (!(key in patch))
22236
22269
  continue;
22237
22270
  const value = patch[key];
@@ -22252,6 +22285,21 @@ async function writeLocalConfig(patch, env = process.env) {
22252
22285
  }
22253
22286
  return out;
22254
22287
  }
22288
+ async function pruneLocalConfig(env = process.env) {
22289
+ let parsed;
22290
+ try {
22291
+ parsed = JSON.parse(await readFile2(localConfigPath(env), "utf8"));
22292
+ }
22293
+ catch {
22294
+ return;
22295
+ }
22296
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
22297
+ return;
22298
+ const known = ["v", ...LOCAL_CONFIG_KEYS];
22299
+ if (Object.keys(parsed).every((key) => known.includes(key)))
22300
+ return;
22301
+ await writeLocalConfig({}, env);
22302
+ }
22255
22303
  function isErrno(err, code) {
22256
22304
  return typeof err === "object" && err !== null && "code" in err && err.code === code;
22257
22305
  }
@@ -22306,7 +22354,7 @@ var FLAG_HOME = {
22306
22354
  "--since": "handout library --recent",
22307
22355
  "--cadence": "handout follow",
22308
22356
  "--keep": "handout versions prune",
22309
- "--out": "handout source, versions source, proposals source or read",
22357
+ "--out": "handout source, versions source or read",
22310
22358
  "--browser": "handout open",
22311
22359
  "--name": "handout collections create/update or workspaces create/update (a document's own name is --title)",
22312
22360
  "--description": "handout collections create or update",
@@ -22350,7 +22398,6 @@ var VALUE_FLAGS = new Set([
22350
22398
  "--retain-versions",
22351
22399
  "--expected-version",
22352
22400
  "--diff-summary",
22353
- "--approval-mode",
22354
22401
  "--connect-src",
22355
22402
  "--idempotency-key",
22356
22403
  "--message",
@@ -22520,8 +22567,6 @@ async function resolveWorkspaceHandle(input2) {
22520
22567
  const fromEnv = input2.env["HANDOUT_WORKSPACE"]?.trim();
22521
22568
  if (fromEnv !== void 0 && fromEnv !== "")
22522
22569
  return parseWorkspaceHandle(fromEnv);
22523
- if (input2.localDefault !== void 0 && input2.localDefault !== "")
22524
- return input2.localDefault;
22525
22570
  const me = await input2.getMe();
22526
22571
  const defaultId = me.settings.defaultWorkspaceId;
22527
22572
  if (defaultId !== void 0) {
@@ -23248,6 +23293,65 @@ __export(collections_exports, {
23248
23293
  });
23249
23294
  import { readFile as readFile3, rm as rm2, stat as stat2 } from "node:fs/promises";
23250
23295
  import { basename as basename2, join as join3 } from "node:path";
23296
+ import { isDeepStrictEqual } from "node:util";
23297
+ import { connect } from "node:net";
23298
+ var BUS_TIMEOUT_MS = 500;
23299
+ function busSocketPath(address) {
23300
+ if (address === void 0 || address === "")
23301
+ return void 0;
23302
+ for (const entry of address.split(";")) {
23303
+ if (!entry.startsWith("unix:"))
23304
+ continue;
23305
+ const params = new Map();
23306
+ for (const pair2 of entry.slice("unix:".length).split(",")) {
23307
+ const eq = pair2.indexOf("=");
23308
+ if (eq > 0)
23309
+ params.set(pair2.slice(0, eq), unescapeValue(pair2.slice(eq + 1)));
23310
+ }
23311
+ const path = params.get("path");
23312
+ if (path !== void 0 && path !== "")
23313
+ return path;
23314
+ const abstract = params.get("abstract");
23315
+ if (abstract !== void 0 && abstract !== "")
23316
+ return `\0${abstract}`;
23317
+ }
23318
+ return void 0;
23319
+ }
23320
+ function unescapeValue(value) {
23321
+ return value.replace(/%([0-9a-fA-F]{2})/g, (_, hex3) => String.fromCharCode(parseInt(hex3, 16)));
23322
+ }
23323
+ async function sessionBusResponds(env, timeoutMs = BUS_TIMEOUT_MS) {
23324
+ const path = busSocketPath(env["DBUS_SESSION_BUS_ADDRESS"]);
23325
+ if (path === void 0)
23326
+ return false;
23327
+ const uid = String(process.getuid?.() ?? 0);
23328
+ const hexUid = Buffer.from(uid, "ascii").toString("hex");
23329
+ return new Promise((resolve3) => {
23330
+ let settled = false;
23331
+ const socket = connect({ path });
23332
+ const finish = (answer) => {
23333
+ if (settled)
23334
+ return;
23335
+ settled = true;
23336
+ clearTimeout(timer);
23337
+ socket.destroy();
23338
+ resolve3(answer);
23339
+ };
23340
+ const timer = setTimeout(() => finish(false), timeoutMs);
23341
+ socket.on("connect", () => {
23342
+ socket.write(`\0AUTH EXTERNAL ${hexUid}\r
23343
+ `);
23344
+ });
23345
+ let reply = "";
23346
+ socket.on("data", (chunk) => {
23347
+ reply += chunk.toString("ascii");
23348
+ if (reply.includes("\n"))
23349
+ finish(/^(OK|REJECTED)\b/.test(reply));
23350
+ });
23351
+ socket.on("error", () => finish(false));
23352
+ socket.on("close", () => finish(false));
23353
+ });
23354
+ }
23251
23355
  function parseCredential(text) {
23252
23356
  let value;
23253
23357
  try {
@@ -23283,20 +23387,28 @@ var loadKeyring = async () => {
23283
23387
  }
23284
23388
  };
23285
23389
  var KEYCHAIN_SERVICE = "handout";
23390
+ var WINDOWS_SECRET_LIMIT = 2560;
23391
+ var ENTRY_OPTIONS = { linux: { store: "secret-service" } };
23286
23392
  var KeychainStore = class {
23287
- constructor(host, keyring) {
23393
+ constructor(host, keyring, platform = process.platform, service = KEYCHAIN_SERVICE) {
23288
23394
  this.host = host;
23289
23395
  this.keyring = keyring;
23396
+ this.platform = platform;
23397
+ this.service = service;
23290
23398
  }
23291
23399
  host;
23292
23400
  keyring;
23401
+ platform;
23402
+ service;
23293
23403
  kind = "keychain";
23404
+ cachedEntry;
23294
23405
  entry() {
23295
- return new this.keyring.Entry(KEYCHAIN_SERVICE, this.host);
23406
+ this.cachedEntry ??= new this.keyring.Entry(this.service, this.host, ENTRY_OPTIONS);
23407
+ return this.cachedEntry;
23296
23408
  }
23297
23409
  probe() {
23298
23410
  try {
23299
- this.entry().getPassword();
23411
+ this.entry().getSecret();
23300
23412
  return true;
23301
23413
  }
23302
23414
  catch {
@@ -23305,25 +23417,55 @@ var KeychainStore = class {
23305
23417
  }
23306
23418
  async read() {
23307
23419
  try {
23308
- const secret = this.entry().getPassword();
23309
- return secret === null ? void 0 : parseCredential(secret);
23420
+ const secret = this.entry().getSecret();
23421
+ return secret === null ? void 0 : parseCredential(Buffer.from(secret).toString("utf8"));
23310
23422
  }
23311
23423
  catch {
23312
23424
  return void 0;
23313
23425
  }
23314
23426
  }
23427
+ stored(credential) {
23428
+ if (this.platform === "win32" && Buffer.byteLength(JSON.stringify(credential), "utf8") > WINDOWS_SECRET_LIMIT) {
23429
+ return { ...credential, idToken: "", idTokenExpiresAt: 0 };
23430
+ }
23431
+ return credential;
23432
+ }
23315
23433
  async write(credential) {
23316
- this.entry().setPassword(JSON.stringify(credential));
23434
+ this.entry().setSecret(Buffer.from(JSON.stringify(this.stored(credential)), "utf8"));
23317
23435
  }
23318
- async delete() {
23436
+ async writeVerified(credential) {
23319
23437
  try {
23320
- return this.entry().deleteCredential();
23438
+ await this.write(credential);
23321
23439
  }
23322
23440
  catch {
23323
23441
  return false;
23324
23442
  }
23443
+ return isDeepStrictEqual(await this.read(), this.stored(credential));
23444
+ }
23445
+ async delete() {
23446
+ let deleted;
23447
+ try {
23448
+ deleted = this.entry().deleteCredential();
23449
+ }
23450
+ catch (err) {
23451
+ throw keychainDeleteError(err);
23452
+ }
23453
+ let remaining;
23454
+ try {
23455
+ remaining = this.entry().getSecret();
23456
+ }
23457
+ catch (err) {
23458
+ throw keychainDeleteError(err);
23459
+ }
23460
+ if (remaining !== null)
23461
+ throw keychainDeleteError(void 0);
23462
+ return deleted;
23325
23463
  }
23326
23464
  };
23465
+ function keychainDeleteError(cause) {
23466
+ const reason = cause === void 0 ? "it is still there" : errorMessage(cause);
23467
+ return new CliError(`Could not remove your Handout login from the system keychain (${reason}). Remove the "${KEYCHAIN_SERVICE}" entry in your keychain app.`, { exitCode: 1, code: "file", cause });
23468
+ }
23327
23469
  var FileStore = class {
23328
23470
  constructor(host, env, platform = process.platform) {
23329
23471
  this.platform = platform;
@@ -23415,11 +23557,13 @@ var EnvStore = class {
23415
23557
  });
23416
23558
  }
23417
23559
  };
23560
+ var MIGRATION_NOTICE = "Your Handout login moved to the system keychain. To keep it in a file instead, run handout login --no-keychain.";
23418
23561
  var HostCredentials = class {
23419
23562
  constructor(host, options) {
23420
23563
  this.host = host;
23421
23564
  this.options = options;
23422
- this.fileStore = new FileStore(host, options.env, options.platform);
23565
+ this.platform = options.platform ?? process.platform;
23566
+ this.fileStore = new FileStore(host, options.env, this.platform);
23423
23567
  this.envStore = EnvStore.isActive(options.env) ? new EnvStore(host, options.env, options.fallbackApiKey) : void 0;
23424
23568
  }
23425
23569
  host;
@@ -23427,46 +23571,78 @@ var HostCredentials = class {
23427
23571
  keychainPromise;
23428
23572
  fileStore;
23429
23573
  envStore;
23574
+ platform;
23575
+ source;
23430
23576
  writtenTo;
23431
23577
  get kind() {
23432
23578
  if (this.envStore !== void 0)
23433
23579
  return "env";
23434
- return this.writtenTo ?? "file";
23580
+ return this.writtenTo ?? this.source ?? "file";
23435
23581
  }
23436
- keychainDisabled() {
23437
- return this.options.noKeychain === true || this.options.env["HANDOUT_NO_KEYCHAIN"] === "1";
23582
+ get filePath() {
23583
+ return this.fileStore.path;
23438
23584
  }
23439
- keychain() {
23440
- if (this.keychainDisabled())
23585
+ get keychainDisabled() {
23586
+ return this.options.noKeychain === true || this.options.env["HANDOUT_NO_KEYCHAIN"] === "1" || this.options.localConfig?.noKeychain === true;
23587
+ }
23588
+ reachableKeychain() {
23589
+ if (this.options.env["HANDOUT_NO_KEYCHAIN"] === "1")
23441
23590
  return Promise.resolve(void 0);
23442
23591
  this.keychainPromise ??= (async () => {
23592
+ if (this.platform !== "win32" && this.platform !== "darwin") {
23593
+ const busCheck = this.options.busCheck ?? sessionBusResponds;
23594
+ if (!await busCheck(this.options.env))
23595
+ return void 0;
23596
+ }
23443
23597
  const keyring = await (this.options.loadKeyring ?? loadKeyring)();
23444
23598
  if (keyring === void 0)
23445
23599
  return void 0;
23446
- const store = new KeychainStore(this.host, keyring);
23600
+ const store = new KeychainStore(this.host, keyring, this.platform, this.options.keychainService);
23447
23601
  return store.probe() ? store : void 0;
23448
23602
  })();
23449
23603
  return this.keychainPromise;
23450
23604
  }
23605
+ keychain() {
23606
+ return this.keychainDisabled ? Promise.resolve(void 0) : this.reachableKeychain();
23607
+ }
23451
23608
  async read() {
23452
23609
  if (this.envStore !== void 0)
23453
23610
  return this.envStore.read();
23454
- const configured = this.options.localConfig?.credentials;
23455
- const order = configured === "file" ? ["file", "keychain"] : ["keychain", "file"];
23456
- for (const kind of order) {
23457
- if (kind === "keychain") {
23458
- const keychain = await this.keychain();
23459
- const found = await keychain?.read();
23460
- if (found !== void 0)
23461
- return found;
23462
- }
23463
- else {
23464
- const found = await this.fileStore.read();
23465
- if (found !== void 0)
23466
- return found;
23611
+ const keychain = await this.keychain();
23612
+ const fromFile = await this.fileStore.read();
23613
+ if (fromFile !== void 0) {
23614
+ this.source = "file";
23615
+ if (keychain !== void 0 && await this.migrate(keychain, fromFile)) {
23616
+ this.source = "keychain";
23467
23617
  }
23618
+ return fromFile;
23468
23619
  }
23469
- return void 0;
23620
+ const fromKeychain = await keychain?.read();
23621
+ if (fromKeychain === void 0)
23622
+ return void 0;
23623
+ this.source = "keychain";
23624
+ return fromKeychain;
23625
+ }
23626
+ async migrate(keychain, credential) {
23627
+ const firstMove = await keychain.read() === void 0;
23628
+ if (!await keychain.writeVerified(credential))
23629
+ return false;
23630
+ let removed;
23631
+ try {
23632
+ removed = await this.fileStore.delete();
23633
+ }
23634
+ catch {
23635
+ if (!firstMove)
23636
+ return true;
23637
+ if (await this.fileStore.read().catch(() => credential) === void 0)
23638
+ return true;
23639
+ await keychain.delete().catch(() => false);
23640
+ return false;
23641
+ }
23642
+ if (removed && firstMove)
23643
+ this.options.onNotice?.(MIGRATION_NOTICE);
23644
+ await pruneLocalConfig(this.options.env).catch(() => void 0);
23645
+ return true;
23470
23646
  }
23471
23647
  async write(credential) {
23472
23648
  if (this.envStore !== void 0) {
@@ -23474,28 +23650,42 @@ var HostCredentials = class {
23474
23650
  this.writtenTo = "env";
23475
23651
  return;
23476
23652
  }
23477
- const keychain = this.options.localConfig?.credentials === "file" && this.options.noKeychain !== true ? void 0 : await this.keychain();
23478
- if (keychain !== void 0) {
23479
- try {
23480
- await keychain.write(credential);
23653
+ if (this.source === void 0)
23654
+ return this.replace(credential);
23655
+ if (this.source === "keychain") {
23656
+ const keychain = await this.keychain();
23657
+ if (keychain !== void 0 && await keychain.writeVerified(credential)) {
23481
23658
  this.writtenTo = "keychain";
23482
23659
  return;
23483
23660
  }
23484
- catch {
23485
- }
23486
23661
  }
23487
23662
  await this.fileStore.write(credential);
23488
23663
  this.writtenTo = "file";
23489
23664
  }
23665
+ async replace(credential) {
23666
+ if (this.envStore !== void 0) {
23667
+ await this.envStore.write(credential);
23668
+ this.writtenTo = "env";
23669
+ return;
23670
+ }
23671
+ const keychain = await this.keychain();
23672
+ if (keychain !== void 0 && await keychain.writeVerified(credential)) {
23673
+ this.writtenTo = "keychain";
23674
+ await this.fileStore.delete().catch(() => false);
23675
+ return;
23676
+ }
23677
+ await this.fileStore.write(credential);
23678
+ this.writtenTo = "file";
23679
+ const stale = await this.reachableKeychain();
23680
+ await stale?.delete().catch(() => false);
23681
+ }
23490
23682
  async delete() {
23491
23683
  if (this.envStore !== void 0)
23492
23684
  return this.envStore.delete();
23493
- let deleted = false;
23494
- const keychain = await this.keychain();
23685
+ let deleted = await this.fileStore.delete();
23686
+ const keychain = await this.reachableKeychain();
23495
23687
  if (keychain !== void 0 && await keychain.delete())
23496
23688
  deleted = true;
23497
- if (await this.fileStore.delete())
23498
- deleted = true;
23499
23689
  return deleted;
23500
23690
  }
23501
23691
  };
@@ -23591,7 +23781,8 @@ function createTokenSource(options) {
23591
23781
  fallbackApiKey: options.config.firebase.apiKey,
23592
23782
  ...options.noKeychain === void 0 ? {} : { noKeychain: options.noKeychain },
23593
23783
  ...options.loadKeyring === void 0 ? {} : { loadKeyring: options.loadKeyring },
23594
- ...options.platform === void 0 ? {} : { platform: options.platform }
23784
+ ...options.platform === void 0 ? {} : { platform: options.platform },
23785
+ ...options.onNotice === void 0 ? {} : { onNotice: options.onNotice }
23595
23786
  });
23596
23787
  store = opened;
23597
23788
  return opened;
@@ -23826,7 +24017,7 @@ function isTimeout(err) {
23826
24017
  }
23827
24018
  function createClient(options) {
23828
24019
  const fetchImpl = options.fetchImpl ?? fetch;
23829
- const sleep = options.sleep ?? ((ms) => new Promise((resolve2) => setTimeout(resolve2, ms)));
24020
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms)));
23830
24021
  const ua = options.userAgent ?? userAgent();
23831
24022
  const apiBase = options.apiBase.replace(/\/+$/, "");
23832
24023
  async function perform(spec, token, requestId) {
@@ -24301,18 +24492,6 @@ function createClient(options) {
24301
24492
  schema: RejectProposalResponse,
24302
24493
  context: ws(handle, slug, "proposal")
24303
24494
  }),
24304
- claimLease: (handle, slug) => call({
24305
- method: "PUT",
24306
- path: doc(handle, slug, "/lease"),
24307
- schema: EditLeaseResponse,
24308
- context: ws(handle, slug)
24309
- }),
24310
- releaseLease: (handle, slug) => call({
24311
- method: "DELETE",
24312
- path: doc(handle, slug, "/lease"),
24313
- schema: EditLeaseResponse,
24314
- context: ws(handle, slug)
24315
- }),
24316
24495
  listComments: (handle, slug, extras) => call({
24317
24496
  method: "GET",
24318
24497
  path: pub(handle, slug, "/comments"),
@@ -24385,7 +24564,8 @@ async function resolveContext(options) {
24385
24564
  env: options.env,
24386
24565
  fetchImpl,
24387
24566
  ...options.now === void 0 ? {} : { now: options.now },
24388
- ...options.noKeychain === void 0 ? {} : { noKeychain: options.noKeychain }
24567
+ ...options.noKeychain === void 0 ? {} : { noKeychain: options.noKeychain },
24568
+ ...options.onNotice === void 0 ? {} : { onNotice: options.onNotice }
24389
24569
  });
24390
24570
  }
24391
24571
  const client = createClient({
@@ -24397,6 +24577,24 @@ async function resolveContext(options) {
24397
24577
  });
24398
24578
  return { host: options.host, apiBase, config: config2, getToken, fetchImpl, client };
24399
24579
  }
24580
+ function reorderExactly(current, requested, spec) {
24581
+ const fold = spec.fold ?? ((name) => name);
24582
+ const byKey = new Map(current.map((item) => [fold(spec.nameOf(item)), item]));
24583
+ const seen = new Set();
24584
+ const repeated = [];
24585
+ for (const name of requested) {
24586
+ if (seen.has(fold(name)))
24587
+ repeated.push(name);
24588
+ seen.add(fold(name));
24589
+ }
24590
+ const missing = current.filter((item) => !seen.has(fold(spec.nameOf(item)))).map(spec.nameOf);
24591
+ const unknown2 = [...new Set(requested.filter((name) => !byKey.has(fold(name))))];
24592
+ if (missing.length > 0 || unknown2.length > 0 || repeated.length > 0) {
24593
+ const more = repeated.length > 0 ? `; listed more than once: ${[...new Set(repeated)].join(", ")}` : "";
24594
+ throw usageError(`reorder must list every ${spec.noun} exactly once; missing: ${missing.join(", ")}; unknown: ${unknown2.join(", ")}${more}.`);
24595
+ }
24596
+ return requested.map((name) => byKey.get(fold(name)));
24597
+ }
24400
24598
  function scanArgs(argv, spec) {
24401
24599
  const valueFlags = new Set(spec.values ?? []);
24402
24600
  const booleanFlags = new Set(spec.booleans ?? []);
@@ -24872,21 +25070,8 @@ function applyRemove(current, slugs) {
24872
25070
  };
24873
25071
  }
24874
25072
  function applyReorder(current, slugs) {
24875
- const bySlug = new Map(current.map((item) => [item.slug, item]));
24876
- const seen = new Set();
24877
- const duplicated = [];
24878
- for (const slug of slugs) {
24879
- if (seen.has(slug))
24880
- duplicated.push(slug);
24881
- seen.add(slug);
24882
- }
24883
- const missing = current.filter((item) => !seen.has(item.slug)).map((item) => item.slug);
24884
- const unknown2 = [...seen].filter((slug) => !bySlug.has(slug));
24885
- if (missing.length > 0 || unknown2.length > 0 || duplicated.length > 0) {
24886
- throw usageError(`reorder must list every item exactly once; missing: ${missing.join(", ")}; unknown: ${unknown2.join(", ")}${duplicated.length > 0 ? `; listed more than once: ${[...new Set(duplicated)].join(", ")}` : ""}.`);
24887
- }
24888
25073
  return {
24889
- items: slugs.map((slug) => bySlug.get(slug)),
25074
+ items: reorderExactly(current, slugs, { noun: "item", nameOf: (item) => item.slug }),
24890
25075
  added: [],
24891
25076
  removed: [],
24892
25077
  alreadyPresent: [],
@@ -25226,6 +25411,7 @@ function buildCreateRequest(options, target, title) {
25226
25411
  set2("interactiveConnectSrc", options.connectSrc === void 0 ? void 0 : [...options.connectSrc]);
25227
25412
  set2("branding", options.branding);
25228
25413
  set2("retainVersions", options.retainVersions);
25414
+ set2("collection", options.collection);
25229
25415
  const parsed = CreateDocumentRequest.safeParse(body);
25230
25416
  if (!parsed.success)
25231
25417
  throw rejected(parsed.error.issues);
@@ -25264,6 +25450,9 @@ async function readTargets(options, fs = nodePublishFs) {
25264
25450
  return targets;
25265
25451
  }
25266
25452
  function lintHeader(warnings) {
25453
+ if (warnings.length > 0 && warnings.every((w) => w.code === "pdf_no_text")) {
25454
+ return "Published, with a note on search:";
25455
+ }
25267
25456
  return warnings.length === 1 && warnings[0]?.code === "interactive-unsanitized" ? "Published (interactive):" : "Published, but this HTML may render degraded in the reader:";
25268
25457
  }
25269
25458
  function printLintWarnings(ctx, warnings, prefix) {
@@ -25329,6 +25518,8 @@ async function publishOne(input2) {
25329
25518
  ...data.invitesFailed === void 0 ? {} : { invitesFailed: data.invitesFailed },
25330
25519
  ...data.warnings === void 0 ? {} : { warnings: data.warnings }
25331
25520
  };
25521
+ if (data.collectionAdded === false)
25522
+ outcome.collectionAdded = false;
25332
25523
  return { outcome, kind: "published" };
25333
25524
  };
25334
25525
  if (options.command === "update") {
@@ -25500,6 +25691,7 @@ async function publishMany(ctx, command, deps = {}) {
25500
25691
  const handle = updateRef?.handle ?? await ctx.workspace();
25501
25692
  const client = await ctx.client();
25502
25693
  const items = [];
25694
+ const updatedSlugs = [];
25503
25695
  for (const [index, target] of targets.entries()) {
25504
25696
  let done;
25505
25697
  try {
@@ -25521,12 +25713,17 @@ async function publishMany(ctx, command, deps = {}) {
25521
25713
  }
25522
25714
  const { outcome, kind } = done;
25523
25715
  items.push(outcome);
25716
+ if (kind === "updated")
25717
+ updatedSlugs.push(outcome.slug);
25524
25718
  reportOutcome(ctx, outcome, kind, targets.length > 1);
25719
+ if (options.collection !== void 0 && outcome.collectionAdded === false) {
25720
+ ctx.warn(`Warning: published, but could not add ${outcome.slug} to collection "${options.collection}".`);
25721
+ }
25525
25722
  }
25526
- if (options.collection !== void 0) {
25723
+ if (options.collection !== void 0 && updatedSlugs.length > 0) {
25527
25724
  const add = deps.addToCollection ?? defaultAddToCollection;
25528
25725
  try {
25529
- await add(client, handle, options.collection, items.map((item) => item.slug));
25726
+ await add(client, handle, options.collection, updatedSlugs);
25530
25727
  }
25531
25728
  catch (err) {
25532
25729
  const message = err instanceof Error ? err.message : String(err);
@@ -25863,17 +26060,17 @@ function openerCommand(url2, platform = process.platform) {
25863
26060
  }
25864
26061
  function launchBrowser(url2, platform = process.platform, spawnImpl = spawn) {
25865
26062
  const { command, args } = openerCommand(url2, platform);
25866
- return new Promise((resolve2) => {
26063
+ return new Promise((resolve3) => {
25867
26064
  try {
25868
26065
  const child = spawnImpl(command, args, { detached: true, stdio: "ignore" });
25869
- child.once("error", () => resolve2(false));
26066
+ child.once("error", () => resolve3(false));
25870
26067
  child.once("spawn", () => {
25871
26068
  child.unref();
25872
- resolve2(true);
26069
+ resolve3(true);
25873
26070
  });
25874
26071
  }
25875
26072
  catch {
25876
- resolve2(false);
26073
+ resolve3(false);
25877
26074
  }
25878
26075
  });
25879
26076
  }
@@ -26180,10 +26377,10 @@ function formatOwnerDocument(doc) {
26180
26377
  if (doc.unlisted === true)
26181
26378
  rows2.push(["unlisted", "yes"]);
26182
26379
  if (doc.interactive === true) {
26183
- const connect = doc.interactiveConnectSrc ?? [];
26380
+ const connect2 = doc.interactiveConnectSrc ?? [];
26184
26381
  rows2.push([
26185
26382
  "interactive",
26186
- connect.length === 0 ? "yes" : `yes (connect-src: ${connect.join(" ")})`
26383
+ connect2.length === 0 ? "yes" : `yes (connect-src: ${connect2.join(" ")})`
26187
26384
  ]);
26188
26385
  }
26189
26386
  if (doc.allowSourceDownload !== void 0) {
@@ -26667,14 +26864,17 @@ function editScript(a, b) {
26667
26864
  return ops;
26668
26865
  }
26669
26866
  function buildUnifiedDiff(a, va, b, vb) {
26670
- const ops = editScript(decode3(a.bytes), decode3(b.bytes));
26867
+ return unifiedDiff(a.bytes, b.bytes, `v${va}/${a.filename}`, `v${vb}/${b.filename}`) ?? `(no differences between v${va} and v${vb})`;
26868
+ }
26869
+ function unifiedDiff(a, b, fromLabel, toLabel) {
26870
+ const ops = editScript(decode3(a), decode3(b));
26671
26871
  const changes = [];
26672
26872
  ops.forEach((op, index) => {
26673
26873
  if (op.kind !== " ")
26674
26874
  changes.push(index);
26675
26875
  });
26676
26876
  if (changes.length === 0)
26677
- return `(no differences between v${va} and v${vb})`;
26877
+ return null;
26678
26878
  const groups = [];
26679
26879
  for (const index of changes) {
26680
26880
  const current = groups[groups.length - 1];
@@ -26709,8 +26909,8 @@ function buildUnifiedDiff(a, va, b, vb) {
26709
26909
  return `@@ -${aBefore + 1},${aCount} +${bBefore + 1},${bCount} @@
26710
26910
  ${lines.join("\n")}`;
26711
26911
  });
26712
- return `--- v${va}/${a.filename}
26713
- +++ v${vb}/${b.filename}
26912
+ return `--- ${fromLabel}
26913
+ +++ ${toLabel}
26714
26914
  ${hunks.join("\n")}`;
26715
26915
  }
26716
26916
  var VERSIONS_USAGE = {
@@ -26947,34 +27147,13 @@ function requireAnswerable(ctx) {
26947
27147
  throw usageError(`${ctx.command} needs --yes when stdin is not a terminal.`);
26948
27148
  }
26949
27149
  }
26950
- async function resolveDefaultHandle(ctx, response) {
26951
- const forced = ctx.global.workspace ?? ctx.env["HANDOUT_WORKSPACE"];
26952
- if (forced !== void 0 && forced !== "") {
26953
- try {
26954
- return parseWorkspaceHandle(forced);
26955
- }
26956
- catch {
26957
- return void 0;
26958
- }
26959
- }
26960
- const local = (await ctx.localConfig()).defaultWorkspace;
26961
- if (local !== void 0)
26962
- return local;
26963
- if (response.items.length === 0)
26964
- return void 0;
26965
- const me = await (await ctx.client()).getMe();
26966
- const byId = response.items.find((item) => item.id === me.settings.defaultWorkspaceId);
26967
- if (byId !== void 0)
26968
- return byId.handle;
26969
- return response.items.length === 1 ? response.items[0]?.handle : void 0;
26970
- }
26971
27150
  async function runList2(ctx) {
26972
27151
  const context = CONTEXT5("list");
26973
27152
  const scanned = scanArgs(ctx.args, { context, usage: LIST_USAGE2 });
26974
27153
  expectPositionals(scanned, context, 0);
26975
27154
  const client = await ctx.client();
26976
27155
  const response = await client.listWorkspaces();
26977
- const defaultHandle = ctx.json ? void 0 : await resolveDefaultHandle(ctx, response);
27156
+ const defaultHandle = ctx.json ? void 0 : await ctx.workspace().catch(() => void 0);
26978
27157
  return result("workspaces-list", { response, defaultHandle });
26979
27158
  }
26980
27159
  function formatWorkspaceList(data) {
@@ -27008,15 +27187,6 @@ async function runCreate2(ctx) {
27008
27187
  }
27009
27188
  const client = await ctx.client();
27010
27189
  const workspace = await client.createWorkspace(body, key === void 0 ? void 0 : { idempotencyKey: key });
27011
- try {
27012
- const mine = await client.listWorkspaces();
27013
- if (mine.items.filter((item) => item.deletedAt === void 0).length <= 1) {
27014
- await ctx.updateLocalConfig({ defaultWorkspace: workspace.handle });
27015
- ctx.info(`Set as your default workspace (handout use ${workspace.handle} to change).`);
27016
- }
27017
- }
27018
- catch {
27019
- }
27020
27190
  return result("workspaces-create", workspace);
27021
27191
  }
27022
27192
  async function runGet2(ctx) {
@@ -27136,18 +27306,17 @@ var commands6 = {
27136
27306
  };
27137
27307
  var account_exports = {};
27138
27308
  __export(account_exports, {
27309
+ SETTING_KEYS: () => SETTING_KEYS,
27310
+ SETUP_TIP: () => SETUP_TIP,
27139
27311
  buildSettingsPatch: () => buildSettingsPatch,
27140
27312
  commands: () => commands7,
27141
27313
  formatSettings: () => formatSettings
27142
27314
  });
27143
27315
  var USE_USAGE = buildUsage({
27144
- synopsis: ["handout use <handle> [--account]", "handout use --clear [--account]"],
27145
- description: "Stores the default workspace in the local config. --account also saves it on your account so the web app follows.",
27146
- flags: [
27147
- ["--account", "Also save the default on your account"],
27148
- ["--clear", "Remove the default"]
27149
- ],
27150
- examples: ["handout use acme", "handout use acme --account"]
27316
+ synopsis: ["handout use <handle>", "handout use --clear"],
27317
+ description: "Saves the default workspace on your account, so the web app follows too.",
27318
+ flags: [["--clear", "Remove the default"]],
27319
+ examples: ["handout use acme", "handout use --clear"]
27151
27320
  });
27152
27321
  var SETTING_KEYS = [
27153
27322
  ["email-notifications", "on|off"],
@@ -27155,6 +27324,7 @@ var SETTING_KEYS = [
27155
27324
  ["theme", "system|light|dark"],
27156
27325
  ["keep-versions", "<n>|clear"],
27157
27326
  ["default-workspace", "<handle>|clear"],
27327
+ ["default-format", "html|markdown|pdf|clear"],
27158
27328
  ["default-exposure", "private|people|password|open|clear"],
27159
27329
  ["default-unlisted", "on|off|clear"],
27160
27330
  ["default-allow-source-download", "on|off|clear"],
@@ -27163,8 +27333,7 @@ var SETTING_KEYS = [
27163
27333
  ["default-collection", "<collection-slug>|clear"],
27164
27334
  ["default-labels", "<a,b,c>|clear"],
27165
27335
  ["weekly-digest", "on|off"],
27166
- ["default-comments", "on|off|clear"],
27167
- ["default-approval-mode", "none|owner|clear"]
27336
+ ["default-comments", "on|off|clear"]
27168
27337
  ];
27169
27338
  var SETTINGS_GET_USAGE = buildUsage({
27170
27339
  synopsis: ["handout settings [get]"],
@@ -27195,11 +27364,10 @@ async function runUse(ctx) {
27195
27364
  const scanned = scanArgs(ctx.args, {
27196
27365
  context,
27197
27366
  usage: USE_USAGE,
27198
- booleans: ["--account", "--clear"]
27367
+ booleans: ["--clear"]
27199
27368
  });
27200
27369
  expectPositionals(scanned, context, 1);
27201
27370
  const clear = scanned.seen.has("--clear");
27202
- const account = scanned.seen.has("--account");
27203
27371
  const rawHandle = scanned.positionals[0];
27204
27372
  if (clear && rawHandle !== void 0) {
27205
27373
  throw usageError("use --clear takes no workspace handle (handout use --clear).");
@@ -27208,17 +27376,13 @@ async function runUse(ctx) {
27208
27376
  throw usageError("use requires a workspace handle (handout use <handle>).");
27209
27377
  }
27210
27378
  if (clear) {
27211
- await ctx.updateLocalConfig({ defaultWorkspace: void 0 });
27212
- if (account)
27213
- await (await ctx.client()).patchMe({ defaultWorkspaceId: null });
27379
+ await (await ctx.client()).patchMe({ defaultWorkspaceId: null });
27214
27380
  return result("use", { defaultWorkspace: null });
27215
27381
  }
27216
27382
  const handle = parseHandle(rawHandle);
27217
27383
  const client = await ctx.client();
27218
27384
  const workspace = await client.getWorkspace(handle);
27219
- await ctx.updateLocalConfig({ defaultWorkspace: workspace.handle });
27220
- if (account)
27221
- await client.patchMe({ defaultWorkspaceId: workspace.id });
27385
+ await client.patchMe({ defaultWorkspaceId: workspace.id });
27222
27386
  return result("use", { defaultWorkspace: workspace.handle });
27223
27387
  }
27224
27388
  var isClear = (value) => value.trim().toLowerCase() === "clear";
@@ -27273,6 +27437,14 @@ var PARSERS = {
27273
27437
  }
27274
27438
  return { defaultExposure: parsed.data };
27275
27439
  },
27440
+ "default-format": (value, key) => {
27441
+ if (isClear(value))
27442
+ return { defaultFormat: null };
27443
+ const parsed = DefaultFormat.safeParse(value.trim().toLowerCase());
27444
+ if (!parsed.success)
27445
+ throw usageError(`${key} must be html, markdown, pdf or clear.`);
27446
+ return { defaultFormat: parsed.data };
27447
+ },
27276
27448
  "default-collection": (value, key) => {
27277
27449
  if (isClear(value))
27278
27450
  return { defaultCollectionSlug: null };
@@ -27299,14 +27471,6 @@ var PARSERS = {
27299
27471
  }
27300
27472
  return { defaultLabels: labels };
27301
27473
  },
27302
- "default-approval-mode": (value, key) => {
27303
- if (isClear(value))
27304
- return { defaultApprovalMode: null };
27305
- const parsed = ApprovalMode.safeParse(value.trim().toLowerCase());
27306
- if (!parsed.success)
27307
- throw usageError(`${key} must be none, owner or clear.`);
27308
- return { defaultApprovalMode: parsed.data };
27309
- },
27310
27474
  "default-workspace": async (value, key, ctx) => {
27311
27475
  if (isClear(value))
27312
27476
  return { defaultWorkspaceId: null };
@@ -27356,6 +27520,7 @@ function formatSettings(data) {
27356
27520
  const handle = data.workspaces.find((w) => w.id === s.defaultWorkspaceId)?.handle;
27357
27521
  lines.push(`Default workspace: ${handle ?? s.defaultWorkspaceId}`);
27358
27522
  }
27523
+ lines.push(`Default format: ${s.defaultFormat ?? "agent decides"}`);
27359
27524
  if (s.defaultExposure !== void 0)
27360
27525
  lines.push(`Default exposure: ${s.defaultExposure}`);
27361
27526
  if (s.defaultUnlisted !== void 0)
@@ -27378,16 +27543,64 @@ function formatSettings(data) {
27378
27543
  if (s.defaultCommentsEnabled !== void 0) {
27379
27544
  lines.push(`Default comments: ${onOffText(s.defaultCommentsEnabled)}`);
27380
27545
  }
27381
- if (s.defaultApprovalMode !== void 0)
27382
- lines.push(`Default approval mode: ${s.defaultApprovalMode}`);
27383
27546
  return lines.join("\n");
27384
27547
  }
27548
+ var SETUP_TIP = "Tip: Handout setup can save your publishing defaults (format, audience, labels) and add Handout to your agent's instructions. In Claude Code type /handout:setup (plugin) or /handout-setup; in Codex ask for the handout-setup skill. This tip is shown once.";
27549
+ async function maybeSetupTip(ctx, settings) {
27550
+ if (ctx.quiet)
27551
+ return;
27552
+ if (hasChosenPublishingDefault(settings))
27553
+ return;
27554
+ try {
27555
+ if ((await ctx.localConfig()).setupTipShown === true)
27556
+ return;
27557
+ await ctx.updateLocalConfig({ setupTipShown: true });
27558
+ }
27559
+ catch {
27560
+ return;
27561
+ }
27562
+ ctx.info(SETUP_TIP);
27563
+ }
27385
27564
  async function runSettingsGet(ctx) {
27386
27565
  const context = "on handout settings get";
27387
27566
  expectPositionals(scanArgs(ctx.args, { context, usage: SETTINGS_GET_USAGE }), context, 0);
27388
27567
  const me = await (await ctx.client()).getMe();
27568
+ await maybeSetupTip(ctx, me.settings);
27389
27569
  return result("settings", { settings: me.settings, workspaces: me.workspaces });
27390
27570
  }
27571
+ var FIELD_KEYS = {
27572
+ emailNotifications: "email-notifications",
27573
+ weeklyDigest: "weekly-digest",
27574
+ defaultUnlisted: "default-unlisted",
27575
+ defaultAllowSourceDownload: "default-allow-source-download",
27576
+ defaultNotifyOnView: "default-notify-on-view",
27577
+ defaultRequestAcknowledgment: "default-request-ack",
27578
+ defaultCommentsEnabled: "default-comments",
27579
+ digestCadence: "digest-cadence",
27580
+ theme: "theme",
27581
+ keepVersions: "keep-versions",
27582
+ defaultExposure: "default-exposure",
27583
+ defaultFormat: "default-format",
27584
+ defaultCollectionSlug: "default-collection",
27585
+ defaultLabels: "default-labels",
27586
+ defaultWorkspaceId: "default-workspace"
27587
+ };
27588
+ function reportUnsaved(ctx, patch, settings) {
27589
+ const requested = Object.entries(patch);
27590
+ const dropped = requested.filter(([field, value]) => {
27591
+ if (value === null || Array.isArray(value) && value.length === 0)
27592
+ return false;
27593
+ return settings[field] === void 0;
27594
+ }).map(([field]) => FIELD_KEYS[field] ?? field);
27595
+ if (dropped.length === 0)
27596
+ return;
27597
+ const names = dropped.join(", ");
27598
+ const detail = `the server didn't save ${names} (it may be running an older Handout version).`;
27599
+ if (dropped.length === requested.length) {
27600
+ throw new CliError(`Nothing was saved: ${detail}`, { exitCode: 1, code: "settings_not_saved" });
27601
+ }
27602
+ ctx.warn(`Warning: ${detail}`);
27603
+ }
27391
27604
  async function runSettingsSet(ctx) {
27392
27605
  const tokens = [];
27393
27606
  for (const token of ctx.args) {
@@ -27400,6 +27613,7 @@ async function runSettingsSet(ctx) {
27400
27613
  const patch = await buildSettingsPatch(tokens, ctx);
27401
27614
  const client = await ctx.client();
27402
27615
  const settings = await client.patchMe(patch);
27616
+ reportUnsaved(ctx, patch, settings);
27403
27617
  const workspaces = settings.defaultWorkspaceId === void 0 ? [] : (await client.getMe()).workspaces;
27404
27618
  return result("settings", { settings, workspaces });
27405
27619
  }
@@ -27508,8 +27722,8 @@ function respond(res, status, page2) {
27508
27722
  function startCallbackServer(pkce, timeoutMs, host) {
27509
27723
  return new Promise((resolveStart, rejectStart) => {
27510
27724
  let settle2 = () => void 0;
27511
- const outcome = new Promise((resolve2) => {
27512
- settle2 = resolve2;
27725
+ const outcome = new Promise((resolve3) => {
27726
+ settle2 = resolve3;
27513
27727
  });
27514
27728
  let received = false;
27515
27729
  const server = createServer((req, res) => {
@@ -27576,7 +27790,7 @@ function startCallbackServer(pkce, timeoutMs, host) {
27576
27790
  server.close();
27577
27791
  server.closeAllConnections();
27578
27792
  };
27579
- const result2 = new Promise((resolve2, reject) => {
27793
+ const result2 = new Promise((resolve3, reject) => {
27580
27794
  timer = setTimeout(() => {
27581
27795
  close();
27582
27796
  reject(new CliError("Sign-in timed out after 5 minutes; run handout login again.", {
@@ -27593,7 +27807,7 @@ function startCallbackServer(pkce, timeoutMs, host) {
27593
27807
  if (timer !== void 0)
27594
27808
  clearTimeout(timer);
27595
27809
  let answered = false;
27596
- resolve2({
27810
+ resolve3({
27597
27811
  code: value.code,
27598
27812
  finish: (status, page2) => {
27599
27813
  if (answered)
@@ -27798,15 +28012,20 @@ async function runLogin(ctx) {
27798
28012
  const localConfig = await ctx.localConfig();
27799
28013
  const env = { ...ctx.env };
27800
28014
  delete env["HANDOUT_REFRESH_TOKEN"];
28015
+ const forThisWrite = { ...localConfig };
28016
+ delete forThisWrite.noKeychain;
27801
28017
  const store = openStore(ctx.host, {
27802
28018
  env,
27803
- localConfig,
28019
+ localConfig: forThisWrite,
27804
28020
  noKeychain: flags.noKeychain,
27805
28021
  fallbackApiKey: connection.config.firebase.apiKey
27806
28022
  });
27807
- await store.write(credential);
27808
- if (store.writtenTo === "keychain" || store.writtenTo === "file") {
27809
- await ctx.updateLocalConfig({ credentials: store.writtenTo });
28023
+ await store.replace(credential);
28024
+ if (flags.noKeychain !== (localConfig.noKeychain === true)) {
28025
+ await ctx.updateLocalConfig({ noKeychain: flags.noKeychain ? true : void 0 });
28026
+ }
28027
+ if (store.writtenTo === "file" && !store.keychainDisabled) {
28028
+ ctx.info(`Saved your login to ${store.filePath} (no system keychain is available).`);
27810
28029
  }
27811
28030
  await rememberHost(ctx, localConfig.host);
27812
28031
  const data = { email: credential.email, uid: credential.uid };
@@ -28144,17 +28363,46 @@ var commands9 = {
28144
28363
  };
28145
28364
  var labels_exports = {};
28146
28365
  __export(labels_exports, {
28366
+ applyAdd: () => applyAdd2,
28367
+ applyRemove: () => applyRemove2,
28368
+ applyReorder: () => applyReorder2,
28147
28369
  commands: () => commands10,
28148
- formatLabels: () => formatLabels
28370
+ formatLabels: () => formatLabels,
28371
+ formatLabelsEdit: () => formatLabelsEdit,
28372
+ parseLabelArgs: () => parseLabelArgs
28149
28373
  });
28150
- var USAGE_TEXT = buildUsage({
28151
- synopsis: ["handout labels"],
28374
+ var LIST_USAGE3 = buildUsage({
28375
+ synopsis: ["handout labels [list]"],
28152
28376
  description: "Shows the workspace's suggested labels with how many documents carry each, then any other labels in use. A label says what kind of document it is (plan, spec, report); a collection says what it belongs to. Pick from the suggested list and ask before inventing a label.",
28153
28377
  examples: ["handout labels", "handout labels --json"]
28154
28378
  });
28379
+ var ADD_USAGE2 = buildUsage({
28380
+ synopsis: ["handout labels add <label>..."],
28381
+ description: `Adds labels to the end of the suggested list (at most ${MAX_SUGGESTED_LABELS}). A label is 1-24 characters; a label already on the list, in any letter case, is left as it is. These are suggestions: any label still works on a document.`,
28382
+ examples: ["handout labels add contract", "handout labels add contract,memo --json"]
28383
+ });
28384
+ var REMOVE_USAGE2 = buildUsage({
28385
+ synopsis: ["handout labels remove <label>..."],
28386
+ description: "Removes labels from the suggested list. Documents that carry a label keep it; it stays a label in use.",
28387
+ examples: ["handout labels remove prototype"]
28388
+ });
28389
+ var REORDER_USAGE2 = buildUsage({
28390
+ synopsis: ["handout labels reorder <label>..."],
28391
+ description: "Lists every suggested label exactly once, in the new order. Run handout labels to see the current order.",
28392
+ examples: ["handout labels reorder spec plan report review guide notes proposal prototype"]
28393
+ });
28394
+ var SEED_USAGE = buildUsage({
28395
+ synopsis: ["handout labels seed"],
28396
+ description: `Adds the starter set (${SEED_SUGGESTED_LABELS.join(", ")}) to the end of the suggested list. A label already on the list stays where it is, so nothing is lost.`,
28397
+ examples: ["handout labels seed"]
28398
+ });
28155
28399
  function rows(items) {
28156
28400
  const width = Math.max(0, ...items.map((item) => item.label.length));
28157
- return items.map((item) => ` ${item.label.padEnd(width)} ${plural2(item.count, "document")}`);
28401
+ return items.map((item) => {
28402
+ const row2 = ` ${item.label.padEnd(width)} ${plural2(item.count, "document")}`;
28403
+ const match = item.matchesCollection;
28404
+ return match === void 0 ? row2 : `${row2} (all in collection "${match.name}" (${match.slug}); suggest the collection instead)`;
28405
+ });
28158
28406
  }
28159
28407
  function formatLabels(data) {
28160
28408
  const lines = [];
@@ -28162,7 +28410,7 @@ function formatLabels(data) {
28162
28410
  lines.push("Suggested labels:", ...rows(data.suggested));
28163
28411
  }
28164
28412
  else if (data.seedable === true) {
28165
- lines.push("No suggested labels yet. This workspace already uses labels, so none were added for you.", "Adopt the suggested set from the workspace's settings page.");
28413
+ lines.push("No suggested labels yet. This workspace already uses labels, so none were added for you.", "Add the suggested set with: handout labels seed");
28166
28414
  }
28167
28415
  else {
28168
28416
  lines.push("No suggested labels.");
@@ -28175,21 +28423,123 @@ function formatLabels(data) {
28175
28423
  return lines.join("\n");
28176
28424
  }
28177
28425
  registerOutput("labels", passthrough(formatLabels));
28178
- async function runLabels(ctx) {
28426
+ async function runList3(ctx) {
28179
28427
  const context = "on handout labels";
28180
- expectPositionals(scanArgs(ctx.args, { context, usage: USAGE_TEXT }), context, 0);
28428
+ expectPositionals(scanArgs(ctx.args, { context, usage: LIST_USAGE3 }), context, 0);
28181
28429
  const handle = await ctx.workspace();
28182
28430
  return result("labels", await (await ctx.client()).getWorkspaceLabels(handle));
28183
28431
  }
28432
+ var keyOf = (label) => label.toLowerCase();
28433
+ function parseLabelArgs(positionals) {
28434
+ const labels = [];
28435
+ for (const token of positionals) {
28436
+ for (const part of token.split(",")) {
28437
+ const label = part.trim();
28438
+ if (label === "")
28439
+ continue;
28440
+ if (!DocumentLabel.safeParse(label).success) {
28441
+ throw usageError(`"${label}" must be 1-24 characters.`);
28442
+ }
28443
+ labels.push(label);
28444
+ }
28445
+ }
28446
+ return labels;
28447
+ }
28448
+ function applyAdd2(current, labels) {
28449
+ const next = [...current];
28450
+ const present = new Set(next.map(keyOf));
28451
+ const added = [];
28452
+ const skipped = [];
28453
+ for (const label of normalizeSuggestedLabels(labels)) {
28454
+ if (present.has(keyOf(label))) {
28455
+ skipped.push(label);
28456
+ }
28457
+ else {
28458
+ present.add(keyOf(label));
28459
+ next.push(label);
28460
+ added.push(label);
28461
+ }
28462
+ }
28463
+ if (next.length > MAX_SUGGESTED_LABELS)
28464
+ throw usageError(MAX_SUGGESTED_LABELS_MESSAGE);
28465
+ return { suggestedLabels: next, added, removed: [], skipped };
28466
+ }
28467
+ function applyRemove2(current, labels) {
28468
+ const drop = new Set(labels.map(keyOf));
28469
+ const stored = new Set(current.map(keyOf));
28470
+ return {
28471
+ suggestedLabels: current.filter((label) => !drop.has(keyOf(label))),
28472
+ added: [],
28473
+ removed: current.filter((label) => drop.has(keyOf(label))),
28474
+ skipped: normalizeSuggestedLabels(labels).filter((label) => !stored.has(keyOf(label)))
28475
+ };
28476
+ }
28477
+ function applyReorder2(current, labels) {
28478
+ const suggestedLabels = reorderExactly(current, labels, {
28479
+ noun: "suggested label",
28480
+ nameOf: (label) => label,
28481
+ fold: keyOf
28482
+ });
28483
+ return { suggestedLabels, added: [], removed: [], skipped: [] };
28484
+ }
28485
+ var EDIT_USAGE = {
28486
+ add: ADD_USAGE2,
28487
+ remove: REMOVE_USAGE2,
28488
+ reorder: REORDER_USAGE2,
28489
+ seed: SEED_USAGE
28490
+ };
28491
+ async function runEdit(ctx, kind) {
28492
+ const context = `on handout labels ${kind}`;
28493
+ const scanned = scanArgs(ctx.args, { context, usage: EDIT_USAGE[kind] });
28494
+ let labels = [];
28495
+ if (kind === "seed") {
28496
+ expectPositionals(scanned, context, 0);
28497
+ }
28498
+ else {
28499
+ labels = parseLabelArgs(scanned.positionals);
28500
+ if (labels.length === 0) {
28501
+ throw usageError(`labels ${kind} requires at least one label (handout labels ${kind} <label>\u2026).`);
28502
+ }
28503
+ }
28504
+ const handle = await ctx.workspace();
28505
+ const client = await ctx.client();
28506
+ const workspace = await client.getWorkspace(handle);
28507
+ const current = workspace.suggestedLabels ?? [];
28508
+ const edit = kind === "add" ? applyAdd2(current, labels) : kind === "seed" ? applyAdd2(current, SEED_SUGGESTED_LABELS) : kind === "remove" ? applyRemove2(current, labels) : applyReorder2(current, labels);
28509
+ if (kind === "add" || kind === "remove") {
28510
+ const note = kind === "add" ? "is already suggested" : "is not suggested";
28511
+ for (const label of edit.skipped)
28512
+ ctx.info(`${label} ${note}`);
28513
+ }
28514
+ const changed = edit.suggestedLabels.length !== current.length || edit.suggestedLabels.some((label, index) => label !== current[index]);
28515
+ let suggestedLabels = current;
28516
+ if (changed) {
28517
+ const saved = await client.patchWorkspace(handle, {
28518
+ suggestedLabels: [...edit.suggestedLabels],
28519
+ expectedUpdatedAt: workspace.updatedAt
28520
+ });
28521
+ suggestedLabels = saved.suggestedLabels ?? edit.suggestedLabels;
28522
+ }
28523
+ ctx.info(`added ${edit.added.length} \xB7 removed ${edit.removed.length} \xB7 ${plural2(suggestedLabels.length, "label")}`);
28524
+ return result("labels-edit", { suggestedLabels, added: edit.added, removed: edit.removed });
28525
+ }
28526
+ function formatLabelsEdit(data) {
28527
+ return data.suggestedLabels.length === 0 ? "No suggested labels." : `Suggested labels: ${data.suggestedLabels.join(", ")}`;
28528
+ }
28529
+ registerOutput("labels-edit", passthrough(formatLabelsEdit));
28184
28530
  var commands10 = {
28185
- labels: { usage: USAGE_TEXT, run: runLabels }
28531
+ "labels list": { usage: LIST_USAGE3, run: runList3 },
28532
+ "labels add": { usage: ADD_USAGE2, run: (ctx) => runEdit(ctx, "add") },
28533
+ "labels remove": { usage: REMOVE_USAGE2, run: (ctx) => runEdit(ctx, "remove") },
28534
+ "labels reorder": { usage: REORDER_USAGE2, run: (ctx) => runEdit(ctx, "reorder") },
28535
+ "labels seed": { usage: SEED_USAGE, run: (ctx) => runEdit(ctx, "seed") }
28186
28536
  };
28187
28537
  var usage_exports = {};
28188
28538
  __export(usage_exports, {
28189
28539
  commands: () => commands11,
28190
28540
  formatUsage: () => formatUsage
28191
28541
  });
28192
- var USAGE_TEXT2 = buildUsage({
28542
+ var USAGE_TEXT = buildUsage({
28193
28543
  synopsis: ["handout usage"],
28194
28544
  description: "Shows your account's documents against its limit across all your workspaces, then storage per workspace and per document, biggest documents first.",
28195
28545
  examples: ["handout usage", "handout usage --json"]
@@ -28217,22 +28567,26 @@ function formatUsage(usage) {
28217
28567
  }
28218
28568
  async function runUsage(ctx) {
28219
28569
  const context = "on handout usage";
28220
- expectPositionals(scanArgs(ctx.args, { context, usage: USAGE_TEXT2 }), context, 0);
28570
+ expectPositionals(scanArgs(ctx.args, { context, usage: USAGE_TEXT }), context, 0);
28221
28571
  if (ctx.global.workspace !== void 0)
28222
28572
  throw usageError(WORKSPACE_REFUSED);
28223
28573
  return result("usage", await (await ctx.client()).getUsage());
28224
28574
  }
28225
28575
  registerOutput("usage", { json: (data) => data, text: formatUsage });
28226
28576
  var commands11 = {
28227
- usage: { usage: USAGE_TEXT2, run: runUsage }
28577
+ usage: { usage: USAGE_TEXT, run: runUsage }
28228
28578
  };
28229
28579
  var skill_exports = {};
28230
28580
  __export(skill_exports, {
28231
28581
  LEGACY_INSTALL_FILES: () => LEGACY_INSTALL_FILES,
28582
+ SETUP_SKILL_FOLDER: () => SETUP_SKILL_FOLDER,
28232
28583
  SKILL_AGENTS: () => SKILL_AGENTS,
28233
28584
  SKILL_FOLDER: () => SKILL_FOLDER,
28234
28585
  agentSkillsDir: () => agentSkillsDir,
28235
28586
  commands: () => commands12,
28587
+ expandHome: () => expandHome,
28588
+ home: () => home,
28589
+ packagedSetupSkillPath: () => packagedSetupSkillPath,
28236
28590
  packagedSkillPath: () => packagedSkillPath
28237
28591
  });
28238
28592
  import { randomBytes as randomBytes3 } from "node:crypto";
@@ -28269,17 +28623,23 @@ function packagedSkillPath(env, moduleUrl = import.meta.url) {
28269
28623
  if (override !== void 0 && override !== "")
28270
28624
  return resolve(override);
28271
28625
  const here = dirname2(fileURLToPath(moduleUrl));
28272
- const bundled = "1.4.0".length > 0;
28626
+ const bundled = "1.6.0".length > 0;
28273
28627
  return bundled ? join4(here, "SKILL.md") : join4(here, "..", "..", "SKILL.md");
28274
28628
  }
28629
+ var SETUP_SKILL_FOLDER = "handout-setup";
28630
+ function packagedSetupSkillPath(env, moduleUrl = import.meta.url) {
28631
+ return join4(dirname2(packagedSkillPath(env, moduleUrl)), "setup", "SKILL.md");
28632
+ }
28275
28633
  var INSTALL_USAGE = buildUsage({
28276
28634
  synopsis: ["handout skill install --agent claude|codex", "handout skill install --dir <path>"],
28277
28635
  description: [
28278
- "Copies the SKILL.md that ships with this CLI into an agent's skills directory, as",
28279
- `<dir>/${SKILL_FOLDER}/SKILL.md, so the agent can discover Handout. Re-run it after updating the CLI.`,
28636
+ "Copies the two skills that ship with this CLI into an agent's skills directory, so the agent",
28637
+ `can discover Handout: <dir>/${SKILL_FOLDER}/SKILL.md (publishing) and`,
28638
+ `<dir>/${SETUP_SKILL_FOLDER}/SKILL.md (the one-time guided setup, which you start yourself).`,
28639
+ "Re-run it after updating the CLI.",
28280
28640
  " --agent claude ~/.claude/skills (or $CLAUDE_CONFIG_DIR/skills)",
28281
28641
  " --agent codex ~/.agents/skills",
28282
- "Claude Code can install the skill as a plugin instead: /plugin marketplace add usehandout/handout,",
28642
+ "Claude Code can install the skills as a plugin instead: /plugin marketplace add usehandout/handout,",
28283
28643
  "then /plugin install handout@usehandout. Use one or the other, not both."
28284
28644
  ].join("\n"),
28285
28645
  flags: [
@@ -28295,13 +28655,24 @@ var INSTALL_USAGE = buildUsage({
28295
28655
  function describeTarget(data) {
28296
28656
  return data.agent === null ? "" : ` for ${SKILL_AGENTS[data.agent].label}`;
28297
28657
  }
28658
+ function installLine(name, skill, data) {
28659
+ const target = describeTarget(data);
28660
+ if (skill.status === "unchanged") {
28661
+ return `The ${name}${target} is already up to date (${data.version}): ${skill.path}`;
28662
+ }
28663
+ const verb = skill.status === "installed" ? "Installed" : "Updated";
28664
+ return `${verb} the ${name}${target} (${data.version}): ${skill.path}`;
28665
+ }
28298
28666
  registerOutput("skill-install", {
28299
28667
  json: (data) => data,
28300
- text: (data) => data.status === "unchanged" ? `The Handout skill${describeTarget(data)} is already up to date (${data.version}): ${data.path}` : `${data.status === "installed" ? "Installed" : "Updated"} the Handout skill${describeTarget(data)} (${data.version}): ${data.path}`,
28668
+ text: (data) => [
28669
+ installLine("Handout skill", data, data),
28670
+ installLine("Handout setup skill", data.setup, data)
28671
+ ].join("\n"),
28301
28672
  notes: (data) => {
28302
28673
  const notes = [];
28303
- if (data.status !== "unchanged") {
28304
- notes.push(data.agent === null ? "Point your agent at that file, or start a new session if it discovers skills itself." : `Start a new ${SKILL_AGENTS[data.agent].label} session to load it.`);
28674
+ if (data.status !== "unchanged" || data.setup.status !== "unchanged") {
28675
+ notes.push(data.agent === null ? "Point your agent at those files, or start a new session if it discovers skills itself." : `Start a new ${SKILL_AGENTS[data.agent].label} session to load them.`);
28305
28676
  }
28306
28677
  if (data.legacyFiles.length > 0) {
28307
28678
  const folder = dirname2(data.path);
@@ -28326,6 +28697,37 @@ function expandHome(path, env) {
28326
28697
  return join4(home(env), path.slice(2));
28327
28698
  return path;
28328
28699
  }
28700
+ async function readPackaged(source, what) {
28701
+ try {
28702
+ return await readFile4(source);
28703
+ }
28704
+ catch (err) {
28705
+ throw fileError(`This CLI's ${what} is missing (${source}): ${errorMessage(err)}. Reinstall the CLI.`, err);
28706
+ }
28707
+ }
28708
+ async function installOne(contents, folder) {
28709
+ const target = join4(folder, "SKILL.md");
28710
+ let current;
28711
+ try {
28712
+ current = await readFile4(target);
28713
+ }
28714
+ catch {
28715
+ current = void 0;
28716
+ }
28717
+ if (current !== void 0 && current.equals(contents))
28718
+ return { path: target, status: "unchanged" };
28719
+ const staged = `${target}.${randomBytes3(6).toString("hex")}.tmp`;
28720
+ try {
28721
+ await mkdir2(folder, { recursive: true });
28722
+ await writeFile3(staged, contents);
28723
+ await rename2(staged, target);
28724
+ }
28725
+ catch (err) {
28726
+ await rm3(staged, { force: true }).catch(() => void 0);
28727
+ throw fileError(`Could not write ${target}: ${errorMessage(err)}.`, err);
28728
+ }
28729
+ return { path: target, status: current === void 0 ? "installed" : "updated" };
28730
+ }
28329
28731
  async function runSkillInstall(ctx) {
28330
28732
  const scanned = scanArgs(ctx.args, {
28331
28733
  context: "on handout skill install",
@@ -28357,62 +28759,642 @@ ${INSTALL_USAGE}`);
28357
28759
  const expanded = expandHome(raw, ctx.env);
28358
28760
  skillsDir = isAbsolute(expanded) ? expanded : resolve(expanded);
28359
28761
  }
28360
- const source = packagedSkillPath(ctx.env);
28361
- let contents;
28762
+ const main2 = await readPackaged(packagedSkillPath(ctx.env), "SKILL.md");
28763
+ const setupSkill = await readPackaged(packagedSetupSkillPath(ctx.env), "setup skill");
28764
+ const folder = join4(skillsDir, SKILL_FOLDER);
28765
+ const installed = await installOne(main2, folder);
28766
+ const setup = await installOne(setupSkill, join4(skillsDir, SETUP_SKILL_FOLDER));
28767
+ const legacyFiles = [];
28768
+ for (const name of LEGACY_INSTALL_FILES) {
28769
+ if (await exists(join4(folder, name)))
28770
+ legacyFiles.push(name);
28771
+ }
28772
+ const data = {
28773
+ agent,
28774
+ path: installed.path,
28775
+ status: installed.status,
28776
+ version: bundledVersion(),
28777
+ legacyFiles,
28778
+ setup
28779
+ };
28780
+ return result("skill-install", data);
28781
+ }
28782
+ var commands12 = {
28783
+ "skill install": { usage: INSTALL_USAGE, run: runSkillInstall }
28784
+ };
28785
+ var setup_exports = {};
28786
+ __export(setup_exports, {
28787
+ BEGIN_MARKER: () => BEGIN_MARKER,
28788
+ END_MARKER: () => END_MARKER,
28789
+ INSTRUCTIONS_VERSION: () => INSTRUCTIONS_VERSION,
28790
+ INSTRUCTION_AGENTS: () => INSTRUCTION_AGENTS,
28791
+ INSTRUCTION_LINES: () => INSTRUCTION_LINES,
28792
+ MY_RULES_HEADING: () => MY_RULES_HEADING,
28793
+ commands: () => commands13,
28794
+ instructionBlock: () => instructionBlock,
28795
+ instructionsPath: () => instructionsPath,
28796
+ mergeInstructions: () => mergeInstructions
28797
+ });
28798
+ import { readFile as readFile5, stat as stat3 } from "node:fs/promises";
28799
+ import { basename as basename5, dirname as dirname3, isAbsolute as isAbsolute2, join as join5, resolve as resolve2 } from "node:path";
28800
+ var INSTRUCTIONS_VERSION = 1;
28801
+ var BEGIN_MARKER = `<!-- handout:begin v${INSTRUCTIONS_VERSION} -->`;
28802
+ var END_MARKER = "<!-- handout:end -->";
28803
+ var INSTRUCTION_LINES = [
28804
+ "## Handout",
28805
+ "",
28806
+ "- After you create a finished, user-facing HTML, Markdown or PDF document, briefly offer to publish it with Handout (the `handout` skill). Skip routine source files, intermediate drafts and secrets, and don't offer again after I decline. Publish only when I ask or approve.",
28807
+ "- Before you produce or publish a document, run `handout settings get --json` and follow my saved defaults (format, audience, labels and the rest) unless I say otherwise in the request. Don't change my Handout settings unless I ask.",
28808
+ "- For a document that is already published, update the same link (`handout update <slug> <file>`) and keep its audience. Never publish a second copy.",
28809
+ "- Never publish with `--exposure open` (anyone with the link) unless I ask for that.",
28810
+ "- After publishing, give me the link exactly as the CLI printed it.",
28811
+ "- Labels say what kind of document it is (`plan`, `spec`, `report`); collections say what it belongs to (a project, client or period). Reuse existing labels and ask before inventing one.",
28812
+ "- When two or more documents belong to the same project, suggest putting them in a collection."
28813
+ ];
28814
+ function instructionBlock(eol = "\n") {
28815
+ return [BEGIN_MARKER, ...INSTRUCTION_LINES, END_MARKER].join(eol);
28816
+ }
28817
+ var BOM = "\uFEFF";
28818
+ var BEGIN_LINE = /^<!-- handout:begin v(\d+) -->[ \t]*\r?$/gm;
28819
+ var END_LINE = /^<!-- handout:end -->[ \t]*\r?$/gm;
28820
+ function mergeInstructions(existing, keep = []) {
28821
+ if (existing === null) {
28822
+ return {
28823
+ status: "new-file",
28824
+ proposed: `${instructionBlock()}
28825
+ `,
28826
+ foundVersion: null,
28827
+ existingSection: null
28828
+ };
28829
+ }
28830
+ if (existing.startsWith(BOM)) {
28831
+ const merged = mergeInstructions(existing.slice(BOM.length), keep);
28832
+ return merged.proposed === null || merged.status === "new-file" ? merged : { ...merged, proposed: `${BOM}${merged.proposed}` };
28833
+ }
28834
+ const eol = existing.includes("\r\n") ? "\r\n" : "\n";
28835
+ const block = instructionBlock(eol);
28836
+ const begins = [...existing.matchAll(BEGIN_LINE)];
28837
+ const ends = [...existing.matchAll(END_LINE)];
28838
+ if (begins.length === 0 && ends.length === 0) {
28839
+ const sections = findHandoutSections(existing, null);
28840
+ const first = sections[0];
28841
+ if (first === void 0) {
28842
+ const body = existing.replace(/(\r?\n)+$/, "");
28843
+ const proposed3 = body === "" ? `${block}${eol}` : `${body}${eol}${eol}${block}${eol}`;
28844
+ return { status: "add", proposed: proposed3, foundVersion: null, existingSection: null };
28845
+ }
28846
+ const existingSection = describe3(first, existing);
28847
+ if (sections.length > 1) {
28848
+ return { status: "conflict", proposed: null, foundVersion: null, existingSection };
28849
+ }
28850
+ const proposed2 = existing.slice(0, first.start) + block + keptAfterBlock(existingSection.text, keep, eol) + existing.slice(first.textEnd);
28851
+ return { status: "unmarked", proposed: proposed2, foundVersion: null, existingSection };
28852
+ }
28853
+ const begin = begins[0];
28854
+ const end = ends[0];
28855
+ if (begins.length !== 1 || ends.length !== 1 || begin === void 0 || end === void 0 || end.index < begin.index) {
28856
+ return { status: "conflict", proposed: null, foundVersion: null, existingSection: null };
28857
+ }
28858
+ const endText = end[0].endsWith("\r") ? end[0].slice(0, -1) : end[0];
28859
+ const blockEnd = end.index + endText.length;
28860
+ const stray = findHandoutSections(existing, [begin.index, blockEnd])[0];
28861
+ if (stray !== void 0) {
28862
+ return {
28863
+ status: "conflict",
28864
+ proposed: null,
28865
+ foundVersion: null,
28866
+ existingSection: describe3(stray, existing)
28867
+ };
28868
+ }
28869
+ const foundVersion = Number(begin[1]);
28870
+ if (foundVersion > INSTRUCTIONS_VERSION) {
28871
+ return { status: "newer", proposed: null, foundVersion, existingSection: null };
28872
+ }
28873
+ const proposed = existing.slice(0, begin.index) + block + existing.slice(blockEnd);
28874
+ return {
28875
+ status: proposed === existing ? "current" : "replace",
28876
+ proposed,
28877
+ foundVersion,
28878
+ existingSection: null
28879
+ };
28880
+ }
28881
+ function describe3(found, file2) {
28882
+ const text = file2.slice(found.start, found.textEnd);
28883
+ return {
28884
+ startLine: found.startLine,
28885
+ endLine: found.endLine,
28886
+ text,
28887
+ items: splitEntries(text).map((entry) => entry.lines.join("\n"))
28888
+ };
28889
+ }
28890
+ var MY_RULES_HEADING = "### My Handout rules";
28891
+ var LIST_ITEM = /^(?:[-*+]|\d+[.)])[ \t]+/;
28892
+ function splitEntries(section2) {
28893
+ const entries = [];
28894
+ let gap = 0;
28895
+ let fence = null;
28896
+ for (const line of section2.split(/\r?\n/).slice(1)) {
28897
+ const last = entries.at(-1);
28898
+ if (fence !== null && last !== void 0) {
28899
+ last.lines.push(line);
28900
+ if (line.trim().startsWith(fence))
28901
+ fence = null;
28902
+ continue;
28903
+ }
28904
+ if (line.trim() === "") {
28905
+ gap += 1;
28906
+ continue;
28907
+ }
28908
+ const opens = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
28909
+ if (last === void 0 || LIST_ITEM.test(line) || gap > 0 && !/^[ \t]/.test(line)) {
28910
+ entries.push({ lines: [line], gap });
28911
+ }
28912
+ else {
28913
+ last.lines.push(...Array(gap).fill(""), line);
28914
+ }
28915
+ if (opens !== void 0)
28916
+ fence = opens;
28917
+ gap = 0;
28918
+ }
28919
+ return entries;
28920
+ }
28921
+ function keptAfterBlock(section2, keep, eol) {
28922
+ const chosen = splitEntries(section2).filter((_, i) => keep.includes(i + 1));
28923
+ if (chosen.length === 0)
28924
+ return "";
28925
+ const body = chosen.map((entry, i) => (i === 0 ? "" : eol.repeat(entry.gap + 1)) + entry.lines.join(eol)).join("");
28926
+ return `${eol}${eol}${MY_RULES_HEADING}${eol}${eol}${body}`;
28927
+ }
28928
+ var HEADING = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$/;
28929
+ var FENCE = /^ {0,3}(`{3,}|~{3,})/;
28930
+ var HANDOUT_TITLE = /^handout(?![\p{L}\p{N}_])/iu;
28931
+ function findHandoutSections(text, skip) {
28932
+ const found = [];
28933
+ let open2 = null;
28934
+ let fence = null;
28935
+ let lastText = 0;
28936
+ let lastTextLine = 0;
28937
+ const close = () => {
28938
+ if (open2 === null)
28939
+ return;
28940
+ found.push({
28941
+ start: open2.start,
28942
+ textEnd: lastText,
28943
+ startLine: open2.startLine,
28944
+ endLine: lastTextLine
28945
+ });
28946
+ open2 = null;
28947
+ };
28948
+ let offset = 0;
28949
+ let lineNo = 0;
28950
+ while (offset <= text.length) {
28951
+ const nl = text.indexOf("\n", offset);
28952
+ const next = nl === -1 ? text.length + 1 : nl + 1;
28953
+ const raw = text.slice(offset, nl === -1 ? text.length : nl);
28954
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
28955
+ lineNo += 1;
28956
+ const inSkip = skip !== null && offset >= skip[0] && offset < skip[1];
28957
+ if (!inSkip) {
28958
+ const fenceMatch = FENCE.exec(line);
28959
+ const fenceRun = fenceMatch?.[1];
28960
+ if (fence !== null) {
28961
+ if (fenceRun?.[0] === fence.char && fenceRun.length >= fence.size && line.trim() === fenceRun) {
28962
+ fence = null;
28963
+ }
28964
+ }
28965
+ else if (fenceRun !== void 0) {
28966
+ fence = { char: fenceRun[0] ?? "`", size: fenceRun.length };
28967
+ }
28968
+ else {
28969
+ const heading = HEADING.exec(line);
28970
+ if (heading !== null) {
28971
+ const level = heading[1]?.length ?? 1;
28972
+ if (open2 !== null && level <= open2.level)
28973
+ close();
28974
+ const title = (heading[2] ?? "").replace(/[ \t]+#+$/, "").trim();
28975
+ if (open2 === null && HANDOUT_TITLE.test(title)) {
28976
+ open2 = { start: offset, level, startLine: lineNo };
28977
+ }
28978
+ }
28979
+ }
28980
+ }
28981
+ if (line.trim() !== "" && open2 !== null) {
28982
+ lastText = offset + line.length;
28983
+ lastTextLine = lineNo;
28984
+ }
28985
+ offset = next;
28986
+ }
28987
+ close();
28988
+ return found;
28989
+ }
28990
+ var INSTRUCTION_AGENTS = {
28991
+ ...SKILL_AGENTS,
28992
+ other: { label: "your agent" }
28993
+ };
28994
+ function instructionsPath(agent, scope, env, cwd, platform = process.platform) {
28995
+ if (agent === "other")
28996
+ return null;
28997
+ const file2 = agent === "claude" ? "CLAUDE.md" : "AGENTS.md";
28998
+ if (scope === "project")
28999
+ return join5(cwd, file2);
29000
+ const override = env[agent === "claude" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME"]?.trim();
29001
+ if (override !== void 0 && override !== "")
29002
+ return join5(override, file2);
29003
+ return join5(home(env, platform), agent === "claude" ? ".claude" : ".codex", file2);
29004
+ }
29005
+ function shadowingFile(agent, path) {
29006
+ return agent === "codex" && basename5(path) === "AGENTS.md" ? join5(dirname3(path), "AGENTS.override.md") : null;
29007
+ }
29008
+ var PRINT_USAGE = buildUsage({
29009
+ synopsis: [
29010
+ "handout setup print-instructions --agent claude|codex|other [--scope global|project]",
29011
+ "handout setup print-instructions --agent <name> --file <path>",
29012
+ "handout setup print-instructions --agent <name> [--file <path>] --keep <n,n,...|none>"
29013
+ ],
29014
+ description: [
29015
+ "Prints the Handout block for an agent's instructions file, between version markers, and on",
29016
+ "stderr which file it belongs in and what adding it would change. It never writes the file:",
29017
+ "--json adds the whole proposed file and a diff, for the handout-setup skill to show before it",
29018
+ "writes. A re-run replaces the block between the markers; it is never duplicated.",
29019
+ "A hand-written Handout section outside the markers is listed with numbered entries (existingSection.items);",
29020
+ "the proposal replaces it, or with --keep also keeps the numbered entries you name, verbatim and in their",
29021
+ "original order, under \"### My Handout rules\" after the end marker. It never decides which to keep.",
29022
+ " --scope global (default) the agent's own instructions, for every project",
29023
+ " --scope project the instructions file in the current directory"
29024
+ ].join("\n"),
29025
+ flags: [
29026
+ ["--agent <name>", "claude, codex or other"],
29027
+ ["--scope <scope>", "global (default) or project"],
29028
+ ["--file <path>", "Another instructions file (instead of --scope)"],
29029
+ [
29030
+ "--keep <n,n,...|none>",
29031
+ "Hand-written section only: the entry numbers to keep (none = replace)"
29032
+ ]
29033
+ ],
29034
+ examples: [
29035
+ "handout setup print-instructions --agent claude",
29036
+ "handout setup print-instructions --agent codex --scope project --json",
29037
+ "handout setup print-instructions --agent other --file ~/.config/my-agent/AGENTS.md"
29038
+ ]
29039
+ });
29040
+ function statusNote(data) {
29041
+ switch (data.status) {
29042
+ case "new-file":
29043
+ return "It does not exist yet: it would be created with this block.";
29044
+ case "add":
29045
+ return "It has no Handout block yet: this block would be added at the end.";
29046
+ case "replace":
29047
+ return "It holds an older or edited Handout block: this block would replace it, between the markers.";
29048
+ case "unmarked": {
29049
+ const found = data.existingSection;
29050
+ const where = found === null ? "" : ` (lines ${found.startLine}-${found.endLine})`;
29051
+ const keeps = data.kept === null ? "this block would replace it" : data.kept.length === 0 ? "this block would replace it (--keep none)" : `this block would replace it and keep your ${data.kept.length === 1 ? "entry" : "entries"} ${data.kept.join(", ")} after the end marker, under "${MY_RULES_HEADING}"`;
29052
+ return `It has its own Handout section${where}, written by hand, outside the markers: ${keeps}, so the file keeps one Handout section. Ask before changing it; never add a second copy.`;
29053
+ }
29054
+ case "current":
29055
+ return "It already holds this block: nothing to change.";
29056
+ case "newer":
29057
+ return "It holds a Handout block from a newer CLI: update the CLI (npm install -g @usehandout/cli@latest) instead.";
29058
+ case "conflict":
29059
+ return data.existingSection === null ? "Its Handout markers are repeated, unbalanced or out of order: fix them by hand first. Nothing is proposed." : `It has a Handout section of its own (lines ${data.existingSection.startLine}-${data.existingSection.endLine}) next to a marked block, or several of them: keep only one by hand first. Nothing is proposed.`;
29060
+ default:
29061
+ return "Add the block to your agent's instructions file, or pass --file <path> to see the change.";
29062
+ }
29063
+ }
29064
+ registerOutput("setup-instructions", {
29065
+ json: (data) => data,
29066
+ text: (data) => data.block,
29067
+ notes: (data) => {
29068
+ const where = data.path === null ? [] : [
29069
+ `Instructions file (${INSTRUCTION_AGENTS[data.agent].label}${data.scope === null ? "" : `, ${data.scope}`}): ${data.path}`
29070
+ ];
29071
+ const shadow = data.shadowedBy === null ? [] : [`${data.shadowedBy} exists, and the agent reads it instead of ${data.path}.`];
29072
+ const items = data.existingSection?.items ?? [];
29073
+ const listed = data.status !== "unmarked" || data.kept !== null ? [] : [
29074
+ "Its entries, numbered (keep any of them after the block with --keep <numbers>, e.g. --keep 1,3; --keep none replaces them all):",
29075
+ ...items.flatMap((item, i) => {
29076
+ const [first = "", ...rest] = item.split("\n");
29077
+ return [` ${i + 1}. ${first}`, ...rest.map((line) => ` ${line}`)];
29078
+ })
29079
+ ];
29080
+ return [
29081
+ ...where,
29082
+ statusNote(data),
29083
+ ...listed,
29084
+ ...shadow,
29085
+ "This command never writes the file; --json adds the proposed file and a diff."
29086
+ ];
29087
+ }
29088
+ });
29089
+ async function readIfExists(path) {
28362
29090
  try {
28363
- contents = await readFile4(source);
29091
+ return await readFile5(path, "utf8");
28364
29092
  }
28365
29093
  catch (err) {
28366
- throw fileError(`This CLI's SKILL.md is missing (${source}): ${errorMessage(err)}. Reinstall the CLI.`, err);
29094
+ if (isErrno(err, "ENOENT"))
29095
+ return null;
29096
+ throw fileError(`Could not read ${path}: ${errorMessage(err)}.`, err);
28367
29097
  }
28368
- const folder = join4(skillsDir, SKILL_FOLDER);
28369
- const target = join4(folder, "SKILL.md");
28370
- let current;
29098
+ }
29099
+ async function isFile(path) {
28371
29100
  try {
28372
- current = await readFile4(target);
29101
+ return (await stat3(path)).isFile();
28373
29102
  }
28374
29103
  catch {
28375
- current = void 0;
29104
+ return false;
28376
29105
  }
28377
- let status;
28378
- if (current !== void 0 && current.equals(contents)) {
28379
- status = "unchanged";
29106
+ }
29107
+ function parseKeep(value, count) {
29108
+ const text = value.trim().toLowerCase();
29109
+ if (text === "none")
29110
+ return [];
29111
+ const numbers = text.split(",").map((part) => part.trim());
29112
+ const valid = numbers.every((part) => /^[1-9]\d*$/.test(part) && Number(part) <= count);
29113
+ if (!valid) {
29114
+ throw usageError(`--keep must be "none" or entry numbers between 1 and ${count} separated by commas, like 1,3 (got "${value}").`);
29115
+ }
29116
+ return [...new Set(numbers.map(Number))].sort((a, b) => a - b);
29117
+ }
29118
+ async function runPrintInstructions(ctx) {
29119
+ const context = "on handout setup print-instructions";
29120
+ const scanned = scanArgs(ctx.args, {
29121
+ context,
29122
+ usage: PRINT_USAGE,
29123
+ values: ["--agent", "--scope", "--file", "--keep"]
29124
+ });
29125
+ expectPositionals(scanned, context, 0);
29126
+ const agentValue = lastValue(scanned, "--agent");
29127
+ if (agentValue === void 0) {
29128
+ throw usageError(`Give --agent claude, codex or other.
29129
+
29130
+ ${PRINT_USAGE}`);
29131
+ }
29132
+ const agentName = agentValue.trim().toLowerCase();
29133
+ if (!Object.hasOwn(INSTRUCTION_AGENTS, agentName)) {
29134
+ throw usageError(`--agent must be claude, codex or other (got "${agentValue}").`);
29135
+ }
29136
+ const agent = agentName;
29137
+ const scopeValue = lastValue(scanned, "--scope");
29138
+ const fileValue = lastValue(scanned, "--file");
29139
+ if (scopeValue !== void 0 && fileValue !== void 0) {
29140
+ throw usageError("Give --scope or --file, not both.");
29141
+ }
29142
+ let scope = null;
29143
+ let path;
29144
+ if (fileValue !== void 0) {
29145
+ const raw = fileValue.trim();
29146
+ if (raw === "")
29147
+ throw usageError("--file needs a file path.");
29148
+ const expanded = expandHome(raw, ctx.env);
29149
+ path = isAbsolute2(expanded) ? expanded : resolve2(expanded);
28380
29150
  }
28381
29151
  else {
28382
- status = current === void 0 ? "installed" : "updated";
28383
- const staged = `${target}.${randomBytes3(6).toString("hex")}.tmp`;
28384
- try {
28385
- await mkdir2(folder, { recursive: true });
28386
- await writeFile3(staged, contents);
28387
- await rename2(staged, target);
29152
+ const scopeName = (scopeValue ?? "global").trim().toLowerCase();
29153
+ if (scopeName !== "global" && scopeName !== "project") {
29154
+ throw usageError(`--scope must be global or project (got "${scopeValue}").`);
28388
29155
  }
28389
- catch (err) {
28390
- await rm3(staged, { force: true }).catch(() => void 0);
28391
- throw fileError(`Could not write ${target}: ${errorMessage(err)}.`, err);
29156
+ scope = scopeName;
29157
+ path = instructionsPath(agent, scope, ctx.env, process.cwd());
29158
+ }
29159
+ const block = instructionBlock();
29160
+ let data = {
29161
+ version: INSTRUCTIONS_VERSION,
29162
+ agent,
29163
+ scope,
29164
+ path,
29165
+ status: null,
29166
+ block,
29167
+ proposed: null,
29168
+ existingSection: null,
29169
+ kept: null,
29170
+ diff: null,
29171
+ shadowedBy: null
29172
+ };
29173
+ const keepValue = lastValue(scanned, "--keep");
29174
+ if (path === null) {
29175
+ if (keepValue !== void 0)
29176
+ throw usageError("--keep needs the file: pass --file <path>.");
29177
+ return result("setup-instructions", data);
29178
+ }
29179
+ const existing = await readIfExists(path);
29180
+ let kept = null;
29181
+ if (keepValue !== void 0) {
29182
+ const probe = mergeInstructions(existing);
29183
+ if (probe.status !== "unmarked" || probe.existingSection === null) {
29184
+ throw usageError(`--keep only applies to a file with a hand-written Handout section outside the markers; ${path} has none.`);
29185
+ }
29186
+ kept = parseKeep(keepValue, probe.existingSection.items.length);
29187
+ }
29188
+ const merge2 = mergeInstructions(existing, kept ?? []);
29189
+ if (kept !== null && merge2.proposed !== null && mergeInstructions(merge2.proposed).status !== "current") {
29190
+ throw usageError("--keep would leave a second Handout heading after the end marker (a kept sub-heading that starts with \"Handout\"). Drop that entry, or reword it by hand first.");
29191
+ }
29192
+ const encoder = new TextEncoder();
29193
+ const diff = merge2.proposed === null || merge2.status === "current" ? null : unifiedDiff(encoder.encode(existing ?? ""), encoder.encode(merge2.proposed), existing === null ? "/dev/null" : path, path);
29194
+ const shadow = shadowingFile(agent, path);
29195
+ data = {
29196
+ ...data,
29197
+ status: merge2.status,
29198
+ proposed: merge2.proposed,
29199
+ existingSection: merge2.existingSection,
29200
+ kept,
29201
+ diff,
29202
+ shadowedBy: shadow !== null && await isFile(shadow) ? shadow : null
29203
+ };
29204
+ return result("setup-instructions", data);
29205
+ }
29206
+ var commands13 = {
29207
+ "setup print-instructions": { usage: PRINT_USAGE, run: runPrintInstructions }
29208
+ };
29209
+ var comments_exports = {};
29210
+ __export(comments_exports, {
29211
+ commands: () => commands14,
29212
+ formatComments: () => formatComments
29213
+ });
29214
+ var LIST_USAGE4 = buildUsage({
29215
+ synopsis: ["handout comments list <ref> [--password <secret>]"],
29216
+ description: "Lists the comment threads on a document you can open.",
29217
+ flags: [["--password <secret>", "Document password, if it has one (- reads stdin)"]],
29218
+ examples: ["handout comments list q3-report", "handout comments list acme/q3-report --json"]
29219
+ });
29220
+ var RESOLVE_USAGE = buildUsage({
29221
+ synopsis: ["handout comments resolve <slug> <id>"],
29222
+ examples: ["handout comments resolve q3-report 01j..."]
29223
+ });
29224
+ var UNRESOLVE_USAGE = buildUsage({
29225
+ synopsis: ["handout comments unresolve <slug> <id>"],
29226
+ examples: ["handout comments unresolve q3-report 01j..."]
29227
+ });
29228
+ var DELETE_USAGE4 = buildUsage({
29229
+ synopsis: ["handout comments delete <ref> <id>"],
29230
+ examples: ["handout comments delete q3-report 01j..."]
29231
+ });
29232
+ var author = (comment) => {
29233
+ const who = comment.authorEmail || comment.authorName || "A reader";
29234
+ return `${who}${comment.authorType === "publisher" ? " (publisher)" : ""}`;
29235
+ };
29236
+ function commentBlock(comment, indent) {
29237
+ const resolved = comment.resolvedAt === void 0 ? "" : `[resolved by ${comment.resolvedBy ?? "unknown"}] `;
29238
+ return [
29239
+ `${indent}# ${resolved}${comment.id}`,
29240
+ `${indent}${comment.createdAt} ${author(comment)}`,
29241
+ `${indent} ${comment.deletedAt === void 0 ? comment.body : "[deleted]"}`
29242
+ ];
29243
+ }
29244
+ function formatComments(response) {
29245
+ if (!response.commentsEnabled)
29246
+ return "Commenting is turned off for this document.";
29247
+ if (response.comments.length === 0)
29248
+ return "No comments yet.";
29249
+ return response.comments.map((thread) => {
29250
+ const lines = commentBlock(thread, "");
29251
+ for (const reply of thread.replies)
29252
+ lines.push(...commentBlock(reply, " "));
29253
+ return lines.join("\n");
29254
+ }).join("\n\n");
29255
+ }
29256
+ async function pair(ctx, sub, usage) {
29257
+ const context = `on handout comments ${sub}`;
29258
+ const scanned = scanArgs(ctx.args, { context, usage });
29259
+ expectPositionals(scanned, context, 2);
29260
+ const ref = scanned.positionals[0]?.trim();
29261
+ const id = scanned.positionals[1]?.trim();
29262
+ if (ref === void 0 || ref === "" || id === void 0 || id === "") {
29263
+ throw usageError(`comments ${sub} requires the document and the ${sub === "delete" ? "comment" : "thread"} id (handout comments ${sub} <slug> <id>).`);
29264
+ }
29265
+ return { ...await resolveDocumentRef(ctx, ref), id };
29266
+ }
29267
+ async function runList4(ctx) {
29268
+ const context = "on handout comments list";
29269
+ const scanned = scanArgs(ctx.args, { context, usage: LIST_USAGE4, values: ["--password"] });
29270
+ expectPositionals(scanned, context, 1);
29271
+ const ref = scanned.positionals[0]?.trim();
29272
+ if (ref === void 0 || ref === "") {
29273
+ throw usageError("comments list requires the document (handout comments list <ref>).");
29274
+ }
29275
+ const password = await resolvePasswordInput(lastValue(scanned, "--password"), ctx.passwordDeps);
29276
+ const { handle, slug } = await resolveDocumentRef(ctx, ref);
29277
+ const response = await (await ctx.client()).listComments(handle, slug, { password });
29278
+ return result("comments-list", response);
29279
+ }
29280
+ async function runThread(ctx, resolve3) {
29281
+ const sub = resolve3 ? "resolve" : "unresolve";
29282
+ const { handle, slug, id } = await pair(ctx, sub, resolve3 ? RESOLVE_USAGE : UNRESOLVE_USAGE);
29283
+ const client = await ctx.client();
29284
+ const response = resolve3 ? await client.resolveThread(handle, slug, id) : await client.unresolveThread(handle, slug, id);
29285
+ return result(resolve3 ? "comments-resolve" : "comments-unresolve", { response, slug });
29286
+ }
29287
+ async function runDelete3(ctx) {
29288
+ const { handle, slug, id } = await pair(ctx, "delete", DELETE_USAGE4);
29289
+ const response = await (await ctx.client()).deleteComment(handle, slug, id);
29290
+ return result("comments-delete", { response, slug, id });
29291
+ }
29292
+ registerOutput("comments-list", passthrough(formatComments));
29293
+ registerOutput("comments-resolve", {
29294
+ json: (d) => d.response,
29295
+ text: (d) => `Resolved thread ${d.response.threadId} on ${d.slug}.`
29296
+ });
29297
+ registerOutput("comments-unresolve", {
29298
+ json: (d) => d.response,
29299
+ text: (d) => `Reopened thread ${d.response.threadId} on ${d.slug}.`
29300
+ });
29301
+ registerOutput("comments-delete", {
29302
+ json: (d) => d.response,
29303
+ text: (d) => `Deleted comment ${d.id} on ${d.slug}.`
29304
+ });
29305
+ var commands14 = {
29306
+ "comments list": { usage: LIST_USAGE4, run: runList4 },
29307
+ "comments resolve": { usage: RESOLVE_USAGE, run: (ctx) => runThread(ctx, true) },
29308
+ "comments unresolve": { usage: UNRESOLVE_USAGE, run: (ctx) => runThread(ctx, false) },
29309
+ "comments delete": { usage: DELETE_USAGE4, run: runDelete3 }
29310
+ };
29311
+ var browse_exports = {};
29312
+ __export(browse_exports, {
29313
+ commands: () => commands15,
29314
+ formatBrowse: () => formatBrowse
29315
+ });
29316
+ var USAGE2 = buildUsage({
29317
+ synopsis: [
29318
+ "handout browse [--query <text>] [--exposure <rung>] [--label <name>] [--publisher <handle>]",
29319
+ " [--since <when>] [--collection <slug>] [--cursor <token>]"
29320
+ ],
29321
+ description: "Lists listed documents and collections you can open, most recently updated first (at most 200).",
29322
+ flags: [
29323
+ ["--query <text>", "Search titles and text"],
29324
+ ["--exposure <rung>", "Only this audience"],
29325
+ ["--label <name>", "Only documents with this label"],
29326
+ ["--publisher <handle>", "Only this workspace"],
29327
+ ["--since <when>", "Updated since a date/time or a duration like 7d"],
29328
+ ["--collection <slug>", "Only documents in this collection"],
29329
+ ["--cursor <token>", "Continue from a previous page"]
29330
+ ],
29331
+ examples: ["handout browse --query roadmap", "handout browse --publisher acme --since 7d --json"]
29332
+ });
29333
+ function formatBrowse(response) {
29334
+ if (response.documents.length === 0 && response.collections.length === 0) {
29335
+ return "Nothing to browse \u2014 no documents or collections you can open are listed.";
29336
+ }
29337
+ const lines = [];
29338
+ if (response.documents.length > 0) {
29339
+ lines.push(`Documents (${response.documents.length}):`);
29340
+ for (const doc of response.documents) {
29341
+ lines.push(` ${fields(doc.url, doc.exposure, doc.publisher.handle, doc.title, doc.snippet === void 0 || doc.snippet === "" ? void 0 : doc.snippet)}`);
28392
29342
  }
28393
29343
  }
28394
- const legacyFiles = [];
28395
- for (const name of LEGACY_INSTALL_FILES) {
28396
- if (await exists(join4(folder, name)))
28397
- legacyFiles.push(name);
29344
+ if (response.collections.length > 0) {
29345
+ lines.push(`Collections (${response.collections.length}):`);
29346
+ for (const collection of response.collections) {
29347
+ lines.push(` ${fields(collection.url, collection.exposure, collection.publisher.handle, plural2(collection.itemCount, "item"), collection.name)}`);
29348
+ }
28398
29349
  }
28399
- const data = {
28400
- agent,
28401
- path: target,
28402
- status,
28403
- version: bundledVersion(),
28404
- legacyFiles
28405
- };
28406
- return result("skill-install", data);
29350
+ if (response.nextCursor !== void 0) {
29351
+ lines.push("Showing the first 200 (most-recently-updated). More results \u2014 next page:", ` handout browse --cursor ${response.nextCursor} (repeat the same filters)`);
29352
+ }
29353
+ return lines.join("\n");
28407
29354
  }
28408
- var commands12 = {
28409
- "skill install": { usage: INSTALL_USAGE, run: runSkillInstall }
29355
+ async function runBrowse(ctx) {
29356
+ const context = "on handout browse";
29357
+ const scanned = scanArgs(ctx.args, {
29358
+ context,
29359
+ usage: USAGE2,
29360
+ values: [
29361
+ "--query",
29362
+ "--exposure",
29363
+ "--label",
29364
+ "--publisher",
29365
+ "--since",
29366
+ "--collection",
29367
+ "--cursor"
29368
+ ]
29369
+ });
29370
+ expectPositionals(scanned, context, 0);
29371
+ const exposure = lastValue(scanned, "--exposure");
29372
+ const since = lastValue(scanned, "--since");
29373
+ const collection = lastValue(scanned, "--collection")?.trim();
29374
+ const label = lastValue(scanned, "--label")?.trim();
29375
+ const publisher = lastValue(scanned, "--publisher")?.trim();
29376
+ const query = lastValue(scanned, "--query")?.trim();
29377
+ const cursor = lastValue(scanned, "--cursor");
29378
+ const filters = {
29379
+ q: query === "" ? void 0 : query,
29380
+ exposure: exposure === void 0 ? void 0 : parseExposure(exposure),
29381
+ label: label === "" ? void 0 : label,
29382
+ publisher: publisher === "" ? void 0 : publisher,
29383
+ since: since === void 0 ? void 0 : parseSince(since, ctx.now()),
29384
+ collection: collection === "" ? void 0 : collection,
29385
+ cursor
29386
+ };
29387
+ return result("browse", await (await ctx.client()).browse(filters));
29388
+ }
29389
+ registerOutput("browse", passthrough(formatBrowse));
29390
+ var commands15 = {
29391
+ browse: { usage: USAGE2, run: runBrowse }
28410
29392
  };
28411
29393
  import { realpathSync } from "node:fs";
28412
29394
  import { createInterface } from "node:readline/promises";
28413
29395
  import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
28414
- import { mkdir as mkdir3, readFile as readFile5, rename as rename3, writeFile as writeFile4 } from "node:fs/promises";
28415
- import { dirname as dirname3, join as join5 } from "node:path";
29396
+ import { mkdir as mkdir3, readFile as readFile6, rename as rename3, writeFile as writeFile4 } from "node:fs/promises";
29397
+ import { dirname as dirname4, join as join6 } from "node:path";
28416
29398
  function compareVersions(a, b) {
28417
29399
  const left = parseVersion(a);
28418
29400
  const right = parseVersion(b);
@@ -28442,11 +29424,11 @@ function parseVersion(value) {
28442
29424
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
28443
29425
  var MANIFEST_TIMEOUT_MS = 2000;
28444
29426
  function stampPath(host, env) {
28445
- return join5(configDir(env), `version-check-${hostHash(host)}.json`);
29427
+ return join6(configDir(env), `version-check-${hostHash(host)}.json`);
28446
29428
  }
28447
29429
  async function readStamp(path) {
28448
29430
  try {
28449
- const parsed = JSON.parse(await readFile5(path, "utf8"));
29431
+ const parsed = JSON.parse(await readFile6(path, "utf8"));
28450
29432
  if (typeof parsed !== "object" || parsed === null)
28451
29433
  return void 0;
28452
29434
  const record2 = parsed;
@@ -28466,7 +29448,7 @@ async function readStamp(path) {
28466
29448
  }
28467
29449
  async function writeStamp(path, stamp) {
28468
29450
  try {
28469
- await mkdir3(dirname3(path), { recursive: true, mode: 448 });
29451
+ await mkdir3(dirname4(path), { recursive: true, mode: 448 });
28470
29452
  const tmp = `${path}.${process.pid}.tmp`;
28471
29453
  await writeFile4(tmp, `${JSON.stringify(stamp)}
28472
29454
  `, { mode: 384 });
@@ -28557,7 +29539,12 @@ var COMMAND_TREE = {
28557
29539
  acks: { modules: ["documents", "manage"], summary: "Show who acknowledged a document" },
28558
29540
  list: { modules: ["documents"], summary: "List your documents" },
28559
29541
  get: { modules: ["documents"], summary: "Show a document's details" },
28560
- labels: { modules: ["labels"], summary: "Show the suggested labels and how often each is used" },
29542
+ labels: {
29543
+ modules: ["labels"],
29544
+ summary: "Show and edit the workspace's suggested labels",
29545
+ subcommands: ["list", "add", "remove", "reorder", "seed"],
29546
+ bare: "list"
29547
+ },
28561
29548
  search: { modules: ["documents"], summary: "Search your documents" },
28562
29549
  source: { modules: ["documents"], summary: "Download a document's source" },
28563
29550
  open: { modules: ["documents"], summary: "Print (or open) a document's link" },
@@ -28580,28 +29567,14 @@ var COMMAND_TREE = {
28580
29567
  ],
28581
29568
  bare: "list"
28582
29569
  },
28583
- proposals: {
28584
- modules: ["proposals"],
28585
- summary: "List and decide edit proposals",
28586
- subcommands: ["list", "source", "approve", "reject"],
28587
- deferred: true
28588
- },
28589
- lease: {
28590
- modules: ["proposals", "lease"],
28591
- summary: "Claim or release a document's edit lease",
28592
- subcommands: ["claim", "release"],
28593
- deferred: true
28594
- },
28595
29570
  comments: {
28596
29571
  modules: ["comments"],
28597
29572
  summary: "List and moderate comments",
28598
- subcommands: ["list", "resolve", "unresolve", "delete"],
28599
- deferred: true
29573
+ subcommands: ["list", "resolve", "unresolve", "delete"]
28600
29574
  },
28601
29575
  browse: {
28602
29576
  modules: ["browse"],
28603
- summary: "Browse documents and collections you can open",
28604
- deferred: true
29577
+ summary: "Browse documents and collections you can open"
28605
29578
  },
28606
29579
  workspaces: {
28607
29580
  modules: ["workspaces"],
@@ -28633,9 +29606,14 @@ var COMMAND_TREE = {
28633
29606
  usage: { modules: ["usage"], summary: "Show storage and document usage" },
28634
29607
  skill: {
28635
29608
  modules: ["skill"],
28636
- summary: "Install the Handout skill for an agent",
29609
+ summary: "Install the Handout skills for an agent",
28637
29610
  subcommands: ["install"]
28638
29611
  },
29612
+ setup: {
29613
+ modules: ["setup"],
29614
+ summary: "Print the Handout block for an agent's instructions",
29615
+ subcommands: ["print-instructions"]
29616
+ },
28639
29617
  help: { modules: [], summary: "Show help for a command" }
28640
29618
  };
28641
29619
  function buildGlobalUsage() {
@@ -28649,14 +29627,14 @@ function buildGlobalUsage() {
28649
29627
  for (const [label, description] of rows2)
28650
29628
  lines.push(` ${label.padEnd(width)} ${description}`);
28651
29629
  lines.push("", "Commands:");
28652
- const names = Object.entries(COMMAND_TREE).filter(([, entry]) => entry.deferred !== true);
29630
+ const names = Object.entries(COMMAND_TREE);
28653
29631
  const nameWidth = Math.max(...names.map(([name]) => name.length));
28654
29632
  for (const [name, entry] of names)
28655
29633
  lines.push(` ${name.padEnd(nameWidth)} ${entry.summary}`);
28656
29634
  lines.push("", "Run handout <command> --help for that command's flags.");
28657
29635
  return lines.join("\n");
28658
29636
  }
28659
- var USAGE2 = buildGlobalUsage();
29637
+ var USAGE3 = buildGlobalUsage();
28660
29638
  function defaultDeps() {
28661
29639
  return {
28662
29640
  io: { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin },
@@ -28665,56 +29643,27 @@ function defaultDeps() {
28665
29643
  fetchImpl: fetch
28666
29644
  };
28667
29645
  }
28668
- function isCommandModule(value) {
28669
- return typeof value === "object" && value !== null && "commands" in value && typeof value.commands === "object" && value.commands !== null;
28670
- }
28671
- function isModuleNotFound(err) {
28672
- return typeof err === "object" && err !== null && "code" in err && (err.code === "ERR_MODULE_NOT_FOUND" || err.code === "MODULE_NOT_FOUND");
28673
- }
28674
- async function importModule(name) {
28675
- switch (name) {
28676
- case "publish":
28677
- return Promise.resolve(publish_exports);
28678
- case "manage":
28679
- return Promise.resolve(manage_exports);
28680
- case "documents":
28681
- return Promise.resolve(documents_exports);
28682
- case "versions":
28683
- return Promise.resolve(versions_exports);
28684
- case "collections":
28685
- return Promise.resolve(collections_exports);
28686
- case "workspaces":
28687
- return Promise.resolve(workspaces_exports);
28688
- case "account":
28689
- return Promise.resolve(account_exports);
28690
- case "auth":
28691
- return Promise.resolve(auth_exports);
28692
- case "library":
28693
- return Promise.resolve(library_exports);
28694
- case "labels":
28695
- return Promise.resolve(labels_exports);
28696
- case "usage":
28697
- return Promise.resolve(usage_exports);
28698
- case "skill":
28699
- return Promise.resolve(skill_exports);
28700
- default: {
28701
- const specifier = `./commands/${name}.js`;
28702
- return import(specifier);
28703
- }
28704
- }
28705
- }
29646
+ var MODULES = {
29647
+ publish: publish_exports,
29648
+ manage: manage_exports,
29649
+ documents: documents_exports,
29650
+ versions: versions_exports,
29651
+ collections: collections_exports,
29652
+ workspaces: workspaces_exports,
29653
+ account: account_exports,
29654
+ auth: auth_exports,
29655
+ library: library_exports,
29656
+ labels: labels_exports,
29657
+ usage: usage_exports,
29658
+ skill: skill_exports,
29659
+ setup: setup_exports,
29660
+ comments: comments_exports,
29661
+ browse: browse_exports
29662
+ };
28706
29663
  async function loadCommandModule(name, deps) {
28707
29664
  if (deps.loadModule !== void 0)
28708
29665
  return deps.loadModule(name);
28709
- try {
28710
- const mod = await importModule(name);
28711
- return isCommandModule(mod) ? mod : void 0;
28712
- }
28713
- catch (err) {
28714
- if (isModuleNotFound(err) && errorMessage(err).includes(`commands/${name}`))
28715
- return void 0;
28716
- throw err;
28717
- }
29666
+ return Object.hasOwn(MODULES, name) ? MODULES[name] : void 0;
28718
29667
  }
28719
29668
  function selectCommand(rest) {
28720
29669
  let nameIndex = -1;
@@ -28787,7 +29736,11 @@ function createContext(command, args, global, host, deps) {
28787
29736
  env: deps.env,
28788
29737
  fetchImpl: deps.fetchImpl,
28789
29738
  now: deps.now,
28790
- ...deps.sleep === void 0 ? {} : { sleep: deps.sleep }
29739
+ ...deps.sleep === void 0 ? {} : { sleep: deps.sleep },
29740
+ onNotice: (line) => {
29741
+ deps.io.stderr.write(`${line}
29742
+ `);
29743
+ }
28791
29744
  });
28792
29745
  return connectionPromise;
28793
29746
  };
@@ -28812,15 +29765,11 @@ function createContext(command, args, global, host, deps) {
28812
29765
  connection,
28813
29766
  client,
28814
29767
  workspace: () => {
28815
- workspacePromise ??= (async () => {
28816
- const localDefault = global.workspace === void 0 && deps.env["HANDOUT_WORKSPACE"] === void 0 ? (await localConfig()).defaultWorkspace : void 0;
28817
- return resolveWorkspaceHandle({
28818
- flag: global.workspace,
28819
- env: deps.env,
28820
- localDefault,
28821
- getMe: async () => (await client()).getMe()
28822
- });
28823
- })();
29768
+ workspacePromise ??= resolveWorkspaceHandle({
29769
+ flag: global.workspace,
29770
+ env: deps.env,
29771
+ getMe: async () => (await client()).getMe()
29772
+ });
28824
29773
  return workspacePromise;
28825
29774
  },
28826
29775
  localConfig,
@@ -28890,20 +29839,20 @@ async function findDefinition(key, entry, deps) {
28890
29839
  return void 0;
28891
29840
  }
28892
29841
  async function runCommand(argv, deps = defaultDeps()) {
28893
- const { global, rest } = extractGlobalFlags(argv, USAGE2);
29842
+ const { global, rest } = extractGlobalFlags(argv, USAGE3);
28894
29843
  const selection = selectCommand(rest);
28895
29844
  if (selection.name === void 0) {
28896
29845
  if (global.help) {
28897
- deps.io.stdout.write(textLine(USAGE2));
29846
+ deps.io.stdout.write(textLine(USAGE3));
28898
29847
  return;
28899
29848
  }
28900
- throw usageError(USAGE2);
29849
+ throw usageError(USAGE3);
28901
29850
  }
28902
29851
  if (selection.name === "help") {
28903
29852
  const topics = selection.remaining.filter((t) => !isUnknownFlagToken(t));
28904
29853
  const target = topics.length === 0 ? [] : [...topics, "--help"];
28905
29854
  if (target.length === 0) {
28906
- deps.io.stdout.write(textLine(USAGE2));
29855
+ deps.io.stdout.write(textLine(USAGE3));
28907
29856
  return;
28908
29857
  }
28909
29858
  await runCommand([...target, ...rest.filter((t) => isUnknownFlagToken(t))], deps);
@@ -28935,9 +29884,6 @@ async function runCommand(argv, deps = defaultDeps()) {
28935
29884
  }
28936
29885
  const definition = await findDefinition(key, entry, deps);
28937
29886
  if (definition === void 0) {
28938
- if (entry.deferred === true) {
28939
- throw usageError(`Unknown command "${selection.name}". Run handout --help for the list of commands.`);
28940
- }
28941
29887
  throw usageError(`The command "${key}" is not available in this build of handout.`);
28942
29888
  }
28943
29889
  if (global.help) {
@@ -28961,8 +29907,7 @@ async function runCommand(argv, deps = defaultDeps()) {
28961
29907
  function printLintWarnings2(ctx, warnings, prefix) {
28962
29908
  if (ctx.json || warnings === void 0 || warnings.length === 0)
28963
29909
  return;
28964
- const only = warnings.length === 1 ? warnings[0] : void 0;
28965
- const header = only?.code === "interactive-unsanitized" ? "Published (interactive):" : "Published, but this HTML may render degraded in the reader:";
29910
+ const header = lintHeader(warnings);
28966
29911
  const lines = warnings.map((w) => ` - ${w.message}`);
28967
29912
  if (prefix !== void 0)
28968
29913
  ctx.warn(`${prefix}:`, header, ...lines);
@@ -28995,7 +29940,7 @@ async function execute(argv, deps = defaultDeps()) {
28995
29940
  let exitCode = 0;
28996
29941
  resetShapeMismatch();
28997
29942
  try {
28998
- const { global, rest } = extractGlobalFlags(argv, USAGE2);
29943
+ const { global, rest } = extractGlobalFlags(argv, USAGE3);
28999
29944
  json2 = global.json;
29000
29945
  quiet = global.quiet;
29001
29946
  noColor = global.noColor;
@@ -29006,7 +29951,7 @@ async function execute(argv, deps = defaultDeps()) {
29006
29951
  }
29007
29952
  const selection = selectCommand(rest);
29008
29953
  const knownCommand = selection.name !== void 0 && Object.hasOwn(COMMAND_TREE, selection.name);
29009
- const offline = global.help || !knownCommand || selection.name === "help" || selection.name === "skill";
29954
+ const offline = global.help || !knownCommand || selection.name === "help" || selection.name === "skill" || selection.name === "setup";
29010
29955
  let host = deps.host;
29011
29956
  if (!offline) {
29012
29957
  if (host === void 0) {
@@ -29091,4 +30036,4 @@ var isMain = isMainModule(process.argv[1], import.meta.url);
29091
30036
  if (isMain) {
29092
30037
  void main();
29093
30038
  }
29094
- export { CLI_NAME, COMMAND_OUTPUT, COMMAND_TREE, USAGE2 as USAGE, defaultDeps, execute, isMainModule, main, printLintWarnings2 as printLintWarnings, runCommand };
30039
+ export { CLI_NAME, COMMAND_OUTPUT, COMMAND_TREE, USAGE3 as USAGE, defaultDeps, execute, isMainModule, main, printLintWarnings2 as printLintWarnings, runCommand };