saturndocs 0.2.0 → 0.4.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.
Files changed (64) hide show
  1. package/dist/auth-NKYU6ZSC.js +16 -0
  2. package/dist/{chunk-QF2ADHQZ.js → chunk-22WNRYB7.js} +17 -19
  3. package/dist/{chunk-2RZEC3VH.js → chunk-2GBM6W4I.js} +102 -34
  4. package/dist/{chunk-4ORVQCHY.js → chunk-3JUP4HIA.js} +34 -9
  5. package/dist/chunk-4B6PUKF5.js +915 -0
  6. package/dist/{chunk-GGGL4O7Z.js → chunk-6JJEMNSP.js} +8 -7
  7. package/dist/{chunk-Z5CBPJ2L.js → chunk-BB32XQJB.js} +9 -5
  8. package/dist/chunk-BRC7CU3J.js +427 -0
  9. package/dist/{chunk-ADZOBRZE.js → chunk-EH6E45H4.js} +805 -146
  10. package/dist/{chunk-DBMFJXKP.js → chunk-GLB47CSE.js} +5 -5
  11. package/dist/{chunk-EB7RWFQA.js → chunk-HHRZ3Y55.js} +1594 -140
  12. package/dist/{chunk-2YTD2XNI.js → chunk-HJ7HRIAT.js} +1 -1
  13. package/dist/{chunk-WBI4EI3D.js → chunk-KEZAO7P5.js} +2 -2
  14. package/dist/chunk-KWEWL4MJ.js +53 -0
  15. package/dist/{chunk-W3GKH5DY.js → chunk-N66SXAI5.js} +19 -11
  16. package/dist/chunk-QF5ELRAU.js +421 -0
  17. package/dist/{chunk-WUPP3THV.js → chunk-QMA7433F.js} +5 -5
  18. package/dist/{chunk-YSFP37B7.js → chunk-TRQCW5CZ.js} +20 -6
  19. package/dist/{chunk-6JGAA5TF.js → chunk-UXCORL5H.js} +4 -4
  20. package/dist/{chunk-56U46JVN.js → chunk-YGVC4N4V.js} +2 -1
  21. package/dist/chunk-ZHYL7FYA.js +1537 -0
  22. package/dist/chunk-ZXJ3Z3PR.js +115 -0
  23. package/dist/cli.js +6 -6
  24. package/dist/{coverage-EBWULNQQ.js → coverage-IUQLC2H6.js} +5 -5
  25. package/dist/{dist-XISZDQTR.js → dist-LZ5BC7HG.js} +38 -3
  26. package/dist/index.d.ts +69 -37
  27. package/dist/index.js +111 -47
  28. package/dist/{init-PI4VTG7V.js → init-EFZZRZZM.js} +4 -3
  29. package/dist/{lint-SXBP37G3.js → lint-N7ENEJVU.js} +3 -3
  30. package/dist/login-34OM3PJ2.js +22 -0
  31. package/dist/{manage-OB6DQK3Q.js → manage-2AOOCZE2.js} +6 -2
  32. package/dist/{nav-R4OORY2G.js → nav-DKCGLENP.js} +4 -4
  33. package/dist/openapiCheck-KEHPUZOD.js +103 -0
  34. package/dist/pages-E73CUM6I.js +16 -0
  35. package/dist/{read-WWOMA67R.js → read-TQSSS7EJ.js} +60 -12
  36. package/dist/{read-VECMKHBW.js → read-UGXFNEGJ.js} +11 -9
  37. package/dist/requests-OLCBRUAW.js +13 -0
  38. package/dist/{schema-NKOXZHQH.js → schema-3I6XJSCY.js} +3 -3
  39. package/dist/{sites-XMMGWPY2.js → sites-6HKU6JP7.js} +5 -4
  40. package/dist/{status-SYIUUSSU.js → status-DFAYOCC4.js} +4 -4
  41. package/dist/{suggestions-GX5CQK26.js → suggestions-JSTWOWRY.js} +35 -20
  42. package/dist/unavailable-HVN65Q7D.js +40 -0
  43. package/dist/validate-6RIKQWMI.js +11 -0
  44. package/package.json +14 -8
  45. package/dist/auth-DUYYFNEZ.js +0 -14
  46. package/dist/brokenLinks-E364XYH3.js +0 -48
  47. package/dist/build-F5PWGP57.js +0 -39
  48. package/dist/chunk-4J33CCAC.js +0 -49
  49. package/dist/chunk-D3CLXV7D.js +0 -131
  50. package/dist/chunk-FGKHDJOC.js +0 -697
  51. package/dist/chunk-GLI3OUYL.js +0 -637
  52. package/dist/chunk-K5YY6NSF.js +0 -71
  53. package/dist/chunk-KOJJUISB.js +0 -39
  54. package/dist/chunk-O72DR5FK.js +0 -152
  55. package/dist/chunk-SVDVBZPA.js +0 -588
  56. package/dist/chunk-VNYDYHXM.js +0 -22
  57. package/dist/chunk-VXEUNRVA.js +0 -26
  58. package/dist/chunk-WHNL6UYJ.js +0 -57
  59. package/dist/deploy-QUVLOGII.js +0 -13
  60. package/dist/dev-VDSDCBO2.js +0 -43
  61. package/dist/openapiCheck-X2QQGETY.js +0 -66
  62. package/dist/pages-MKFZAVGI.js +0 -15
  63. package/dist/requests-A7WC3B4M.js +0 -13
  64. package/dist/validate-D4I3DY2W.js +0 -32
@@ -4,6 +4,7 @@ import { z as z22 } from "zod";
4
4
  import { z as z32 } from "zod";
5
5
 
6
6
  // ../owner-contract/dist/index.js
7
+ import { z } from "zod";
7
8
  import { z as z2 } from "zod";
8
9
 
9
10
  // ../control-abi/dist/index.js
@@ -30,10 +31,10 @@ var DEFAULT_SKIP_LABELS = Object.freeze(["no-docs", "skip-docs"]);
30
31
  var DEFAULT_IGNORE_GLOBS = Object.freeze(["**/*.test.*", "**/__tests__/**", "**/*.lock", "**/node_modules/**", ".github/**"]);
31
32
  var DEFAULT_SKIP_AUTHORS = Object.freeze(["*[bot]"]);
32
33
  var ENFORCEMENT = Object.freeze({ ownership: "d1_transaction", heads: "d1_transaction", hostname: "d1_transaction", gitConnections: "d1_transaction", webhookDeliveries: "d1_transaction", tombstone: "d1_transaction", jobRelations: "d1_transaction", records: "d1_transaction", sourceBlobs: "r2_ordering", releaseObjects: "r2_ordering" });
34
+ var PR_PREVIEW_IDLE_MS = 30 * 24 * 60 * 60 * 1e3;
33
35
 
34
36
  // ../owner-contract/dist/index.js
35
- import { z } from "zod";
36
- var MANAGEMENT_SCOPES = ["manage:read", "manage:write", "manage:approve", "manage:access"];
37
+ var MANAGEMENT_SCOPES = ["manage:read", "manage:write", "manage:approve", "manage:access", "rollback"];
37
38
  var ManagementCredential = z.object({
38
39
  token_id: z.string(),
39
40
  site_id: z.string(),
@@ -49,7 +50,7 @@ var ManagementCredential = z.object({
49
50
  var ManagementCredentials = z.object({ site_id: z.string(), credentials: z.array(ManagementCredential) });
50
51
  var CreateManagementCredential = z.object({
51
52
  label: z.string().trim().min(1).max(80),
52
- scopes: z.array(z.enum(MANAGEMENT_SCOPES)).min(1).max(4).refine((scopes) => new Set(scopes).size === scopes.length, "Permissions must be unique"),
53
+ scopes: z.array(z.enum(MANAGEMENT_SCOPES)).min(1).max(MANAGEMENT_SCOPES.length).refine((scopes) => new Set(scopes).size === scopes.length, "Permissions must be unique"),
53
54
  expires_at: z.iso.datetime()
54
55
  }).strict();
55
56
  var IssuedManagementCredential = z.object({ credential: ManagementCredential, token: z.string() });
@@ -57,9 +58,21 @@ var OWNER_PREFIX = "/__gs-portal";
57
58
  var MAX_SESSION_EVIDENCE = 20;
58
59
  var OWNER_PATHS = {
59
60
  login: `${OWNER_PREFIX}/login`,
60
- magicRequest: `${OWNER_PREFIX}/magic/request`,
61
- magicVerify: `${OWNER_PREFIX}/magic/verify`,
61
+ start: `${OWNER_PREFIX}/start`,
62
62
  logout: `${OWNER_PREFIX}/logout`,
63
+ account: `${OWNER_PREFIX}/account`,
64
+ accountRequirePasskey: `${OWNER_PREFIX}/account/require-passkey`,
65
+ accountSignOutEverywhere: `${OWNER_PREFIX}/account/sign-out-everywhere`,
66
+ accountSession: (id) => OWNER_PREFIX + "/account/sessions/" + encodeURIComponent(id),
67
+ accountPasskey: (id) => `${OWNER_PREFIX}/account/passkeys/${encodeURIComponent(id)}`,
68
+ passkeyRegisterOptions: `${OWNER_PREFIX}/auth/passkey/generate-register-options`,
69
+ passkeyRegister: `${OWNER_PREFIX}/auth/passkey/verify-registration`,
70
+ organization: `${OWNER_PREFIX}/organization`,
71
+ organizationLeave: `${OWNER_PREFIX}/organization/leave`,
72
+ audit: `${OWNER_PREFIX}/audit`,
73
+ billing: `${OWNER_PREFIX}/billing`,
74
+ billingCheckout: `${OWNER_PREFIX}/billing/checkout`,
75
+ billingPortal: `${OWNER_PREFIX}/billing/portal`,
63
76
  switch: `${OWNER_PREFIX}/switch`,
64
77
  site: `${OWNER_PREFIX}/site`,
65
78
  sites: `${OWNER_PREFIX}/sites`,
@@ -78,6 +91,7 @@ var OWNER_PATHS = {
78
91
  gaps: `${OWNER_PREFIX}/gaps`,
79
92
  gapWork: `${OWNER_PREFIX}/gaps/work`,
80
93
  pages: `${OWNER_PREFIX}/pages`,
94
+ releaseRollback: `${OWNER_PREFIX}/releases/rollback`,
81
95
  releases: `${OWNER_PREFIX}/releases`,
82
96
  metrics: `${OWNER_PREFIX}/metrics`,
83
97
  domains: `${OWNER_PREFIX}/domains`,
@@ -88,6 +102,7 @@ var OWNER_PATHS = {
88
102
  buildRetry: `${OWNER_PREFIX}/builds/retry`,
89
103
  build: `${OWNER_PREFIX}/builds`,
90
104
  notifications: `${OWNER_PREFIX}/notifications`,
105
+ previews: `${OWNER_PREFIX}/previews`,
91
106
  owners: `${OWNER_PREFIX}/owners`,
92
107
  owner: (email) => `${OWNER_PREFIX}/owners/${encodeURIComponent(email)}`,
93
108
  settingsProposal: `${OWNER_PREFIX}/settings/proposal`,
@@ -171,8 +186,8 @@ var TRIGGER_MODES = ["off", "manual", "daily", "weekly", "push"];
171
186
  var CONNECTION_STATES = ["active", "paused", "broken"];
172
187
  var CONNECTION_BROKEN_REASONS = ["uninstalled", "repository_transferred", "branch_deleted"];
173
188
  var INSTALLATION_HEALTH = ["healthy", "stale", "broken"];
174
- var SKIP_REASONS = ["no_matching_connection", "branch_mismatch", "connection_paused", "connection_broken", "no_watched_paths", "deleted_ref", "bot_author", "skip_label", "invalid_sha", "suggestions_off", "manual_only", "scheduled"];
175
- var ACTIVITY_OPERATIONS = ["product_push", "manual_request", "git_push", "rebuild", "bundle_upload"];
189
+ var ROLLBACK_ACTIVITY_ACCEPT = "application/json; activity=rollback";
190
+ var ACTIVITY_OPERATIONS = ["product_push", "manual_request", "git_push", "rebuild", "bundle_upload", "rollback"];
176
191
  var CONFIDENCES = ["high", "medium", "low"];
177
192
  var TRIAGES = ["user_facing", "internal", "unclear"];
178
193
  var PAGE_CHANGE_OPS = ["create", "update", "delete"];
@@ -278,13 +293,19 @@ var PortalSite = z2.object({
278
293
  latest_job: LatestJob.nullable(),
279
294
  latest_authoring_job: LatestAuthoringJob.nullable().optional(),
280
295
  reader_status: z2.enum(["published", "unpublished", "unknown"]).optional(),
296
+ repo_watcher: z2.boolean().optional(),
281
297
  connections: z2.array(ProductConnection),
282
298
  docs_repo: DocsRepo.nullable(),
283
299
  installations: z2.array(Installation).optional(),
284
300
  slack: SlackConnection.nullable().optional(),
285
301
  usage: PortalUsage.optional()
286
302
  });
287
- var SiteSummary = z2.object({ site_id: z2.string(), primary_host: z2.string().nullable() });
303
+ var SiteSummary = z2.object({
304
+ site_id: z2.string(),
305
+ primary_host: z2.string().nullable(),
306
+ organization_id: z2.string().nullable().optional(),
307
+ organization_name: z2.string().nullable().optional()
308
+ });
288
309
  var SitesResponse = z2.object({ current: z2.string(), sites: z2.array(SiteSummary) });
289
310
  var RationaleEntry = z2.object({ change: z2.string(), affects: z2.array(z2.string()) });
290
311
  var PreviewBlock = z2.object({
@@ -413,6 +434,38 @@ var SuggestionRecord = z2.object({
413
434
  provenance: Provenance.nullable().optional(),
414
435
  merge_mode: z2.enum(MERGE_MODES).nullable().optional()
415
436
  });
437
+ var SuggestionInboxRecord = SuggestionRecord.pick({
438
+ suggestion_id: true,
439
+ pr_number: true,
440
+ head_branch: true,
441
+ base_sha: true,
442
+ state: true,
443
+ title: true,
444
+ repository_id: true,
445
+ commit_sha: true,
446
+ source_pr_number: true,
447
+ request: true,
448
+ requested_by: true,
449
+ pages_count: true,
450
+ first_path: true,
451
+ confidence: true,
452
+ revision: true,
453
+ job_id: true,
454
+ error_code: true,
455
+ error_message: true,
456
+ dismiss_reason: true,
457
+ created_at: true,
458
+ updated_at: true
459
+ });
460
+ var SuggestionDetailRecord = SuggestionRecord.omit({
461
+ pages_count: true,
462
+ first_path: true,
463
+ repository: true,
464
+ error_code: true,
465
+ error_message: true,
466
+ references: true,
467
+ revisions: true
468
+ }).extend({ session_budget: z2.object({ spent: z2.number(), ceiling: z2.number() }) });
416
469
  var SuggestionCounts = z2.object({
417
470
  pending: z2.number().int(),
418
471
  revising: z2.number().int(),
@@ -445,7 +498,9 @@ var RequestChangesBody = z2.object({ note: z2.string().min(1).max(MAX_REQUEST_CH
445
498
  var RetryBody = z2.object({});
446
499
  var SessionMessageBody = z2.object({
447
500
  message: z2.string().min(1).max(MAX_SESSION_MESSAGE_CHARS),
448
- question_id: z2.string().min(1).max(MAX_QUESTION_ID_CHARS).optional()
501
+ question_id: z2.string().min(1).max(MAX_QUESTION_ID_CHARS).optional(),
502
+ /** The session object's dedup key: a replay with the same id and message gets the first turn's result, not a second turn. */
503
+ turn_id: z2.string().uuid().optional()
449
504
  });
450
505
  var SessionResponse = z2.object({
451
506
  answer: z2.string().min(1).max(2e3),
@@ -478,7 +533,7 @@ var ActivityEvent = z2.object({
478
533
  pr_number: z2.number().int().nullable(),
479
534
  triage: z2.enum(TRIAGES).nullable().optional(),
480
535
  pages_considered: nullableString.optional(),
481
- skip_reason: z2.enum(SKIP_REASONS).nullable().optional(),
536
+ skip_reason: z2.string().nullable().optional(),
482
537
  reason: nullableString.optional(),
483
538
  release: ActivityRelease.nullable().optional(),
484
539
  pusher: nullableString.optional(),
@@ -596,7 +651,48 @@ var ReleaseRecord = z2.object({
596
651
  generation: z2.number().int().nullable(),
597
652
  job: z2.object({ job_id: z2.string(), operation: nullableString, commit_sha: nullableString, requested_by: nullableString })
598
653
  });
654
+ var rollbackReleaseId = z2.string().min(1).max(200).regex(/^[^/\\\s\u0000]+$/u).refine((id) => id !== "." && id !== "..");
655
+ var ReleaseRollbackBody = z2.strictObject({
656
+ release_id: rollbackReleaseId,
657
+ expected_active_release_id: rollbackReleaseId,
658
+ expected_generation: z2.number().int().nonnegative()
659
+ });
660
+ var ReleaseRollbackResponse = z2.object({
661
+ site_id: z2.string(),
662
+ active_release_id: z2.string(),
663
+ previous_release_id: z2.string(),
664
+ generation: z2.number().int().positive(),
665
+ security_epoch: z2.number().int().nonnegative(),
666
+ message: z2.string()
667
+ });
668
+ function rollbackProofMatches(site, body, proof) {
669
+ return proof.site_id === site && proof.active_release_id === body.release_id && proof.previous_release_id === body.expected_active_release_id && proof.generation === body.expected_generation + 1;
670
+ }
671
+ var SUPERSEDED_ROLLBACK = "rollback_applied_then_superseded";
672
+ var SupersededRollbackReceipt = z2.object({
673
+ error: z2.literal(SUPERSEDED_ROLLBACK),
674
+ site_id: z2.string().min(1),
675
+ release_id: rollbackReleaseId,
676
+ previous_release_id: rollbackReleaseId,
677
+ applied_generation: z2.number().int().positive(),
678
+ active_release_id: rollbackReleaseId,
679
+ generation: z2.number().int().positive()
680
+ });
681
+ function matchSupersededRollback(site, body, value) {
682
+ const parsed = SupersededRollbackReceipt.safeParse(value);
683
+ if (!parsed.success) return null;
684
+ const receipt = parsed.data;
685
+ return receipt.site_id === site && receipt.release_id === body.release_id && receipt.previous_release_id === body.expected_active_release_id && receipt.applied_generation === body.expected_generation + 1 && receipt.generation > receipt.applied_generation ? receipt : null;
686
+ }
687
+ function describeSupersededRollback(receipt) {
688
+ return `Rollback to ${receipt.release_id} was applied at generation ${receipt.applied_generation} and later superseded by ${receipt.active_release_id} at generation ${receipt.generation}.`;
689
+ }
690
+ var ROLLBACK_RECOVERY = "The rollback may already have been applied. Check the active release and generation. To reconcile, repeat the original rollback with the same site, target, expected active release, and generation.";
691
+ function uncertainRollbackRefusal(status, code) {
692
+ return code === "rollback_superseded" || (status ?? 0) >= 500 && code !== "limit_unavailable";
693
+ }
599
694
  var ReleasesPage = z2.object({
695
+ active_generation: z2.number().int().nullable().optional(),
600
696
  site_id: z2.string(),
601
697
  active_release_id: nullableString,
602
698
  active_release_status: z2.enum(["known", "unknown"]).optional(),
@@ -727,16 +823,101 @@ var NotificationPut = z2.object({
727
823
  event: z2.enum(OWNER_NOTIFICATION_EVENTS),
728
824
  mode: z2.enum(OWNER_NOTIFICATION_MODES)
729
825
  });
730
- var OwnerRow = z2.object({ email: z2.string(), role: OwnerRole.optional(), added_at: isoString, you: z2.boolean() });
731
- var OwnersResponse = z2.object({ site_id: z2.string(), owners: z2.array(OwnerRow) });
732
- var OwnerResponse = z2.object({ owner: OwnerRow });
733
- var AddOwnerBody = z2.object({ email: z2.string().min(3).max(320), role: OwnerRole.optional() });
734
- var OwnerRoleBody = z2.object({ role: OwnerRole });
826
+ var PreviewSettings = z2.object({ pr_previews: z2.boolean() });
827
+ var ORGANIZATION_ROLES = ["owner", "admin", "editor", "viewer"];
828
+ var OrganizationRole = z2.enum(ORGANIZATION_ROLES);
829
+ var OrganizationSummary = z2.object({ id: z2.string(), name: z2.string() });
830
+ var OwnerRow = z2.object({ member_id: z2.string().optional(), email: z2.string(), role: OrganizationRole.optional(), added_at: isoString, you: z2.boolean() });
831
+ var OwnersResponse = z2.object({ site_id: z2.string(), organization: OrganizationSummary.optional(), owners: z2.array(OwnerRow) });
832
+ var OwnerResponse = z2.object({ owner: OwnerRow, organization: OrganizationSummary.optional() });
833
+ var AddOwnerBody = z2.object({ email: z2.string().min(3).max(320), role: OrganizationRole.optional() });
834
+ var OwnerRoleBody = z2.object({ role: OrganizationRole, member_id: z2.string().min(1) });
835
+ var OrganizationResponse = z2.object({
836
+ id: z2.string(),
837
+ name: z2.string(),
838
+ role: OrganizationRole.nullable(),
839
+ sites: z2.array(z2.object({ site_id: z2.string(), primary_host: z2.string().nullable() })),
840
+ can_leave: z2.boolean().optional(),
841
+ member_count: z2.number().int().nonnegative()
842
+ });
843
+ var OrganizationLeaveResponse = z2.object({ left: z2.string() });
844
+ var AuditResponse = z2.object({
845
+ entries: z2.array(z2.object({
846
+ id: z2.number().int(),
847
+ organization_id: z2.string(),
848
+ site_id: z2.string(),
849
+ actor: z2.string().nullable(),
850
+ op: z2.string(),
851
+ outcome: z2.string(),
852
+ subject: z2.string().nullable(),
853
+ created_at: z2.string(),
854
+ detail: z2.record(z2.string(), z2.union([z2.string(), z2.number(), z2.boolean(), z2.null()]))
855
+ })),
856
+ next_cursor: z2.string().nullable()
857
+ });
858
+ var OrganizationRenameBody = z2.object({ name: z2.string().min(1).max(80) });
859
+ var AccountPasskey = z2.object({
860
+ id: z2.string(),
861
+ name: z2.string().nullable(),
862
+ device_type: z2.string(),
863
+ backed_up: z2.boolean(),
864
+ created_at: z2.string().nullable()
865
+ });
866
+ var AccountResponse = z2.object({
867
+ id: z2.string(),
868
+ email: z2.string(),
869
+ signed_in_with: z2.enum(["email-otp", "passkey"]),
870
+ sessions: z2.array(z2.object({
871
+ id: z2.string(),
872
+ device: z2.string(),
873
+ host: z2.string().nullable(),
874
+ signed_in: z2.string(),
875
+ last_active: z2.string(),
876
+ method: z2.string().nullable(),
877
+ current: z2.boolean()
878
+ })),
879
+ require_passkey: z2.boolean(),
880
+ passkeys: z2.array(AccountPasskey),
881
+ organizations: z2.array(OrganizationSummary.extend({ role: OrganizationRole }))
882
+ });
883
+ var AccountActionResponse = z2.object({ ok: z2.literal(true) });
884
+ var AccountLastOwnerResponse = z2.object({ error: z2.literal("last_owner"), organizations: z2.array(OrganizationSummary) });
885
+ var RequirePasskeyBody = z2.object({ enabled: z2.boolean() });
886
+ var SignOutEverywhereResponse = z2.object({ signed_out: z2.number().int().nonnegative() });
887
+ var BILLING_PLANS = ["none", "standard", "enterprise", "complimentary"];
888
+ var BillingPlan = z2.enum(BILLING_PLANS);
889
+ var BILLING_STATUSES = ["none", "trialing", "active", "past_due", "unpaid", "canceled", "incomplete", "incomplete_expired", "paused"];
890
+ var BillingStatus = z2.enum(BILLING_STATUSES);
891
+ var BillingResponse = z2.object({
892
+ organization: OrganizationSummary,
893
+ plan: BillingPlan,
894
+ offer: z2.literal("early_adopter").nullable().default(null),
895
+ offer_price_cents: z2.number().int().nonnegative().nullable().default(null),
896
+ offer_started_at: z2.string().nullable().default(null),
897
+ offer_locked_until: z2.string().nullable().default(null),
898
+ status: BillingStatus,
899
+ paid: z2.boolean(),
900
+ previewing: z2.boolean(),
901
+ in_grace: z2.boolean(),
902
+ current_period_end: z2.string().nullable(),
903
+ cancel_at_period_end: z2.boolean(),
904
+ site_limit: z2.number().int().nonnegative().nullable(),
905
+ sites_used: z2.number().int().nonnegative(),
906
+ entitlements: z2.object({ custom_domain: z2.boolean(), agent_updates: z2.boolean() }),
907
+ enforced: z2.boolean(),
908
+ checkout_available: z2.boolean(),
909
+ has_customer: z2.boolean(),
910
+ can_subscribe: z2.boolean(),
911
+ portal_available: z2.boolean(),
912
+ reconcile_pending: z2.boolean(),
913
+ can_manage: z2.boolean()
914
+ });
915
+ var BillingRedirect = z2.object({ url: z2.url() });
735
916
  var RemoveOwnerResponse = z2.object({ removed: z2.string(), signed_out: z2.boolean() });
736
917
  var PendingSettingsPr = z2.object({ pr_number: z2.number().int(), html_url: z2.string() });
737
918
  var LogoValue = z2.union([z2.string(), z2.object({ light: z2.string().optional(), dark: z2.string().optional() })]);
738
919
  var RedirectEntry = z2.object({ source: z2.string(), destination: z2.string(), permanent: z2.boolean().optional() });
739
- var MAX_REDIRECTS = 500;
920
+ var MAX_REDIRECTS = 5e3;
740
921
  var SettingsValues = z2.object({
741
922
  name: nullableString.optional(),
742
923
  colors: z2.object({ primary: nullableString }).optional(),
@@ -818,14 +999,15 @@ var DocsRepoConnectBody = z2.object({
818
999
  });
819
1000
  var DocsRepoInspectBody = DocsRepoConnectBody.omit({ first_build: true });
820
1001
  var BootstrapPr = z2.object({ pr_number: z2.number().int(), html_url: z2.string() });
821
- var DocsRepoScaffoldBody = DocsRepoConnectBody.omit({ first_build: true }).extend({ mode: z2.enum(["starter", "convert"]) });
822
- var DocsRepoScaffoldSummary = z2.object({ pages: z2.number().int(), starter_added: z2.boolean(), unconverted: z2.number().int() });
1002
+ var DocsRepoScaffoldBody = DocsRepoConnectBody.omit({ first_build: true }).extend({ mode: z2.enum(["starter", "convert"]), source_mode: z2.enum(["folder", "root_copy"]).optional() });
1003
+ var DocsRepoScaffoldSummary = z2.object({ pages: z2.number().int(), starter_added: z2.boolean(), unconverted: z2.number().int(), copied: z2.boolean().optional() });
823
1004
  var DocsRepoScaffoldResponse = z2.object({ docs_repo: DocsRepo, pending: BootstrapPr, summary: DocsRepoScaffoldSummary.nullable().optional() });
824
1005
  var DocsRepoBootstrapStatus = z2.object({
825
1006
  pending: BootstrapPr.nullable(),
826
1007
  state: z2.enum(["none", "open", "merged", "closed"]),
827
1008
  pull: BootstrapPr.nullable(),
828
- docs_json: z2.boolean().nullable()
1009
+ docs_json: z2.boolean().nullable(),
1010
+ source_mode: z2.enum(["root_copy", "folder"]).optional()
829
1011
  });
830
1012
  var DocsRepoSourceBlocked = z2.object({
831
1013
  error: z2.literal("source_blocked"),
@@ -838,7 +1020,7 @@ var DocsRepoSourceBlocked = z2.object({
838
1020
  var DocsCounts = z2.object({ pages: z2.number().int(), assets: z2.number().int(), unconverted: z2.number().int(), total: z2.number().int() });
839
1021
  var DocsPlatform = z2.enum(["mintlify", "docusaurus", "mkdocs", "docsify", "mdbook", "sphinx", "gitbook", "jekyll", "antora"]).nullable();
840
1022
  var DocsInspection = z2.discriminatedUnion("verdict", [
841
- z2.object({ verdict: z2.enum(["saturndocs", "incompatible", "empty"]), platform: DocsPlatform, counts: DocsCounts, structure_violations: z2.number().int() }),
1023
+ z2.object({ verdict: z2.enum(["saturndocs", "incompatible", "empty"]), platform: DocsPlatform, counts: DocsCounts, structure_violations: z2.number().int(), site_folder: z2.string().optional() }),
842
1024
  z2.object({ verdict: z2.literal("unknown"), reason: z2.enum(["token_refused", "branch_missing", "tree_truncated", "github_error"]) })
843
1025
  ]);
844
1026
  var ProductConnectionsResponse = z2.object({ site_id: z2.string().optional(), product_connections: z2.array(ProductConnectionRules) });
@@ -931,10 +1113,147 @@ var ApproveOutcome = OperationFailure.extend({
931
1113
  });
932
1114
  var DismissOutcome = OperationFailure.extend({ state: z2.literal("dismissed").optional(), pr_number: z2.number().int().nullable().optional(), pull_request_closed: z2.boolean().optional() });
933
1115
  var RequestChangesOutcome = OperationFailure.extend({ state: z2.literal("revising").optional(), pr_number: z2.number().int().nullable().optional(), revision: z2.number().int().optional(), already_requested: z2.boolean().optional() });
1116
+ var RetryOutcome = ApproveOutcome;
1117
+ function isGitHubRepository(value) {
1118
+ const [owner, repo, ...extra] = value.split("/");
1119
+ return extra.length === 0 && !!owner && owner.length <= 39 && /^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*(?:_[A-Za-z0-9]{3,8})?$/u.test(owner) && !!repo && repo !== "." && repo !== ".." && /^[A-Za-z0-9._-]{1,100}$/u.test(repo);
1120
+ }
1121
+ var Grant = (() => {
1122
+ const suggestion = SuggestionRecord.pick({
1123
+ suggestion_id: true,
1124
+ title: true,
1125
+ state: true,
1126
+ revision: true,
1127
+ base_sha: true,
1128
+ head_sha: true,
1129
+ commit_sha: true,
1130
+ created_at: true,
1131
+ updated_at: true,
1132
+ merge_mode: true,
1133
+ requested_by: true,
1134
+ reviewer: true,
1135
+ head_edited_by: true
1136
+ });
1137
+ const suggestions = SuggestionsPage.pick({ site_id: true, state: true, next_cursor: true }).extend({ suggestions: z2.array(suggestion) });
1138
+ const detail = z2.object({ site_id: z2.string(), suggestion });
1139
+ const request = RequestRecord.pick({
1140
+ job_id: true,
1141
+ request: true,
1142
+ requested_by: true,
1143
+ state: true,
1144
+ attempt: true,
1145
+ thread_id: true,
1146
+ suggestion_id: true,
1147
+ created_at: true,
1148
+ updated_at: true
1149
+ });
1150
+ const entries = z2.array(RequestThreadEntry.pick({ job_id: true, seq: true, author: true, kind: true, body: true, created_at: true }));
1151
+ const thread = RequestThread.pick({ site_id: true, thread_id: true, open: true }).extend({ root: request, latest_job: request, entries });
1152
+ const flat = z2.object({ site_id: z2.string(), requests: z2.array(request), next_cursor: z2.string().nullable() });
1153
+ const grouped = RequestsPage.pick({ site_id: true, page_cursor: true, next_cursor: true, has_newer: true }).extend({
1154
+ threads: z2.array(RequestThreadSummary.pick({ thread_id: true, open: true, turns: true }).extend({ root: request, latest: request, entries }))
1155
+ });
1156
+ const site = PortalSite.pick({ site_id: true, reader_status: true }).extend({
1157
+ docs_repo: DocsRepo.pick({ repository: true, branch: true, docs_root: true, state: true }).nullable(),
1158
+ active_release: ActiveRelease.pick({ release_id: true, state: true, generation: true, activated_at: true }).nullable(),
1159
+ latest_job: LatestJob.pick({ state: true, updated_at: true }).nullable()
1160
+ });
1161
+ const pages = z2.object({
1162
+ site_id: z2.string(),
1163
+ unavailable: z2.literal("no_release").optional(),
1164
+ release_id: z2.string().optional(),
1165
+ pages: z2.array(z2.object({ path: z2.string(), url: z2.string() })).optional()
1166
+ });
1167
+ const releases = ReleasesPage.pick({ site_id: true, next_cursor: true, active_release_id: true, active_release_status: true }).extend({
1168
+ releases: z2.array(ReleaseRecord.pick({ release_id: true, state: true, built_at: true, activated_at: true, source_revision_id: true, git_commit: true }).extend({
1169
+ job: ReleaseRecord.shape.job.pick({ job_id: true, operation: true, requested_by: true })
1170
+ }))
1171
+ });
1172
+ const activityEvent = ActivityEvent.pick({
1173
+ id: true,
1174
+ operation: true,
1175
+ state: true,
1176
+ outcome_code: true,
1177
+ error_code: true,
1178
+ repository: true,
1179
+ commit_sha: true,
1180
+ actor: true,
1181
+ suggestion_id: true,
1182
+ pr_number: true,
1183
+ skip_reason: true,
1184
+ created_at: true,
1185
+ updated_at: true
1186
+ }).transform((event) => ({
1187
+ ...event,
1188
+ repository: event.repository && isGitHubRepository(event.repository) ? event.repository : null,
1189
+ error_message: null,
1190
+ commit_message: null
1191
+ }));
1192
+ const activity = ActivityPage.pick({ site_id: true, next_cursor: true }).extend({ events: z2.array(activityEvent) });
1193
+ const count = z2.number().int().nonnegative().optional();
1194
+ const activitySummary = ActivitySummary.pick({ site_id: true, since: true, until: true, total: true }).extend({
1195
+ counts: z2.object({ suggestion: count, nochange: count, skipped: count, failed: count, published: count, working: count, cancelled: count })
1196
+ });
1197
+ const preview = SuggestionPreviewResponse.pick({ state: true, revision: true, current: true });
1198
+ const buildRetry = z2.object({ retried: z2.boolean(), job_id: z2.string().optional(), attempt: z2.number().int().optional(), operation: z2.string().optional() });
1199
+ const requests = z2.union([flat, grouped]);
1200
+ const update = UpdateRequestResponse.pick({ job_id: true, state: true });
1201
+ const retry = RequestRetryResponse.pick({ job_id: true, state: true, attempt: true });
1202
+ const build = BuildOutcome.pick({ job_id: true, commit_sha: true, state: true });
1203
+ return { suggestion, suggestions, detail, request, entries, grouped, flat, requests, thread, site, pages, releases, activity, activitySummary, preview, buildRetry, update, retry, build };
1204
+ })();
1205
+ var managementWriteReceipts = {
1206
+ "POST /settings/proposal/approve": SettingsApprovalResponse,
1207
+ "POST /settings/proposal/update": SettingsUpdateResponse,
1208
+ "POST /releases/rollback": ReleaseRollbackResponse,
1209
+ "POST /requests": UpdateRequestResponse,
1210
+ "POST /gaps/work": GapWorkResponse,
1211
+ "POST /requests/{job}/retry": RequestRetryResponse,
1212
+ "POST /domains": AddDomainResponse,
1213
+ "DELETE /domains/{hostname}": RemoveDomainResponse,
1214
+ "POST /readers": WriteReaderResponse,
1215
+ "DELETE /readers": ClearReadersResponse,
1216
+ "DELETE /readers/{entry}": RemoveReaderResponse,
1217
+ "POST /readers/rotate": RotateReadersResponse,
1218
+ "POST /owners": OwnerResponse,
1219
+ "PATCH /owners/{owner}": OwnerResponse,
1220
+ "DELETE /owners/{owner}": RemoveOwnerResponse,
1221
+ "PATCH /organization": OrganizationResponse,
1222
+ "POST /organization/leave": OrganizationLeaveResponse,
1223
+ "POST /billing/checkout": BillingRedirect,
1224
+ "POST /billing/portal": BillingRedirect,
1225
+ "POST /credentials": IssuedManagementCredential,
1226
+ "DELETE /grants/{grant}": z2.object({ revoked: z2.boolean(), grant_id: z2.string() }),
1227
+ "DELETE /credentials/{token}": z2.object({ revoked: z2.boolean(), token_id: z2.string() }),
1228
+ "POST /builds": BuildOutcome,
1229
+ "POST /builds/retry": z2.object({ retried: z2.boolean(), job_id: z2.string().optional(), operation: z2.string().optional(), attempt: z2.number().int().optional() }),
1230
+ "POST /suggestions/{suggestion}/approve": ApproveOutcome,
1231
+ "POST /suggestions/{suggestion}/retry": RetryOutcome,
1232
+ "POST /suggestions/{suggestion}/dismiss": DismissOutcome,
1233
+ "POST /suggestions/{suggestion}/request-changes": RequestChangesOutcome,
1234
+ "POST /docs-repo": z2.object({ docs_repo: DocsRepoSettings.shape.docs_repo, job_id: z2.string().nullable() }),
1235
+ "POST /docs-repo/inspect": DocsInspection,
1236
+ "POST /docs-repo/scaffold": DocsRepoScaffoldResponse,
1237
+ "POST /docs-repo/reconnect": z2.object({ state: z2.literal("active"), job_id: z2.string().nullable() }),
1238
+ "POST /product-connections": ProductConnectionWriteResponse,
1239
+ "PATCH /product-connections/{connection}": ProductConnectionWriteResponse,
1240
+ "POST /product-connections/{connection}/analyse": AnalyseOutcome,
1241
+ "POST /analysis-limit": AnalysisLimit,
1242
+ ...Object.fromEntries(["pause", "resume", "reconnect"].map((action) => [`POST /product-connections/{connection}/${action}`, z2.object({ product_connection: ProductConnectionRules.nullable(), state: z2.string() })])),
1243
+ "POST /github/install": z2.object({ authorization_url: z2.string() }),
1244
+ "POST /github/connect": z2.object({ authorization_url: z2.string() }),
1245
+ "POST /github/link": GitHubLinkOutcome,
1246
+ "POST /slack/install": z2.object({ authorization_url: z2.string() }),
1247
+ "POST /suggestions/{suggestion}/session": SessionResponse,
1248
+ "POST /suggestions/{suggestion}/preview": SuggestionPreviewResponse,
1249
+ "PUT /notifications": NotificationsResponse,
1250
+ "PUT /previews": PreviewSettings
1251
+ };
934
1252
 
935
1253
  // ../management-client/dist/index.js
936
1254
  import { z as z4 } from "zod";
937
1255
  import { z as z5 } from "zod";
1256
+ import { z as z6 } from "zod";
938
1257
  var EXIT = {
939
1258
  success: 0,
940
1259
  invalid_input: 2,
@@ -1040,7 +1359,11 @@ var LIMITATION_CODES = [
1040
1359
  "hand_edited",
1041
1360
  "cleanup_incomplete",
1042
1361
  "activation_unknown",
1043
- "section_unavailable"
1362
+ "section_unavailable",
1363
+ "field_omitted",
1364
+ "value_redacted",
1365
+ "actor_relabeled",
1366
+ "row_visibility"
1044
1367
  ];
1045
1368
  var ClientLimitation = z22.object({
1046
1369
  code: z22.enum(LIMITATION_CODES),
@@ -1081,26 +1404,72 @@ var ClientResult = z22.discriminatedUnion("ok", [ClientSuccess, ClientFailure]);
1081
1404
  function exitForResult(result) {
1082
1405
  return result.ok ? EXIT.success : result.error.exit;
1083
1406
  }
1407
+ function projection(full, grant) {
1408
+ const omitted2 = Object.keys(full.shape).filter((key) => !(key in grant.shape));
1409
+ const absent = Object.fromEntries(omitted2.map((key) => [key, z32.never().optional()]));
1410
+ return grant.extend(absent);
1411
+ }
1412
+ function credentialSchema(schema, grantAuthenticated) {
1413
+ return grantAuthenticated ? schema : schema.options[0];
1414
+ }
1415
+ var G = Grant;
1416
+ var grantSite = projection(PortalSite, G.site).extend({
1417
+ docs_repo: projection(DocsRepo, G.site.shape.docs_repo.unwrap()).nullable(),
1418
+ latest_job: projection(LatestJob, G.site.shape.latest_job.unwrap()).nullable()
1419
+ });
1420
+ var fullDetail = SuggestionRecord.extend({ session_budget: SuggestionDetailRecord.shape.session_budget.optional() });
1421
+ var grantSuggestion = projection(SuggestionRecord, G.suggestion);
1422
+ var grantRequest = z32.union([RequestRecord, projection(RequestRecord, G.request)]);
1423
+ var grantEntries = z32.array(z32.union([RequestThreadEntry, projection(RequestThreadEntry, G.entries.element)]));
1424
+ var grantThread = G.thread.extend({ root: grantRequest, latest_job: grantRequest, entries: grantEntries });
1425
+ var grantGrouped = projection(RequestsPage, G.grouped).extend({
1426
+ threads: z32.array(G.grouped.shape.threads.element.extend({ root: grantRequest, latest: grantRequest, entries: grantEntries }))
1427
+ });
1428
+ var grantRelease = G.releases.shape.releases.element;
1429
+ var grantReleaseRow = projection(ReleaseRecord, grantRelease).extend({
1430
+ job: projection(ReleaseRecord.shape.job, grantRelease.shape.job)
1431
+ });
1432
+ var grantReleases = ReleasesPage.extend({
1433
+ releases: z32.array(z32.union([ReleaseRecord, grantReleaseRow]))
1434
+ });
1435
+ var [noRelease, published] = PagesResponse.options;
1436
+ var grantPublished = G.pages.pick({ site_id: true, release_id: true, pages: true }).required();
1437
+ var grantPages = z32.union([
1438
+ projection(noRelease, G.pages.pick({ site_id: true, unavailable: true }).required()),
1439
+ projection(published, grantPublished).extend({
1440
+ pages: z32.array(projection(published.shape.pages.element, G.pages.shape.pages.unwrap().element))
1441
+ })
1442
+ ]);
1084
1443
  var SitesResponse2 = SitesResponse.loose();
1085
- var PortalSite2 = PortalSite.loose();
1086
- var PagesResponse2 = PagesResponse;
1444
+ var PortalSite2 = z32.union([PortalSite.loose(), grantSite]);
1445
+ var PagesResponse2 = z32.union([PagesResponse, grantPages]);
1087
1446
  var ActivityPage2 = ActivityPage.loose();
1088
- var ReleasesPage2 = ReleasesPage.loose();
1089
- var RequestsPage2 = RequestsPage.loose();
1090
- var RequestThread2 = RequestThread.loose();
1447
+ var ReleasesPage2 = z32.union([ReleasesPage.loose(), grantReleases]);
1448
+ var BuildRetry = G.buildRetry;
1449
+ var FlatRequestsPage = z32.union([
1450
+ G.flat.extend({ requests: z32.array(RequestRecord), failed: z32.number().int().nonnegative().optional() }).loose(),
1451
+ G.flat.extend({ requests: z32.array(grantRequest) })
1452
+ ]);
1453
+ var RequestsPage2 = z32.union([RequestsPage.loose(), grantGrouped]);
1454
+ var RequestThread2 = z32.union([RequestThread.loose(), grantThread]);
1091
1455
  var UpdateRequestResponse2 = UpdateRequestResponse.loose();
1092
1456
  var RequestRetryResponse2 = RequestRetryResponse.loose();
1093
- var SuggestionsPage2 = SuggestionsPage.loose();
1094
- var SuggestionDetailResponse2 = SuggestionDetailResponse.loose();
1457
+ var SuggestionsPage2 = z32.union([SuggestionsPage.loose(), projection(SuggestionsPage, G.suggestions).extend({ suggestions: z32.array(z32.union([SuggestionRecord, grantSuggestion])) })]);
1458
+ var SuggestionDetailResponse2 = z32.union([
1459
+ SuggestionDetailResponse.extend({ suggestion: fullDetail }).loose(),
1460
+ G.detail.extend({ suggestion: projection(fullDetail, G.detail.shape.suggestion) })
1461
+ ]);
1095
1462
  var SuggestionThread2 = SuggestionThread.loose();
1096
1463
  var SessionResponse2 = SessionResponse.loose();
1097
- var SuggestionPreviewResponse2 = SuggestionPreviewResponse.loose();
1464
+ var SuggestionPreviewResponse2 = z32.union([SuggestionPreviewResponse.loose(), projection(SuggestionPreviewResponse, G.preview)]);
1098
1465
  var ApproveOutcome2 = ApproveOutcome.loose();
1099
1466
  var DismissOutcome2 = DismissOutcome.loose();
1100
1467
  var RequestChangesOutcome2 = RequestChangesOutcome.loose();
1101
1468
  var ErrorEnvelope2 = ErrorEnvelope.loose();
1102
1469
  var DocsRepoSettings2 = DocsRepoSettings.loose();
1103
1470
  var ProductConnectionsResponse2 = ProductConnectionsResponse.loose();
1471
+ var ReleaseRollbackResponse2 = ReleaseRollbackResponse;
1472
+ var ReleaseRollbackBody2 = ReleaseRollbackBody;
1104
1473
  var MANAGEMENT_SCOPES2 = MANAGEMENT_SCOPES;
1105
1474
  var SHA = /^[0-9a-f]{40}$/u;
1106
1475
  var ExactReviewInput = z32.object({
@@ -1173,6 +1542,7 @@ var P0_OPERATIONS = {
1173
1542
  response: ActivityPage2,
1174
1543
  note: "An exact job read comes from the jobs alone, so a queued job is found however many events came after it."
1175
1544
  },
1545
+ "releases.rollback": { path: "/releases/rollback", method: "POST", permission: "rollback", mutation: true, query: [], response: ReleaseRollbackResponse2, note: "Activate the named pin at the expected active release and generation." },
1176
1546
  "releases.list": {
1177
1547
  path: "/releases",
1178
1548
  method: "GET",
@@ -1252,6 +1622,138 @@ function operationPath(key, siteId, params = {}) {
1252
1622
  });
1253
1623
  return `/v1/sites/${encodeURIComponent(siteId)}${rest}`;
1254
1624
  }
1625
+ var receiptRoutes = Object.keys(managementWriteReceipts).map((key) => new RegExp("^" + key.replace(/\{[^}]+\}/gu, "[^/]+") + "$", "u"));
1626
+ function requiresManagementReceipt(method, route) {
1627
+ if (method === "GET") return route === "credentials";
1628
+ return route.startsWith("settings/") || receiptRoutes.some((pattern) => pattern.test(method + " /" + route));
1629
+ }
1630
+ var ManagementError = class extends Error {
1631
+ recovery;
1632
+ detail;
1633
+ constructor(detail, options) {
1634
+ super(detail.message, options);
1635
+ this.name = "ManagementError";
1636
+ this.detail = detail;
1637
+ this.recovery = options?.recovery;
1638
+ }
1639
+ };
1640
+ function clientError(code, message, overrides = {}) {
1641
+ const category = CLIENT_ERROR_CATEGORIES[code];
1642
+ return {
1643
+ code,
1644
+ message,
1645
+ retryable: overrides.retryable ?? category.retryable,
1646
+ mutation: overrides.mutation ?? category.mutation,
1647
+ exit: category.exit,
1648
+ server: overrides.server ?? null
1649
+ };
1650
+ }
1651
+ function managementError(code, message, overrides = {}) {
1652
+ return new ManagementError(clientError(code, message, overrides));
1653
+ }
1654
+ function invalidInput(message) {
1655
+ return managementError("invalid_input", message);
1656
+ }
1657
+ function refusalError(refusal, details = {}) {
1658
+ const code = classifyRefusal(refusal, { exactReview: details.exactReview });
1659
+ const fault = serverFault(refusal, details.retryAfter ?? null, details.correlationId ?? null);
1660
+ const message = code === "unauthorized" ? OPAQUE_UNAUTHORIZED_MESSAGE : fault.message ?? `The management API answered ${refusal.status}${fault.code === null ? "" : ` ${fault.code}`}.`;
1661
+ return new ManagementError(clientError(code, message, { mutation: details.mutation, server: fault }));
1662
+ }
1663
+ function transportFailure(message, mutation = "not_submitted") {
1664
+ return managementError("transport_failure", message, { mutation });
1665
+ }
1666
+ function interrupted(mutation = "not_submitted") {
1667
+ return managementError("interrupted", "The command was interrupted before it finished. Nothing remote was cancelled.", { mutation });
1668
+ }
1669
+ function unknownOutcome(message) {
1670
+ return managementError("unknown_outcome", message);
1671
+ }
1672
+ function isManagementError(value) {
1673
+ return value instanceof ManagementError;
1674
+ }
1675
+ function toClientError(cause, mutation = "not_submitted") {
1676
+ if (isManagementError(cause)) return cause.detail;
1677
+ const message = cause instanceof Error ? cause.message : String(cause);
1678
+ return clientError("transport_failure", message === "" ? "The request failed without a reason." : message, { mutation });
1679
+ }
1680
+ var REDACTION = "[redacted]";
1681
+ function redactSecrets(text, secrets) {
1682
+ let out = text.replace(/[Bb]earer\s+[\w.~+/=-]+/gu, `Bearer ${REDACTION}`);
1683
+ for (const secret of secrets) {
1684
+ if (secret === void 0 || secret === "") continue;
1685
+ out = out.split(secret).join(REDACTION);
1686
+ }
1687
+ return out;
1688
+ }
1689
+ var G2 = Grant;
1690
+ function omitted(full, grant, prefix = "") {
1691
+ return Object.keys(full.shape).filter((key) => !(key in grant.shape)).map((key) => prefix + key);
1692
+ }
1693
+ var grantFields = {
1694
+ site: [
1695
+ ...omitted(PortalSite, G2.site),
1696
+ ...omitted(DocsRepo, G2.site.shape.docs_repo.unwrap(), "docs_repo."),
1697
+ ...omitted(LatestJob, G2.site.shape.latest_job.unwrap(), "latest_job.")
1698
+ ],
1699
+ pages: [
1700
+ ...omitted(PagesResponse.options[1], G2.pages),
1701
+ ...omitted(PagesResponse.options[1].shape.pages.element, G2.pages.shape.pages.unwrap().element, "pages[].")
1702
+ ],
1703
+ pagesUnavailable: omitted(PagesResponse.options[0], G2.pages),
1704
+ releases: omitted(ReleasesPage, G2.releases),
1705
+ release: omitted(ReleaseRecord, G2.releases.shape.releases.element),
1706
+ releaseJob: omitted(ReleaseRecord.shape.job, G2.releases.shape.releases.element.shape.job),
1707
+ suggestion: omitted(SuggestionDetailRecord, G2.detail.shape.suggestion),
1708
+ suggestions: omitted(SuggestionsPage, G2.suggestions),
1709
+ inboxRow: omitted(SuggestionInboxRecord, G2.suggestions.shape.suggestions.element),
1710
+ activity: omitted(ActivityEvent, G2.activity.shape.events.element.in).filter((key) => key !== "error_message" && key !== "commit_message"),
1711
+ requestCounts: omitted(RequestsPage, G2.grouped),
1712
+ request: omitted(RequestRecord, G2.request),
1713
+ entry: omitted(RequestThreadEntry, G2.entries.element, "entries[]."),
1714
+ preview: omitted(SuggestionPreviewResponse, G2.preview)
1715
+ };
1716
+ function grantLimitation(at, fields) {
1717
+ return { code: "field_omitted", at, message: `Saved login omits these fields from ${at}: ${fields.join(", ")}.` };
1718
+ }
1719
+ function actorLimitation(at, fields) {
1720
+ return { code: "actor_relabeled", at, message: `Saved login labels ${fields.join(", ")} as self, agent, or person.` };
1721
+ }
1722
+ function omittedLimitations(at, row, candidates) {
1723
+ const fields = candidates.filter((field) => !Object.hasOwn(row, field));
1724
+ return fields.length ? [grantLimitation(at, fields)] : [];
1725
+ }
1726
+ function labeledActors(at, row, candidates) {
1727
+ const fields = candidates.filter((field) => ["self", "agent", "person"].includes(Reflect.get(row, field)));
1728
+ return fields.length ? [actorLimitation(at, fields)] : [];
1729
+ }
1730
+ function activityGrantLimitations(at, event) {
1731
+ const omitted2 = omittedLimitations(at, event, grantFields.activity);
1732
+ const labels = labeledActors(at, event, ["actor"]);
1733
+ if (!omitted2.length && !labels.length) return [];
1734
+ const redactions = ["commit_message", "error_message", "repository"].filter((field) => event[field] === null);
1735
+ return [...omitted2, ...labels, ...redactions.length ? [{
1736
+ code: "value_redacted",
1737
+ at,
1738
+ message: `Saved login may redact ${redactions.join(", ")}. These values are null.`
1739
+ }] : []];
1740
+ }
1741
+ function suggestionListLimitations(page) {
1742
+ const limitations = omittedLimitations("suggestions", page, grantFields.suggestions);
1743
+ page.suggestions.forEach((row, index) => {
1744
+ const at = `suggestions[${index}]`;
1745
+ if (row.pr_number === void 0) limitations.push(...omittedLimitations(at, row, grantFields.inboxRow));
1746
+ limitations.push(...labeledActors(at, row, ["requested_by"]));
1747
+ });
1748
+ if (page.state === "failed" && page.counts === void 0) limitations.push({ code: "row_visibility", at: "suggestions", message: "For this saved login, the failed tab excludes product push failures that never created a suggestion row." });
1749
+ return limitations;
1750
+ }
1751
+ function requireManagementRead(purpose) {
1752
+ const message = "Set SATURNDOCS_MANAGEMENT_TOKEN to a management credential with manage:read scope.";
1753
+ throw new ManagementError(clientError("unauthorized", `Saved login does not include ${purpose}. ${message}`), {
1754
+ recovery: { message, command: null, replay: null }
1755
+ });
1756
+ }
1255
1757
  var REQUEST_WAIT_TABLE = Object.freeze([
1256
1758
  { state: "queued", entry: null, decision: "continue", outcome: "working", exit: EXIT.success, note: "Still admitted; nothing to report yet." },
1257
1759
  { state: "running", entry: null, decision: "continue", outcome: "working", exit: EXIT.success, note: "Drafting." },
@@ -1271,14 +1773,20 @@ var REQUEST_WAIT_TABLE = Object.freeze([
1271
1773
  { state: "cancelled", entry: "failed", decision: "stop", outcome: "cancelled", exit: EXIT.service_failure, note: "Cancelled or superseded." }
1272
1774
  ]);
1273
1775
  var ENTRY_KINDS = /* @__PURE__ */ new Set(["draft", "question", "no_change", "failed"]);
1776
+ function newestRequestWaitEntry(thread) {
1777
+ const latest = thread.latest_job;
1778
+ const firstGrantAttempt = latest.page === void 0 && latest.attempt === 1;
1779
+ return thread.entries.filter((entry) => entry.job_id === latest.job_id && (firstGrantAttempt || latest.attempt === null || entry.attempt === latest.attempt)).at(-1);
1780
+ }
1274
1781
  function classifyRequestWait(thread) {
1275
1782
  const latest = thread.latest_job;
1276
- const mine = thread.entries.filter((entry2) => entry2.job_id === latest.job_id && (latest.attempt === null || entry2.attempt === latest.attempt));
1277
- const newest = mine.at(-1);
1783
+ const projected = latest.page === void 0;
1784
+ if (projected && latest.state === "succeeded" && latest.attempt !== 1) requireManagementRead("the entry attempts needed to verify this request outcome");
1785
+ const newest = newestRequestWaitEntry(thread);
1278
1786
  const entry = newest === void 0 ? null : ENTRY_KINDS.has(newest.kind) ? newest.kind : "other";
1279
1787
  const rule = REQUEST_WAIT_TABLE.find((row) => row.state === latest.state && row.entry === entry) ?? REQUEST_WAIT_TABLE.find((row) => row.state === latest.state && row.entry === null);
1280
1788
  if (rule === void 0) throw new Error(`No request wait rule for state ${latest.state}`);
1281
- return { job_id: latest.job_id, attempt: latest.attempt, entry, rule, suggestion_id: newest?.suggestion_id ?? null };
1789
+ return { job_id: latest.job_id, attempt: latest.attempt, entry, rule, suggestion_id: newest?.suggestion_id ?? (projected && entry === "draft" ? latest.suggestion_id : null) };
1282
1790
  }
1283
1791
  var SUGGESTION_WAIT_TARGETS = ["reviewable", "published"];
1284
1792
  var SUGGESTION_WAIT_TABLE = Object.freeze([
@@ -1350,10 +1858,13 @@ var cursor = { name: "--cursor", value: "string", required: false, description:
1350
1858
  var limit = { name: "--limit", value: "integer", required: false, description: "Page size, within the operation's server ceiling." };
1351
1859
  var P0_COMMANDS = [
1352
1860
  { name: "auth status", operation: "sites.list", operations: ["sites.list"], permission: "manage:read", mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [], exits: READ_EXITS, summary: "Verify read access and report the credential's own site. Says nothing about scopes the server did not return." },
1861
+ { name: "login", operation: null, operations: [], permission: null, mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [{ name: "--new-site", value: "string", required: false, description: "Propose a new site address; the person creates the site while approving." }, { name: "--scope", value: "string", required: false, description: "Comma-separated permissions to request: read, draft, build, publish. Omit to let the person choose from the defaults." }, { name: "--no-wait", value: "boolean", required: false, description: "Print the approval link and exit; finish later with --resume." }, { name: "--resume", value: "boolean", required: false, description: "Wait for the approval started by an earlier --no-wait." }, { name: "--open", value: "boolean", required: false, description: "Open the approval link in the default browser." }], exits: WAIT_EXITS, summary: "Ask a person to approve this agent for one site in the browser, then save the resulting login." },
1862
+ { name: "logout", operation: null, operations: [], permission: null, mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [{ name: "--all", value: "boolean", required: false, description: "Revoke and forget every saved login for this API origin." }], exits: WRITE_EXITS, summary: "Revoke a saved login on the server and delete it from this computer." },
1863
+ { name: "sites create", operation: null, operations: [], permission: null, mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [{ name: "--scope", value: "string", required: false, description: "Comma-separated permissions to request: read, draft, build, publish. Omit to let the person choose from the defaults." }, { name: "--no-wait", value: "boolean", required: false, description: "Print the approval link and exit; finish later with saturndocs login --resume." }, { name: "--open", value: "boolean", required: false, description: "Open the approval link in the default browser." }], exits: WAIT_EXITS, summary: "Propose a new site; a person creates it while approving this agent, and the login is saved." },
1353
1864
  { name: "sites list", operation: "sites.list", operations: ["sites.list"], permission: "manage:read", mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [], exits: READ_EXITS, summary: "The sites the presented credential resolves to." },
1354
1865
  { name: "sites get", operation: "site.get", operations: ["site.get", "docs-repo.get", "product-connections.list"], permission: "manage:read", mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [{ name: "--connections", value: "boolean", required: false, description: "Also read the documentation repository and watched repositories." }], exits: READ_EXITS, summary: "One site's status, hostnames, publication, and usage." },
1355
1866
  { name: "pages list", operation: "pages.list", operations: ["pages.list"], permission: "manage:read", mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [{ name: "--days", value: "integer", required: false, description: "Traffic window: 7, 30, or 90." }], exits: READ_EXITS, summary: "Published pages of the live release. An unpublished site is not an empty list." },
1356
- { name: "status", operation: null, operations: ["site.get", "requests.list", "suggestions.list", "activity.list"], permission: "manage:read", mutation: false, requires_site: true, text_input: "none", text_limit: null, flags: [], exits: READ_EXITS, summary: "Bounded briefing. Each section reports available, empty, or unavailable on its own." },
1867
+ { name: "status", operation: null, operations: ["site.get", "requests.list", "suggestions.list", "activity.list"], permission: "manage:read", mutation: false, requires_site: true, text_input: "none", text_limit: null, flags: [], exits: READ_EXITS, summary: "Bounded briefing. Each section reports available, empty, unavailable, or not_granted on its own." },
1357
1868
  { name: "schema", operation: null, operations: [], permission: null, mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [], exits: [EXIT.success, EXIT.invalid_input, EXIT.interrupted], summary: "Versioned command metadata, locally. No credential and no network." },
1358
1869
  { name: "nav", operation: null, operations: [], permission: null, mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [{ name: "--outline", value: "string", required: true, description: "Path to the approved outline JSON." }], exits: [EXIT.success, EXIT.invalid_input, EXIT.interrupted], summary: "Rewrite docs.json navigation from an approved outline. Local; no credential and no network." },
1359
1870
  { name: "lint", operation: null, operations: [], permission: null, mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [], exits: [EXIT.success, EXIT.invalid_input, EXIT.interrupted], summary: "Content lint and the known-pitfalls catalog over every page; exits 2 when any finding is an error. Local." },
@@ -1379,69 +1890,29 @@ var P0_COMMANDS = [
1379
1890
  { name: "activity list", operation: "activity.list", operations: ["activity.list"], permission: "manage:read", mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [cursor, limit, { name: "--outcome", value: "string", required: false, description: "suggestion, nochange, skipped, failed, or published." }, { name: "--repo", value: "string", required: false, description: "Full repository name." }, { name: "--from", value: "string", required: false, description: "Inclusive UTC date." }, { name: "--to", value: "string", required: false, description: "Inclusive UTC date." }], exits: READ_EXITS, summary: "Operational activity, newest first." },
1380
1891
  { name: "activity get", operation: "activity.list", operations: ["activity.list"], permission: "manage:read", mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [], exits: READ_EXITS, summary: "One job by id, through the list operation's job_id filter. No page-one scan." },
1381
1892
  { name: "releases list", operation: "releases.list", operations: ["releases.list"], permission: "manage:read", mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [cursor, limit], exits: READ_EXITS, summary: "Releases, newest first, with activation and current-active status." },
1893
+ {
1894
+ name: "releases rollback",
1895
+ operation: "releases.rollback",
1896
+ operations: ["releases.rollback"],
1897
+ permission: "rollback",
1898
+ mutation: true,
1899
+ requires_site: true,
1900
+ text_input: "none",
1901
+ text_limit: null,
1902
+ flags: [
1903
+ { name: "--expected-active", value: "string", required: true, description: "Currently active release id." },
1904
+ { name: "--expected-generation", value: "integer", required: true, description: "Currently active generation." },
1905
+ { name: "--yes", value: "boolean", required: true, description: "Confirm the rollback." }
1906
+ ],
1907
+ exits: WRITE_EXITS,
1908
+ summary: "Make the pinned release live until the next successful docs push."
1909
+ },
1382
1910
  { name: "releases get", operation: "releases.list", operations: ["releases.list"], permission: "manage:read", mutation: false, requires_site: false, text_input: "none", text_limit: null, flags: [], exits: READ_EXITS, summary: "One release by id, including one older than the first page." }
1383
1911
  ];
1384
1912
  var P0_COMMAND_NAMES = Object.freeze(P0_COMMANDS.map((command) => command.name));
1385
1913
  function commandSpec(name) {
1386
1914
  return P0_COMMANDS.find((command) => command.name === name);
1387
1915
  }
1388
- var ManagementError = class extends Error {
1389
- detail;
1390
- constructor(detail, options) {
1391
- super(detail.message, options);
1392
- this.name = "ManagementError";
1393
- this.detail = detail;
1394
- }
1395
- };
1396
- function clientError(code, message, overrides = {}) {
1397
- const category = CLIENT_ERROR_CATEGORIES[code];
1398
- return {
1399
- code,
1400
- message,
1401
- retryable: overrides.retryable ?? category.retryable,
1402
- mutation: overrides.mutation ?? category.mutation,
1403
- exit: category.exit,
1404
- server: overrides.server ?? null
1405
- };
1406
- }
1407
- function managementError(code, message, overrides = {}) {
1408
- return new ManagementError(clientError(code, message, overrides));
1409
- }
1410
- function invalidInput(message) {
1411
- return managementError("invalid_input", message);
1412
- }
1413
- function refusalError(refusal, details = {}) {
1414
- const code = classifyRefusal(refusal, { exactReview: details.exactReview });
1415
- const fault = serverFault(refusal, details.retryAfter ?? null, details.correlationId ?? null);
1416
- const message = code === "unauthorized" ? OPAQUE_UNAUTHORIZED_MESSAGE : fault.message ?? `The management API answered ${refusal.status}${fault.code === null ? "" : ` ${fault.code}`}.`;
1417
- return new ManagementError(clientError(code, message, { mutation: details.mutation, server: fault }));
1418
- }
1419
- function transportFailure(message, mutation = "not_submitted") {
1420
- return managementError("transport_failure", message, { mutation });
1421
- }
1422
- function interrupted(mutation = "not_submitted") {
1423
- return managementError("interrupted", "The command was interrupted before it finished. Nothing remote was cancelled.", { mutation });
1424
- }
1425
- function unknownOutcome(message) {
1426
- return managementError("unknown_outcome", message);
1427
- }
1428
- function isManagementError(value) {
1429
- return value instanceof ManagementError;
1430
- }
1431
- function toClientError(cause, mutation = "not_submitted") {
1432
- if (isManagementError(cause)) return cause.detail;
1433
- const message = cause instanceof Error ? cause.message : String(cause);
1434
- return clientError("transport_failure", message === "" ? "The request failed without a reason." : message, { mutation });
1435
- }
1436
- var REDACTION = "[redacted]";
1437
- function redactSecrets(text, secrets) {
1438
- let out = text.replace(/[Bb]earer\s+[\w.~+/=-]+/gu, `Bearer ${REDACTION}`);
1439
- for (const secret of secrets) {
1440
- if (secret === void 0 || secret === "") continue;
1441
- out = out.split(secret).join(REDACTION);
1442
- }
1443
- return out;
1444
- }
1445
1916
  var COMMIT_SHA = /^[0-9a-f]{40}$/u;
1446
1917
  var SETTINGS_REVISION = /^[0-9a-f]{64}$/u;
1447
1918
  function parseReviewedRevision(base, head) {
@@ -1571,7 +2042,9 @@ function defaultSleep(ms, signal) {
1571
2042
  }
1572
2043
  function createClient(config = {}) {
1573
2044
  const origin = parseOrigin(config.origin);
1574
- const token = config.token;
2045
+ let token = config.token;
2046
+ let pendingToken = null;
2047
+ const provider = config.token === void 0 ? config.tokenProvider : void 0;
1575
2048
  const fetchImpl = config.fetchImpl ?? fetch;
1576
2049
  const callerSignal = config.signal;
1577
2050
  const defaultDeadline = config.deadlineMs ?? DEFAULT_DEADLINE_MS;
@@ -1589,9 +2062,14 @@ function createClient(config = {}) {
1589
2062
  if (input.method === "GET" && (input.body !== void 0 || input.rawBody !== void 0)) throw invalidInput("A GET request does not carry a body.");
1590
2063
  if (input.body !== void 0 && input.rawBody !== void 0) throw invalidInput("A request carries either a JSON body or an encoded one, never both.");
1591
2064
  const anonymous = input.anonymous === true;
1592
- if (!anonymous && (token === void 0 || token === "")) throw invalidInput("Set SATURNDOCS_MANAGEMENT_TOKEN to a management credential for this site.");
2065
+ if (!anonymous && token === void 0 && provider !== void 0) {
2066
+ pendingToken ??= provider();
2067
+ token = await pendingToken;
2068
+ secrets.push(token);
2069
+ }
2070
+ if (!anonymous && (token === void 0 || token === "")) throw invalidInput("Run saturndocs login, or set SATURNDOCS_MANAGEMENT_TOKEN to a management credential for this site.");
1593
2071
  const mutation = input.mutation === true || !IDEMPOTENT.has(input.method);
1594
- const headers = new Headers({ accept: "application/json" });
2072
+ const headers = new Headers({ accept: input.accept ?? "application/json" });
1595
2073
  if (!anonymous) headers.set("authorization", `Bearer ${token}`);
1596
2074
  if (input.revision !== void 0) headers.set("if-match", ifMatchHeader(input.revision));
1597
2075
  const body = input.rawBody ?? (input.body === void 0 ? void 0 : JSON.stringify(input.body));
@@ -1639,7 +2117,7 @@ function createClient(config = {}) {
1639
2117
  throw transportFailure(`The management answer could not be read: ${message}`, mutation ? "unknown" : "not_submitted");
1640
2118
  }
1641
2119
  let data = null;
1642
- if (text.trim() !== "") {
2120
+ if (text.length !== 0) {
1643
2121
  try {
1644
2122
  data = JSON.parse(text);
1645
2123
  } catch {
@@ -1648,13 +2126,14 @@ function createClient(config = {}) {
1648
2126
  data = null;
1649
2127
  }
1650
2128
  }
1651
- if (response.ok) return { status: response.status, headers: response.headers, data, attempts };
2129
+ if (response.ok) return { status: response.status, headers: response.headers, data, attempts, ...text.length === 0 ? { emptyBody: true } : {} };
1652
2130
  const refusal = refusalError({ status: response.status, body: data }, {
1653
2131
  exactReview: input.exactReview,
1654
2132
  retryAfter,
1655
2133
  correlationId,
1656
2134
  mutation: "not_submitted"
1657
2135
  });
2136
+ if (response.status === 409 && input.classifyConflict) throw input.classifyConflict(refusal, data);
1658
2137
  const retryable = !mutation && RETRYABLE_STATUS.has(response.status) && attempts < MAX_READ_ATTEMPTS;
1659
2138
  if (!retryable) throw refusal;
1660
2139
  const waitMs = retryAfter === null ? null : retryAfter * 1e3;
@@ -1682,6 +2161,9 @@ function createClient(config = {}) {
1682
2161
  }
1683
2162
  return {
1684
2163
  origin: origin.origin,
2164
+ get grantAuthenticated() {
2165
+ return token !== void 0 && /^sdga1\.[a-f0-9]{64}$/u.test(token);
2166
+ },
1685
2167
  request,
1686
2168
  get(path, options = {}) {
1687
2169
  return request({ ...options, method: "GET", path });
@@ -1753,7 +2235,7 @@ async function resolveTarget(client, request = {}) {
1753
2235
  if (request.mutation === true && request.site === void 0) {
1754
2236
  throw invalidInput("This command writes, so it needs an explicit --site naming the site to act on.");
1755
2237
  }
1756
- const response = await client.get("/v1/sites", { signal: request.signal, deadlineMs: request.deadlineMs });
2238
+ const response = await client.get("/v1/sites", { signal: request.signal, deadlineMs: request.deadlineMs, query: { for: request.forOperation } });
1757
2239
  const parsed = SitesResponse2.safeParse(response.data);
1758
2240
  if (!parsed.success) {
1759
2241
  throw managementError(
@@ -1869,7 +2351,7 @@ function commandMetadata(name, details) {
1869
2351
  }),
1870
2352
  permissions: Object.freeze({
1871
2353
  server: spec.permission,
1872
- preflight: spec.mutation ? "manage:read" : null
2354
+ preflight: spec.permission === "rollback" ? "rollback" : spec.mutation ? "manage:read" : null
1873
2355
  }),
1874
2356
  side_effects: Object.freeze({
1875
2357
  mutation: spec.mutation,
@@ -1902,7 +2384,7 @@ async function listSites(client, options = {}) {
1902
2384
  }
1903
2385
  async function getSite(client, siteId, options = {}) {
1904
2386
  const response = await client.get(operationPath("site.get", siteId), options);
1905
- return parseResponse(PortalSite2, response.data, `The site read for ${siteId}`);
2387
+ return parseResponse(credentialSchema(PortalSite2, client.grantAuthenticated), response.data, `The site read for ${siteId}`);
1906
2388
  }
1907
2389
  async function getDocsRepo(client, siteId, options = {}) {
1908
2390
  const response = await client.get(operationPath("docs-repo.get", siteId), options);
@@ -1935,7 +2417,7 @@ async function listPages(client, siteId, options = {}) {
1935
2417
  ...read,
1936
2418
  ...days === void 0 ? {} : { query: { days } }
1937
2419
  });
1938
- return parseResponse(PagesResponse2, response.data, `The published page listing for ${siteId}`);
2420
+ return parseResponse(credentialSchema(PagesResponse2, client.grantAuthenticated), response.data, `The published page listing for ${siteId}`);
1939
2421
  }
1940
2422
  var ActivityPageRead = ActivityPage2.extend({ events: z5.array(ActivityEvent.loose()) });
1941
2423
  var ACTIVITY_OUTCOMES = ACTIVITY_OUTCOME_FILTERS;
@@ -1989,6 +2471,7 @@ async function listActivity(client, siteId, options = {}) {
1989
2471
  const query = activityQuery({ cursor: cursor2, limit: limit2, outcome, repo, from, to });
1990
2472
  const response = await client.get(operationPath("activity.list", siteId), {
1991
2473
  ...read,
2474
+ accept: ROLLBACK_ACTIVITY_ACCEPT,
1992
2475
  ...Object.keys(query).length === 0 ? {} : { query }
1993
2476
  });
1994
2477
  return parseResponse(ActivityPageRead, response.data, `The activity listing for ${siteId}`);
@@ -2038,7 +2521,7 @@ async function listSuggestions(client, input) {
2038
2521
  signal: input.signal,
2039
2522
  deadlineMs: input.deadlineMs
2040
2523
  });
2041
- const parsed = SuggestionsPage2.safeParse(response.data);
2524
+ const parsed = credentialSchema(SuggestionsPage2, client.grantAuthenticated).safeParse(response.data);
2042
2525
  if (!parsed.success) unreadable("suggestion listing");
2043
2526
  return parsed.data;
2044
2527
  }
@@ -2048,7 +2531,7 @@ async function getSuggestion(client, input) {
2048
2531
  signal: input.signal,
2049
2532
  deadlineMs: input.deadlineMs
2050
2533
  });
2051
- const parsed = SuggestionDetailResponse2.safeParse(response.data);
2534
+ const parsed = credentialSchema(SuggestionDetailResponse2, client.grantAuthenticated).safeParse(response.data);
2052
2535
  if (!parsed.success) unreadable("suggestion detail");
2053
2536
  return parsed.data;
2054
2537
  }
@@ -2076,6 +2559,7 @@ function suggestionLimitations(suggestion) {
2076
2559
  at: "suggestion.head_sha"
2077
2560
  });
2078
2561
  }
2562
+ if (suggestion.pr_number === void 0) return [...limitations, ...omittedLimitations("suggestion", suggestion, grantFields.suggestion), ...labeledActors("suggestion", suggestion, ["reviewer", "requested_by", "head_edited_by"])];
2079
2563
  if (suggestion.snapshots_available === false || suggestion.pages !== void 0 && !pageContentAvailable(suggestion)) {
2080
2564
  limitations.push({
2081
2565
  code: "content_unavailable",
@@ -2243,7 +2727,7 @@ function rowBytes(row) {
2243
2727
  function bound(pages, maxBytes) {
2244
2728
  const out = [];
2245
2729
  let used = 0;
2246
- let omitted = 0;
2730
+ let omitted2 = 0;
2247
2731
  for (const page of pages) {
2248
2732
  used += new TextEncoder().encode(page.path).length + 16;
2249
2733
  const kept = [];
@@ -2257,13 +2741,13 @@ function bound(pages, maxBytes) {
2257
2741
  kept.push(row);
2258
2742
  }
2259
2743
  if (dropped > 0) kept.push({ op: "omitted", before_line: null, after_line: null, text: null, count: dropped });
2260
- omitted += dropped;
2744
+ omitted2 += dropped;
2261
2745
  out.push({ ...page, rows: kept, omitted_rows: dropped });
2262
2746
  }
2263
- return { pages: out, used, omitted };
2747
+ return { pages: out, used, omitted: omitted2 };
2264
2748
  }
2265
2749
  var HANDOFF = "This is the content the server supplied, formatted here. Nothing in it was checked against the product, so it is a starting point for an owner's review, not a completed one.";
2266
- function limitationsFor(suggestion, pages, omitted, limit2) {
2750
+ function limitationsFor(suggestion, pages, omitted2, limit2) {
2267
2751
  const limitations = [
2268
2752
  { code: "review_incomplete", message: HANDOFF, at: null }
2269
2753
  ];
@@ -2280,8 +2764,8 @@ function limitationsFor(suggestion, pages, omitted, limit2) {
2280
2764
  limitations.push({ code: "page_bounded", message: `The comparison of ${page.path} hit a size bound, so this diff is part of the change and not all of it.`, at });
2281
2765
  }
2282
2766
  });
2283
- if (omitted > 0) {
2284
- limitations.push({ code: "output_truncated", message: `${omitted} diff lines were left out to stay inside the ${limit2}-byte output bound. Read one page at a time with --path, or read the pull request.`, at: null });
2767
+ if (omitted2 > 0) {
2768
+ limitations.push({ code: "output_truncated", message: `${omitted2} diff lines were left out to stay inside the ${limit2}-byte output bound. Read one page at a time with --path, or read the pull request.`, at: null });
2285
2769
  }
2286
2770
  if (typeof suggestion.head_edited_by === "string" && suggestion.head_edited_by !== "") {
2287
2771
  limitations.push({ code: "hand_edited", message: `The head was edited on GitHub by ${suggestion.head_edited_by} after the draft, so this diff of the supplied content may not be what would publish.`, at: "head_sha" });
@@ -2292,6 +2776,7 @@ function limitationsFor(suggestion, pages, omitted, limit2) {
2292
2776
  return limitations;
2293
2777
  }
2294
2778
  function suggestionDiff(suggestion, options = {}) {
2779
+ if (suggestion.pr_number === void 0) requireManagementRead("suggestion page changes");
2295
2780
  const limit2 = options.maxBytes ?? DEFAULT_DIFF_MAX_BYTES;
2296
2781
  const all = suggestion.pages ?? [];
2297
2782
  const selected = options.path === void 0 ? all : all.filter((page) => page.path === options.path);
@@ -2610,8 +3095,8 @@ function summaryOf(release, state, active) {
2610
3095
  if (state === "live") return `${release.release_id} is the release readers are seeing, activated ${release.activated_at ?? "at an unrecorded time"}.`;
2611
3096
  if (state === "built") return `${release.release_id} was built and has no activation record, so it was never published.`;
2612
3097
  if (state === "historical") {
2613
- const generation = release.generation === null ? "unrecorded" : String(release.generation);
2614
- return `${release.release_id} went live at ${String(release.activated_at)} (generation ${generation}) and is not what readers are seeing now${active === null ? "" : `; that is ${active}`}.`;
3098
+ const generation = release.generation === void 0 ? "" : ` (generation ${release.generation ?? "unrecorded"})`;
3099
+ return `${release.release_id} went live at ${String(release.activated_at)}${generation} and is not what readers are seeing now${active === null ? "" : `; that is ${active}`}.`;
2615
3100
  }
2616
3101
  return `${release.release_id} went live at ${String(release.activated_at)}. The activation record could not be read, so whether it is live now is unknown.`;
2617
3102
  }
@@ -2628,7 +3113,7 @@ function classifyReleaseActivation(release, page) {
2628
3113
  return {
2629
3114
  state,
2630
3115
  activated_at: release.activated_at,
2631
- generation: release.generation,
3116
+ ...release.generation === void 0 ? {} : { generation: release.generation },
2632
3117
  active_release_id: active,
2633
3118
  active_release_status: status,
2634
3119
  rule,
@@ -2648,14 +3133,14 @@ async function listReleases(client, siteId, options = {}) {
2648
3133
  ...read,
2649
3134
  query: { ...cursor2 === void 0 ? {} : { cursor: cursor2 }, ...limit2 === void 0 ? {} : { limit: limit2 } }
2650
3135
  });
2651
- return parseResponse(ReleasesPage2, response.data, `The release listing for ${siteId}`);
3136
+ return parseResponse(credentialSchema(ReleasesPage2, client.grantAuthenticated), response.data, `The release listing for ${siteId}`);
2652
3137
  }
2653
3138
  async function getRelease(client, siteId, releaseId, options = {}) {
2654
3139
  const id = releaseId.trim();
2655
3140
  if (id === "") throw invalidInput("Name the release to read.");
2656
3141
  if (id.length > RELEASE_ID_MAX_CHARS) throw invalidInput(`A release id is at most ${RELEASE_ID_MAX_CHARS} characters; the route refuses a longer one as invalid_release_id.`);
2657
3142
  const response = await client.get(operationPath("releases.list", siteId), { ...options, query: { release_id: id } });
2658
- const page = parseResponse(ReleasesPage2, response.data, `The release read for ${id} on ${siteId}`);
3143
+ const page = parseResponse(credentialSchema(ReleasesPage2, client.grantAuthenticated), response.data, `The release read for ${id} on ${siteId}`);
2659
3144
  const release = page.releases[0];
2660
3145
  if (release === void 0) {
2661
3146
  throw managementError(
@@ -2741,7 +3226,9 @@ async function waitForSuggestion(client, input) {
2741
3226
  });
2742
3227
  const suggestion2 = detail.suggestion;
2743
3228
  const reached = classifySuggestionWait(target, suggestion2);
2744
- if (target !== "published" || reached.decision === "stop") {
3229
+ const projected = suggestion2.pr_number === void 0;
3230
+ if (target === "published" && suggestion2.state === "published" && projected) requireManagementRead("publication proof");
3231
+ if (target !== "published" || reached.decision === "stop" || projected) {
2745
3232
  return {
2746
3233
  done: reached.decision === "stop",
2747
3234
  value: { suggestion: suggestion2, outcome: reached.outcome, exit: reached.exit, note: reached.rule.note, release: null, release_unreadable: false }
@@ -2770,7 +3257,7 @@ async function waitForSuggestion(client, input) {
2770
3257
  const missingContent = reviewLimitations.some((limitation) => limitation.code === "content_unavailable");
2771
3258
  const reviewable = !outcome.timed_out && last?.outcome === "reviewable";
2772
3259
  const limitations = Object.freeze([
2773
- ...target === "reviewable" ? reviewLimitations : [],
3260
+ ...target === "reviewable" || suggestion?.pr_number === void 0 ? reviewLimitations : [],
2774
3261
  ...activationLimitation(release)
2775
3262
  ]);
2776
3263
  const base = {
@@ -2781,10 +3268,12 @@ async function waitForSuggestion(client, input) {
2781
3268
  revision: suggestion?.revision ?? null,
2782
3269
  base_sha: suggestion?.base_sha ?? null,
2783
3270
  head_sha: suggestion?.head_sha ?? null,
2784
- pr_number: suggestion?.pr_number ?? null,
2785
- publication_job_id: suggestion?.publication?.job_id ?? null,
3271
+ ...suggestion && suggestion.pr_number === void 0 ? {} : {
3272
+ pr_number: suggestion?.pr_number ?? null,
3273
+ publication_job_id: suggestion?.publication?.job_id ?? null
3274
+ },
2786
3275
  release,
2787
- owner_handoff: reviewable && missingContent,
3276
+ owner_handoff: reviewable && (missingContent || suggestion?.pr_number === void 0),
2788
3277
  limitations,
2789
3278
  polls: outcome.attempts,
2790
3279
  elapsed_ms: outcome.elapsed_ms
@@ -2800,7 +3289,7 @@ async function waitForSuggestion(client, input) {
2800
3289
  };
2801
3290
  }
2802
3291
  var REQUEST_THREAD_LIMIT_MAX = MAX_REQUEST_THREADS;
2803
- function checkedLimit(limit2) {
3292
+ function checkedRequestThreadLimit(limit2) {
2804
3293
  if (limit2 === null || limit2 === void 0) return void 0;
2805
3294
  if (!Number.isInteger(limit2) || limit2 < 1 || limit2 > REQUEST_THREAD_LIMIT_MAX) {
2806
3295
  throw invalidInput(`--limit takes a whole number from 1 to ${REQUEST_THREAD_LIMIT_MAX}. Nothing was sent.`);
@@ -2816,7 +3305,7 @@ async function listRequestThreads(client, input) {
2816
3305
  const query = {
2817
3306
  view: "threads",
2818
3307
  cursor: checkedCursor(input.cursor),
2819
- limit: checkedLimit(input.limit),
3308
+ limit: checkedRequestThreadLimit(input.limit),
2820
3309
  attention: input.attention === true ? "1" : void 0
2821
3310
  };
2822
3311
  const response = await client.get(operationPath("requests.list", input.siteId), {
@@ -2824,7 +3313,7 @@ async function listRequestThreads(client, input) {
2824
3313
  signal: input.signal,
2825
3314
  deadlineMs: input.deadlineMs
2826
3315
  });
2827
- return parseResponse(RequestsPage2, response.data, "The request thread listing");
3316
+ return parseResponse(credentialSchema(RequestsPage2, client.grantAuthenticated), response.data, "The request thread listing");
2828
3317
  }
2829
3318
  async function readRequestThread(client, input) {
2830
3319
  if (input.jobId.trim() === "") throw invalidInput("Name the job whose conversation to read.");
@@ -2832,7 +3321,62 @@ async function readRequestThread(client, input) {
2832
3321
  signal: input.signal,
2833
3322
  deadlineMs: input.deadlineMs
2834
3323
  });
2835
- return parseResponse(RequestThread2, response.data, "The request thread");
3324
+ return parseResponse(credentialSchema(RequestThread2, client.grantAuthenticated), response.data, "The request thread");
3325
+ }
3326
+ function isGrouped(page) {
3327
+ return "threads" in page && Array.isArray(page.threads);
3328
+ }
3329
+ function requestGrantLimitations(page, attention = false) {
3330
+ const grouped = isGrouped(page);
3331
+ const at = grouped ? "threads" : "thread";
3332
+ const limitations = [];
3333
+ if (grouped) limitations.push({ code: "row_visibility", at, message: "This list covers only request threads started by this saved login." });
3334
+ const threads = grouped ? page.threads : [{ root: page.root, latest: page.latest_job, entries: page.entries }];
3335
+ threads.forEach((thread, index) => {
3336
+ const path = grouped ? `threads[${index}]` : at;
3337
+ for (const [name, row] of [["root", thread.root], [grouped ? "latest" : "latest_job", thread.latest]]) {
3338
+ limitations.push(
3339
+ ...omittedLimitations(path + "." + name, row, grantFields.request),
3340
+ ...labeledActors(path + "." + name, row, ["requested_by"])
3341
+ );
3342
+ }
3343
+ if (thread.entries.some((entry) => entry.entry_id === void 0)) limitations.push(grantLimitation(path, grantFields.entry));
3344
+ });
3345
+ if (grouped && attention) limitations.push(...omittedLimitations(at, page, grantFields.requestCounts));
3346
+ return limitations;
3347
+ }
3348
+ async function rollbackRelease(client, siteId, input, signal) {
3349
+ const parsed = ReleaseRollbackBody2.safeParse(input);
3350
+ if (!parsed.success || parsed.data.release_id === parsed.data.expected_active_release_id) {
3351
+ throw invalidInput("Name the pinned release, a different active release, and the current generation.");
3352
+ }
3353
+ const body = parsed.data;
3354
+ const response = await client.request({
3355
+ method: "POST",
3356
+ path: operationPath("releases.rollback", siteId),
3357
+ body,
3358
+ signal,
3359
+ classifyConflict(error, payload) {
3360
+ const { server } = error.detail;
3361
+ if (server?.code !== SUPERSEDED_ROLLBACK) return error;
3362
+ const receipt = matchSupersededRollback(siteId, body, payload);
3363
+ if (!receipt) return unknownOutcome(ROLLBACK_RECOVERY);
3364
+ const message = describeSupersededRollback(receipt);
3365
+ return managementError("conflict", message, { server: { ...server, message }, mutation: "known" });
3366
+ }
3367
+ }).catch((error) => {
3368
+ if (!isManagementError(error)) throw error;
3369
+ const { server } = error.detail;
3370
+ if (server && uncertainRollbackRefusal(server.status, server.code)) {
3371
+ throw managementError("unknown_outcome", ROLLBACK_RECOVERY, { server });
3372
+ }
3373
+ throw error;
3374
+ });
3375
+ const proof = ReleaseRollbackResponse2.safeParse(response.data);
3376
+ if (!proof.success || !rollbackProofMatches(siteId, body, proof.data)) {
3377
+ throw unknownOutcome(ROLLBACK_RECOVERY);
3378
+ }
3379
+ return proof.data;
2836
3380
  }
2837
3381
  var REQUEST_PAGE_LIMIT = 400;
2838
3382
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
@@ -2937,7 +3481,6 @@ async function retryRequest(client, input) {
2937
3481
  }
2938
3482
  return parsed.data;
2939
3483
  }
2940
- var STATUS_SECTIONS = ["site", "requests", "suggestions", "activity"];
2941
3484
  var STATUS_PAGE_LIMIT = 10;
2942
3485
  function available(section2, data, empty, recovery) {
2943
3486
  return { section: section2, state: empty ? "empty" : "available", data, error: null, recovery };
@@ -2958,7 +3501,10 @@ function retryRecovery(section2, siteId) {
2958
3501
  message: `The ${section2} section of this briefing was not read. Run its own command to see whether the service answers, and read nothing into its absence here.`
2959
3502
  };
2960
3503
  }
2961
- async function section(name, siteId, read, isEmpty, recovery) {
3504
+ async function section(scope, name, siteId, read, isEmpty, recovery) {
3505
+ if (name === "requests" && scope && !scope.includes("draft")) {
3506
+ return { section: name, state: "not_granted", reason: "This saved login lacks the draft capability.", data: null, error: null, recovery: null };
3507
+ }
2962
3508
  try {
2963
3509
  const data = await read();
2964
3510
  return available(name, data, isEmpty(data), recovery(data));
@@ -3003,9 +3549,11 @@ function countsOf(requests, suggestions) {
3003
3549
  }
3004
3550
  async function readSiteStatus(client, siteId, options = {}) {
3005
3551
  const { limit: limit2 = STATUS_PAGE_LIMIT, ...read } = options;
3552
+ const scope = await client.savedLoginScope?.();
3006
3553
  const [site, requests, suggestions, activity] = await Promise.all([
3007
- section("site", siteId, () => getSite(client, siteId, read), () => false, () => null),
3554
+ section(scope, "site", siteId, () => getSite(client, siteId, read), () => false, () => null),
3008
3555
  section(
3556
+ scope,
3009
3557
  "requests",
3010
3558
  siteId,
3011
3559
  () => listRequestThreads(client, { siteId, limit: limit2, attention: true, ...read }),
@@ -3013,6 +3561,7 @@ async function readSiteStatus(client, siteId, options = {}) {
3013
3561
  (page) => requestsRecovery(page, siteId)
3014
3562
  ),
3015
3563
  section(
3564
+ scope,
3016
3565
  "suggestions",
3017
3566
  siteId,
3018
3567
  () => listSuggestions(client, { site: siteId, state: "pending", limit: limit2, ...read }),
@@ -3020,6 +3569,7 @@ async function readSiteStatus(client, siteId, options = {}) {
3020
3569
  () => null
3021
3570
  ),
3022
3571
  section(
3572
+ scope,
3023
3573
  "activity",
3024
3574
  siteId,
3025
3575
  () => listActivity(client, siteId, { limit: limit2, ...read }),
@@ -3040,8 +3590,12 @@ async function readSiteStatus(client, siteId, options = {}) {
3040
3590
  function statusSections(status) {
3041
3591
  return [status.site, status.requests, status.suggestions, status.activity];
3042
3592
  }
3043
- function statusLimitations(status) {
3593
+ function statusLimitations(status, savedLogin = false) {
3044
3594
  const limitations = [];
3595
+ if (status.site.data && status.site.data.hostnames === void 0) limitations.push(grantLimitation("site", grantFields.site));
3596
+ if (savedLogin && status.requests.data) limitations.push(...requestGrantLimitations(status.requests.data, true));
3597
+ if (savedLogin && status.suggestions.data) limitations.push(...suggestionListLimitations(status.suggestions.data));
3598
+ if (savedLogin && status.activity.data) limitations.push(...status.activity.data.events.flatMap((event, index) => activityGrantLimitations(`activity.data.events[${index}]`, event)));
3045
3599
  for (const part of statusSections(status)) {
3046
3600
  if (part.state !== "unavailable") continue;
3047
3601
  limitations.push({
@@ -3065,7 +3619,7 @@ function statusBlocker(status) {
3065
3619
  const failures = statusSections(status).filter((part) => part.state === "unavailable");
3066
3620
  const refused = failures.find((part) => part.error?.code === "unauthorized" || part.error?.code === "forbidden");
3067
3621
  if (refused?.error != null) return refused.error;
3068
- if (failures.length === STATUS_SECTIONS.length) return failures[0]?.error ?? null;
3622
+ if (failures.length === statusSections(status).filter((part) => part.state !== "not_granted").length) return failures[0]?.error ?? null;
3069
3623
  return null;
3070
3624
  }
3071
3625
  function statusIds(status) {
@@ -3086,7 +3640,7 @@ function requestWaitErrorCode(outcome) {
3086
3640
  return WAIT_ERROR_CODES2[outcome] ?? null;
3087
3641
  }
3088
3642
  function summaryOf2(state, thread) {
3089
- const entry = thread.entries.filter((row) => row.job_id === state.job_id && (state.attempt === null || row.attempt === state.attempt)).at(-1);
3643
+ const entry = newestRequestWaitEntry(thread);
3090
3644
  const words = entry === void 0 ? null : entry.body.trim();
3091
3645
  return words === null || words === "" ? state.rule.note : words;
3092
3646
  }
@@ -3135,6 +3689,9 @@ function requireSuggestionId2(value) {
3135
3689
  if (value.trim() === "") throw invalidInput("Name the suggestion to preview, as saturndocs suggestions preview <suggestion-id>.");
3136
3690
  return value;
3137
3691
  }
3692
+ function unreadableReceipt() {
3693
+ return unknownOutcome("The preview request was accepted but its receipt could not be read. Read the preview status before requesting another build.");
3694
+ }
3138
3695
  function unreadable4() {
3139
3696
  throw managementError(
3140
3697
  "transport_failure",
@@ -3143,6 +3700,10 @@ function unreadable4() {
3143
3700
  }
3144
3701
  function limitationsFor2(body) {
3145
3702
  const limitations = [];
3703
+ if (body.url === void 0) {
3704
+ const missing = grantLimitation("preview", grantFields.preview);
3705
+ limitations.push({ ...missing, message: missing.message + " Read the preview with SATURNDOCS_MANAGEMENT_TOKEN and manage:read scope to get its URL." });
3706
+ }
3146
3707
  if (body.state === "building") {
3147
3708
  limitations.push({
3148
3709
  code: "activation_unknown",
@@ -3172,10 +3733,10 @@ function toResult(suggestionId, body, requestedBuild) {
3172
3733
  state: body.state,
3173
3734
  revision: body.revision,
3174
3735
  current: body.current,
3175
- url: body.url,
3176
- leave_url: body.leave_url,
3177
- error: body.error,
3178
- current_preview_available: body.state === "ready" && body.current && body.url !== null,
3736
+ ...body.url === void 0 ? {} : { url: body.url, leave_url: body.leave_url, error: body.error },
3737
+ ...body.state === "ready" && body.current && body.url === void 0 ? {} : {
3738
+ current_preview_available: body.state === "ready" && body.current && typeof body.url === "string"
3739
+ },
3179
3740
  requested_build: requestedBuild,
3180
3741
  response: body,
3181
3742
  limitations: limitationsFor2(body)
@@ -3184,9 +3745,15 @@ function toResult(suggestionId, body, requestedBuild) {
3184
3745
  async function readPreview(client, input, method) {
3185
3746
  const suggestionId = requireSuggestionId2(input.suggestionId);
3186
3747
  const path = resourcePath(input.site, ["suggestions", suggestionId, "preview"]);
3187
- const response = method === "GET" ? await client.get(path, { signal: input.signal, deadlineMs: input.deadlineMs }) : await client.request({ method: "POST", path, signal: input.signal, deadlineMs: input.deadlineMs });
3188
- const parsed = SuggestionPreviewResponse2.safeParse(response.data);
3189
- if (!parsed.success) unreadable4();
3748
+ const response = method === "GET" ? await client.get(path, { signal: input.signal, deadlineMs: input.deadlineMs }) : await client.request({ method: "POST", path, signal: input.signal, deadlineMs: input.deadlineMs }).catch((error) => {
3749
+ if (isManagementError(error) && error.detail.code === "unknown_outcome") throw unreadableReceipt();
3750
+ throw error;
3751
+ });
3752
+ const parsed = credentialSchema(SuggestionPreviewResponse2, client.grantAuthenticated).safeParse(response.data);
3753
+ if (!parsed.success) {
3754
+ if (method === "POST") throw unreadableReceipt();
3755
+ unreadable4();
3756
+ }
3190
3757
  return toResult(suggestionId, parsed.data, method === "POST");
3191
3758
  }
3192
3759
  async function getSuggestionPreview(client, input) {
@@ -3199,6 +3766,17 @@ function previewIds(result) {
3199
3766
  return { suggestion_id: result.suggestion_id };
3200
3767
  }
3201
3768
  var SESSION_MESSAGE_LIMIT2 = MAX_SESSION_MESSAGE_CHARS;
3769
+ var SESSION_MESSAGE_DEADLINE_MS = 5 * 6e4;
3770
+ var SESSION_ATTEMPT_MS = DEFAULT_DEADLINE_MS;
3771
+ var MAX_UNREACHABLE_SENDS = 3;
3772
+ var UNREACHABLE_BACKOFF_MS = 250;
3773
+ var PendingTurn = z6.object({
3774
+ turnId: z6.string(),
3775
+ sequence: z6.number().int().positive(),
3776
+ state: z6.enum(["queued", "running", "model_complete", "committing"])
3777
+ });
3778
+ var RUNNING_BACKOFF_MS = 1e3;
3779
+ var MAX_REPLAY_BACKOFF_MS = 5e3;
3202
3780
  function requireSuggestionId3(value, usage) {
3203
3781
  if (value.trim() === "") throw invalidInput(`Name the suggestion to act on, as ${usage}.`);
3204
3782
  return value;
@@ -3214,6 +3792,13 @@ function unreadableTurn(suggestionId) {
3214
3792
  `The message was accepted and its answer was not in the shape this client understands, so whether it queued a revision is not reported here. Read the transcript with saturndocs suggestions conversation ${suggestionId} before sending anything again; sending this message again would ask the suggestion twice.`
3215
3793
  );
3216
3794
  }
3795
+ function unansweredTurn(suggestionId, why) {
3796
+ throw managementError(
3797
+ "transport_failure",
3798
+ `${why} The turn may still complete and may queue a revision. Read the transcript with saturndocs suggestions conversation ${suggestionId} before sending anything again; sending this message again would ask the suggestion twice.`,
3799
+ { mutation: "unknown", retryable: false }
3800
+ );
3801
+ }
3217
3802
  async function readConversation(client, input) {
3218
3803
  const suggestionId = requireSuggestionId3(input.suggestionId, "saturndocs suggestions conversation <suggestion-id>");
3219
3804
  const response = await client.get(resourcePath(input.site, ["suggestions", suggestionId, "session"]), {
@@ -3232,20 +3817,82 @@ async function readConversation(client, input) {
3232
3817
  async function sendSessionMessage(client, input) {
3233
3818
  const suggestionId = requireSuggestionId3(input.suggestionId, "saturndocs suggestions message <suggestion-id>");
3234
3819
  const questionId = input.questionId === void 0 || input.questionId === null || input.questionId === "" ? void 0 : input.questionId;
3235
- const body = SessionMessageBody.safeParse({ message: input.message, ...questionId === void 0 ? {} : { question_id: questionId } });
3820
+ const body = SessionMessageBody.safeParse({
3821
+ message: input.message,
3822
+ turn_id: input.turnId ?? crypto.randomUUID(),
3823
+ ...questionId === void 0 ? {} : { question_id: questionId }
3824
+ });
3236
3825
  if (!body.success) {
3237
- const onQuestion = body.error.issues.some((issue) => issue.path[0] === "question_id");
3826
+ const fields = new Set(body.error.issues.map((issue) => issue.path[0]));
3238
3827
  throw invalidInput(
3239
- onQuestion ? `--question-id takes a question id this suggestion carries, and this one is not a length the server mints. Read the suggestion's questions first; a request thread id is not a suggestion question.` : `saturndocs suggestions message accepts at most ${SESSION_MESSAGE_LIMIT2} characters and no empty message. Nothing was sent.`
3828
+ fields.has("message") ? `saturndocs suggestions message accepts at most ${SESSION_MESSAGE_LIMIT2} characters and no empty message. Nothing was sent.` : fields.has("question_id") ? `--question-id takes a question id this suggestion carries, and this one is not a length the server mints. Read the suggestion's questions first; a request thread id is not a suggestion question.` : "A turn id is a UUID, so a replay can be matched to the turn it repeats. Nothing was sent."
3240
3829
  );
3241
3830
  }
3242
- const response = await client.request({
3243
- method: "POST",
3244
- path: resourcePath(input.site, ["suggestions", suggestionId, "session"]),
3245
- body: body.data,
3246
- signal: input.signal,
3247
- deadlineMs: input.deadlineMs
3248
- });
3831
+ const deadlineMs = input.deadlineMs ?? SESSION_MESSAGE_DEADLINE_MS;
3832
+ const attemptMs = input.attemptMs ?? SESSION_ATTEMPT_MS;
3833
+ if (!Number.isFinite(deadlineMs) || deadlineMs <= 0 || !Number.isFinite(attemptMs) || attemptMs <= 0) {
3834
+ throw invalidInput("The timeout must be a positive number of seconds. Nothing was sent.");
3835
+ }
3836
+ const sleep = input.sleep ?? defaultSleep2;
3837
+ const cancelled = () => input.signal?.aborted === true;
3838
+ const startedAt = Date.now();
3839
+ const remaining = () => deadlineMs - (Date.now() - startedAt);
3840
+ const seconds = Math.round(deadlineMs / 1e3);
3841
+ let sends = 0;
3842
+ let unreachable = 0;
3843
+ let running = 0;
3844
+ let response;
3845
+ for (; ; ) {
3846
+ if (cancelled()) throw interrupted(sends === 0 ? "not_submitted" : "unknown");
3847
+ const left = remaining();
3848
+ if (left <= 0) {
3849
+ unansweredTurn(
3850
+ suggestionId,
3851
+ running > 0 ? `The suggestion did not answer within ${seconds}s, and the server last reported the turn as still running.` : `The suggestion did not answer within ${seconds}s.`
3852
+ );
3853
+ }
3854
+ const attempt = AbortSignal.timeout(Math.min(attemptMs, left));
3855
+ sends += 1;
3856
+ let backoff = 0;
3857
+ try {
3858
+ const answered = await client.request({
3859
+ method: "POST",
3860
+ path: resourcePath(input.site, ["suggestions", suggestionId, "session"]),
3861
+ body: body.data,
3862
+ signal: input.signal === void 0 ? attempt : AbortSignal.any([attempt, input.signal]),
3863
+ deadlineMs: left
3864
+ });
3865
+ unreachable = 0;
3866
+ if (answered.status !== 202) {
3867
+ response = answered;
3868
+ break;
3869
+ }
3870
+ const receipt = PendingTurn.safeParse(answered.data);
3871
+ if (!receipt.success || receipt.data.turnId !== `portal:${body.data.turn_id}`) unreadableTurn(suggestionId);
3872
+ running += 1;
3873
+ backoff = Math.min(MAX_REPLAY_BACKOFF_MS, RUNNING_BACKOFF_MS * 2 ** (running - 1));
3874
+ } catch (cause) {
3875
+ if (cancelled() || !isManagementError(cause)) throw cause;
3876
+ if (cause.detail.code === "unknown_outcome") unreadableTurn(suggestionId);
3877
+ if (cause.detail.code !== "transport_failure" && !(attempt.aborted && cause.detail.code === "interrupted")) throw cause;
3878
+ if (!attempt.aborted && remaining() > 0) {
3879
+ unreachable += 1;
3880
+ if (unreachable >= MAX_UNREACHABLE_SENDS) {
3881
+ unansweredTurn(suggestionId, `The session route could not be reached after ${unreachable} tries in a row: ${cause.detail.message}`);
3882
+ }
3883
+ backoff = UNREACHABLE_BACKOFF_MS * 2 ** (unreachable - 1);
3884
+ }
3885
+ }
3886
+ const wait = Math.min(backoff, remaining());
3887
+ if (wait > 0) {
3888
+ try {
3889
+ await sleep(wait, input.signal ?? new AbortController().signal);
3890
+ } catch (cause) {
3891
+ if (cancelled()) throw interrupted("unknown");
3892
+ throw cause;
3893
+ }
3894
+ }
3895
+ }
3249
3896
  const parsed = SessionResponse2.safeParse(response.data);
3250
3897
  if (!parsed.success) unreadableTurn(suggestionId);
3251
3898
  const outcome = parsed.data;
@@ -3502,10 +4149,19 @@ export {
3502
4149
  CLIENT_ERROR_CODES,
3503
4150
  CLIENT_ERROR_CATEGORIES,
3504
4151
  CLIENT_SCHEMA_VERSION,
4152
+ requiresManagementReceipt,
4153
+ invalidInput,
4154
+ isManagementError,
4155
+ grantFields,
4156
+ grantLimitation,
4157
+ omittedLimitations,
4158
+ labeledActors,
4159
+ activityGrantLimitations,
4160
+ suggestionListLimitations,
3505
4161
  GLOBAL_FLAGS,
3506
4162
  REQUEST_TEXT_LIMIT,
3507
- isManagementError,
3508
4163
  requireCommitSha,
4164
+ parseOrigin,
3509
4165
  createClient,
3510
4166
  resolveTarget,
3511
4167
  COMMAND_SCHEMA_VERSION,
@@ -3542,8 +4198,11 @@ export {
3542
4198
  suggestionWaitErrorCode,
3543
4199
  parseSuggestionWaitTarget,
3544
4200
  waitForSuggestion,
4201
+ checkedRequestThreadLimit,
3545
4202
  listRequestThreads,
3546
4203
  readRequestThread,
4204
+ requestGrantLimitations,
4205
+ rollbackRelease,
3547
4206
  checkedSubmissionId,
3548
4207
  checkedRequestText,
3549
4208
  createRequest,
@@ -3570,7 +4229,7 @@ export {
3570
4229
  applyGlobalFlagsDeep,
3571
4230
  resolveGlobalOptions,
3572
4231
  CliError,
3573
- invalidInput2 as invalidInput,
4232
+ invalidInput2,
3574
4233
  interrupted2 as interrupted,
3575
4234
  clientError2 as clientError,
3576
4235
  successResult,