@usesocial/cli 0.18.4 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3478,7 +3478,7 @@ const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9
3478
3478
  /** Returns a regex for validating an RFC 9562/4122 UUID.
3479
3479
  *
3480
3480
  * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
3481
- const uuid$1 = (version) => {
3481
+ const uuid$2 = (version) => {
3482
3482
  if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
3483
3483
  return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
3484
3484
  };
@@ -4048,8 +4048,8 @@ const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => {
4048
4048
  v8: 8
4049
4049
  }[def.version];
4050
4050
  if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
4051
- def.pattern ?? (def.pattern = uuid$1(v));
4052
- } else def.pattern ?? (def.pattern = uuid$1());
4051
+ def.pattern ?? (def.pattern = uuid$2(v));
4052
+ } else def.pattern ?? (def.pattern = uuid$2());
4053
4053
  $ZodStringFormat.init(inst, def);
4054
4054
  });
4055
4055
  const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => {
@@ -6877,6 +6877,9 @@ const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => {
6877
6877
  $ZodUUID.init(inst, def);
6878
6878
  ZodStringFormat.init(inst, def);
6879
6879
  });
6880
+ function uuid$1(params) {
6881
+ return /* @__PURE__ */ _uuid(ZodUUID, params);
6882
+ }
6880
6883
  const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
6881
6884
  $ZodURL.init(inst, def);
6882
6885
  ZodStringFormat.init(inst, def);
@@ -11046,6 +11049,14 @@ const CONNECTED_ACCOUNT_STATUSES = [
11046
11049
  "disconnected",
11047
11050
  "error"
11048
11051
  ];
11052
+ const ACCOUNT_CONNECT_ATTEMPT_LANES = ["provider", "legacy"];
11053
+ const ACCOUNT_CONNECT_ATTEMPT_STATUSES = [
11054
+ "pending_billing",
11055
+ "pending_approval",
11056
+ "connected",
11057
+ "expired",
11058
+ "failed"
11059
+ ];
11049
11060
  const PROXY_SURFACES = [
11050
11061
  "cli",
11051
11062
  "mcp",
@@ -11102,6 +11113,8 @@ const WEBHOOK_OPERATION_STATES = [
11102
11113
  ];
11103
11114
  _enum(PLATFORMS);
11104
11115
  _enum(CONNECTED_ACCOUNT_STATUSES);
11116
+ _enum(ACCOUNT_CONNECT_ATTEMPT_LANES);
11117
+ _enum(ACCOUNT_CONNECT_ATTEMPT_STATUSES);
11105
11118
  _enum(PROXY_SURFACES);
11106
11119
  _enum(PROXY_CACHE_STATUSES);
11107
11120
  _enum(PROXY_CAPABILITIES);
@@ -11293,6 +11306,33 @@ const connectedAccounts = pgTable("connected_accounts", {
11293
11306
  check("connected_accounts_platform_check", sqlCheckIn(table.platform, PLATFORMS)),
11294
11307
  check("connected_accounts_status_check", sqlCheckIn(table.status, CONNECTED_ACCOUNT_STATUSES))
11295
11308
  ]);
11309
+ pgTable("account_connect_attempts", {
11310
+ id: text$1("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
11311
+ userId: text$1("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
11312
+ platform: text$1("platform", { enum: PLATFORMS }).notNull(),
11313
+ lane: text$1("lane", { enum: ACCOUNT_CONNECT_ATTEMPT_LANES }).notNull(),
11314
+ targetPaidSeats: integer("target_paid_seats").notNull(),
11315
+ status: text$1("status", { enum: ACCOUNT_CONNECT_ATTEMPT_STATUSES }).notNull().default("pending_billing"),
11316
+ connectedAccountId: text$1("connected_account_id").references(() => connectedAccounts.id, { onDelete: "set null" }),
11317
+ operationKey: text$1("operation_key").notNull(),
11318
+ billingPaymentURL: text$1("billing_payment_url"),
11319
+ billingRequiredAction: jsonb("billing_required_action").$type(),
11320
+ hostedAuthBindingId: text$1("hosted_auth_binding_id"),
11321
+ hostedAuthAccountId: text$1("hosted_auth_account_id"),
11322
+ hostedAuthBoundAt: timestamptz("hosted_auth_bound_at"),
11323
+ expiresAt: timestamptz("expires_at").notNull(),
11324
+ createdAt: timestamptz("created_at").notNull().defaultNow(),
11325
+ updatedAt: timestamptz("updated_at").notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
11326
+ }, (table) => [
11327
+ uniqueIndex("account_connect_attempts_operation_key_key").on(table.operationKey),
11328
+ uniqueIndex("account_connect_attempts_hosted_auth_binding_id_key").on(table.hostedAuthBindingId),
11329
+ uniqueIndex("account_connect_attempts_active_user_platform_key").on(table.userId, table.platform).where(sql`${table.status} in ('pending_billing', 'pending_approval')`),
11330
+ index("account_connect_attempts_expiry_idx").on(table.expiresAt).where(sql`${table.status} in ('pending_billing', 'pending_approval')`),
11331
+ check("account_connect_attempts_platform_check", sqlCheckIn(table.platform, PLATFORMS)),
11332
+ check("account_connect_attempts_lane_check", sqlCheckIn(table.lane, ACCOUNT_CONNECT_ATTEMPT_LANES)),
11333
+ check("account_connect_attempts_status_check", sqlCheckIn(table.status, ACCOUNT_CONNECT_ATTEMPT_STATUSES)),
11334
+ check("account_connect_attempts_target_paid_seats_check", sql`${table.targetPaidSeats} >= 0`)
11335
+ ]);
11296
11336
  pgTable("account_defaults", {
11297
11337
  userId: text$1("user_id").notNull(),
11298
11338
  platform: text$1("platform", { enum: PLATFORMS }).notNull(),
@@ -11386,6 +11426,8 @@ pgTable("billing_overrides", {
11386
11426
  email: text$1("email").primaryKey(),
11387
11427
  userId: text$1("user_id").references(() => user.id, { onDelete: "cascade" }),
11388
11428
  seatAllowance: integer("seat_allowance").notNull().default(2),
11429
+ seatAllowanceLinkedin: integer("seat_allowance_linkedin").notNull().default(2),
11430
+ seatAllowanceX: integer("seat_allowance_x").notNull().default(2),
11389
11431
  monthlyUsageCredits: integer("monthly_usage_credits").notNull().default(6e4),
11390
11432
  reason: text$1("reason").notNull(),
11391
11433
  expiresAt: timestamptz("expires_at"),
@@ -11396,6 +11438,8 @@ pgTable("billing_overrides", {
11396
11438
  check("billing_overrides_email_lower_check", sql`lower(${table.email}) = ${table.email}`),
11397
11439
  check("billing_overrides_email_nonempty_check", sql`length(${table.email}) > 0`),
11398
11440
  check("billing_overrides_seat_allowance_check", sql`${table.seatAllowance} >= 0`),
11441
+ check("billing_overrides_seat_allowance_linkedin_check", sql`${table.seatAllowanceLinkedin} >= 0`),
11442
+ check("billing_overrides_seat_allowance_x_check", sql`${table.seatAllowanceX} >= 0`),
11399
11443
  check("billing_overrides_monthly_usage_credits_check", sql`${table.monthlyUsageCredits} >= 0`)
11400
11444
  ]);
11401
11445
  pgTable("proxy_call_logs", {
@@ -22674,11 +22718,6 @@ const LINKEDIN_CONNECTED_STATUS = "connected";
22674
22718
  var InvalidLinkedinLifecycleTarget = class extends h("InvalidLinkedinLifecycleTarget") {};
22675
22719
  var LinkedinLifecycleNoAccountMatch = class extends h("LinkedinLifecycleNoAccountMatch") {};
22676
22720
  var LinkedinLifecycleAmbiguousAccount = class extends h("LinkedinLifecycleAmbiguousAccount") {};
22677
- var LinkedinLifecycleSeatTimeout = class extends h("LinkedinLifecycleSeatTimeout") {
22678
- constructor() {
22679
- super({ message: "billing_seat_timed_out" });
22680
- }
22681
- };
22682
22721
  const accountUsername$1 = (account) => account.username.replace(/^@+/, "");
22683
22722
  const parseLinkedinReconnectTarget = (value) => {
22684
22723
  const trimmed = value.trim();
@@ -22739,41 +22778,16 @@ const resolveLinkedinDisconnectAccount = (accounts, identifier) => {
22739
22778
  const LINKEDIN_PLATFORM = "linkedin";
22740
22779
  const DEFAULT_POLL_INTERVAL_MS = 2e3;
22741
22780
  const DEFAULT_POLL_TIMEOUT_MS = 12e4;
22742
- const SEAT_POLL_TIMEOUT_MS$1 = 600 * 1e3;
22781
+ const CONNECT_POLL_TIMEOUT_MS = 600 * 1e3;
22743
22782
  const surfaceURL$1 = (deps, url, options = {}) => {
22744
22783
  const log = deps.log ?? console.error;
22745
22784
  if (options.log ?? true) log(`Open this URL: ${url}`);
22746
22785
  };
22747
- const pollForSeat$1 = async (deps) => {
22748
- const intervalMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
22749
- const sleep = deps.sleep ?? setTimeout$1;
22750
- const startedAt = Date.now();
22751
- while (Date.now() - startedAt < SEAT_POLL_TIMEOUT_MS$1) {
22752
- if ((await deps.client.billing.status()).canConnect) return;
22753
- await sleep(intervalMs);
22754
- }
22755
- throw new LinkedinLifecycleSeatTimeout();
22756
- };
22757
- const prepareAccountConnect$1 = async (deps) => {
22758
- if ((await deps.client.billing.status()).canConnect) return;
22759
- const status = await deps.client.billing.prepareAccountConnect();
22760
- if (status.canConnect) return;
22761
- if (status.paymentURL) surfaceURL$1(deps, status.paymentURL);
22762
- await pollForSeat$1(deps);
22763
- };
22764
22786
  const accountUsername = (account) => account.username.replace(/^@+/, "");
22765
22787
  const listLinkedinLifecycleAccounts = (deps, includeDisconnected = true) => deps.client.listAccounts({
22766
22788
  platform: LINKEDIN_PLATFORM,
22767
22789
  includeDisconnected
22768
22790
  });
22769
- /**
22770
- * Resolve the LinkedIn hosted-auth connect URL without opening a browser or
22771
- * polling. Lets a non-TTY caller advance a connect handshake one step at a time.
22772
- */
22773
- const createLinkedinConnectURL = async (deps) => (await deps.client.createHostedAuthURL({
22774
- platform: LINKEDIN_PLATFORM,
22775
- mode: "create"
22776
- })).url;
22777
22791
  const pollForAccount$1 = async (deps, predicate, errorMessage) => {
22778
22792
  const startedAt = Date.now();
22779
22793
  const timeoutMs = deps.pollTimeoutMs ?? DEFAULT_POLL_TIMEOUT_MS;
@@ -22791,8 +22805,15 @@ const authURLFor$1 = async (deps, operation) => ({
22791
22805
  openingLogged: deps.handshakeAuthURL !== void 0
22792
22806
  });
22793
22807
  const reconnectAccountForIdentifier = async (deps, identifier) => {
22794
- const account = resolveLinkedinLifecycleAccount(await listLinkedinLifecycleAccounts(deps), identifier);
22795
- if (ae.isError(account)) throw account.error;
22808
+ const accounts = await listLinkedinLifecycleAccounts(deps);
22809
+ const account = resolveLinkedinLifecycleAccount(accounts.filter((candidate) => candidate.status !== "disconnected"), identifier);
22810
+ if (ae.isError(account)) {
22811
+ if (LinkedinLifecycleNoAccountMatch.is(account.error)) {
22812
+ const disconnected = resolveLinkedinLifecycleAccount(accounts.filter((candidate) => candidate.status === "disconnected"), identifier);
22813
+ if (ae.isOk(disconnected)) throw new Error(`LinkedIn account @${accountUsername(disconnected.value)} is disconnected and its seat was released. Run \`social account connect linkedin\` to connect it again.`);
22814
+ }
22815
+ throw account.error;
22816
+ }
22796
22817
  return account.value;
22797
22818
  };
22798
22819
  const resolveDisconnectTarget = async (deps, identifier) => {
@@ -22800,21 +22821,32 @@ const resolveDisconnectTarget = async (deps, identifier) => {
22800
22821
  if (ae.isError(account)) throw account.error;
22801
22822
  return account.value;
22802
22823
  };
22803
- const connectLinkedinAccount = async (deps) => {
22804
- await prepareAccountConnect$1(deps);
22805
- const before = await listLinkedinLifecycleAccounts(deps);
22806
- const existingProfileIds = new Set(before.map((account) => account.profileId));
22807
- const authURL = await authURLFor$1(deps, async () => (await deps.client.createHostedAuthURL({
22808
- platform: LINKEDIN_PLATFORM,
22809
- mode: "create"
22810
- })).url);
22811
- surfaceURL$1(deps, authURL.url, { log: !authURL.openingLogged });
22812
- const account = await pollForAccount$1(deps, (candidate) => candidate.status === "connected" && !existingProfileIds.has(candidate.profileId), "Timed out waiting for a new LinkedIn account connection.");
22813
- return {
22814
- platform: LINKEDIN_PLATFORM,
22815
- status: "connected",
22816
- account
22817
- };
22824
+ const connectLinkedinAccount = async (deps, attemptId) => {
22825
+ const intervalMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
22826
+ const sleep = deps.sleep ?? setTimeout$1;
22827
+ const startedAt = Date.now();
22828
+ let currentAttemptId = attemptId;
22829
+ const surfacedURLs = /* @__PURE__ */ new Set();
22830
+ while (Date.now() - startedAt < CONNECT_POLL_TIMEOUT_MS) {
22831
+ const state = await deps.client.connectStep({
22832
+ platform: LINKEDIN_PLATFORM,
22833
+ ...currentAttemptId ? { attemptId: currentAttemptId } : {}
22834
+ });
22835
+ currentAttemptId = state.attemptId;
22836
+ if (state.status === "connected") return {
22837
+ platform: LINKEDIN_PLATFORM,
22838
+ status: "connected",
22839
+ account: state.account
22840
+ };
22841
+ if (state.status === "expired" || state.status === "failed") throw new Error(state.code);
22842
+ const url = state.status === "pending_billing" ? state.paymentURL : state.status === "pending_approval" ? state.connectURL : null;
22843
+ if (url && !surfacedURLs.has(url)) {
22844
+ surfacedURLs.add(url);
22845
+ surfaceURL$1(deps, url);
22846
+ } else if (state.status === "pending_billing" && state.requiredAction) deps.log?.(state.requiredAction.reason);
22847
+ await sleep(intervalMs);
22848
+ }
22849
+ throw new Error("linkedin_connect_timed_out");
22818
22850
  };
22819
22851
  const reconnectLinkedinAccount = async (deps, identifier) => {
22820
22852
  const account = await reconnectAccountForIdentifier(deps, identifier);
@@ -22846,7 +22878,6 @@ const disconnectLinkedinAccount = async (deps, identifier) => {
22846
22878
  //#endregion
22847
22879
  //#region ../../packages/x/src/cli/lifecycle.ts
22848
22880
  const CONNECT_TIMEOUT_MS = 300 * 1e3;
22849
- const SEAT_POLL_TIMEOUT_MS = 600 * 1e3;
22850
22881
  const POLL_INTERVAL_MS = 2 * 1e3;
22851
22882
  var XConnectTimedOut = class extends h("XConnectTimedOut") {
22852
22883
  constructor(args) {
@@ -22857,14 +22888,14 @@ var XConnectTimedOut = class extends h("XConnectTimedOut") {
22857
22888
  this.name = "XConnectTimedOut";
22858
22889
  }
22859
22890
  };
22860
- var XBillingSeatTimedOut = class extends h("XBillingSeatTimedOut") {
22861
- constructor() {
22891
+ var XConnectStepFailed = class extends h("XConnectStepFailed") {
22892
+ constructor(args) {
22862
22893
  super({
22863
- operation: "prepareAccountConnect",
22864
- timeoutMS: SEAT_POLL_TIMEOUT_MS,
22865
- message: "billing_seat_timed_out"
22894
+ operation: "connect",
22895
+ ...args,
22896
+ message: args.code
22866
22897
  });
22867
- this.name = "XBillingSeatTimedOut";
22898
+ this.name = "XConnectStepFailed";
22868
22899
  }
22869
22900
  };
22870
22901
  var XAccountNotFound = class extends h("XAccountNotFound") {
@@ -22876,6 +22907,16 @@ var XAccountNotFound = class extends h("XAccountNotFound") {
22876
22907
  this.name = "XAccountNotFound";
22877
22908
  }
22878
22909
  };
22910
+ var XReconnectRequiresConnect = class extends h("XReconnectRequiresConnect") {
22911
+ constructor(account) {
22912
+ super({
22913
+ operation: "reconnect",
22914
+ account,
22915
+ message: `X account ${account} is disconnected and its seat was released. Run \`social account connect x\` to connect it again.`
22916
+ });
22917
+ this.name = "XReconnectRequiresConnect";
22918
+ }
22919
+ };
22879
22920
  var XInvalidSelector = class extends h("XInvalidSelector") {
22880
22921
  constructor(args) {
22881
22922
  super({
@@ -22895,11 +22936,11 @@ const throwXLifecycleError = (error) => {
22895
22936
  const defaultSleep = async (ms) => {
22896
22937
  await new Promise((resolve) => setTimeout(resolve, ms));
22897
22938
  };
22898
- const connectURLFor = async (deps, reconnectProfileId) => {
22939
+ const reconnectURLFor = async (deps, reconnectProfileId) => {
22899
22940
  return (await deps.client.accounts.reconnectURL({
22900
22941
  platform: "x",
22901
- mode: reconnectProfileId ? "reconnect" : "create",
22902
- ...reconnectProfileId ? { account: `profile_id:${reconnectProfileId}` } : {}
22942
+ mode: "reconnect",
22943
+ account: `profile_id:${reconnectProfileId}`
22903
22944
  })).url;
22904
22945
  };
22905
22946
  const surfaceURL = (deps, url, options = {}) => {
@@ -22927,25 +22968,6 @@ const authURLFor = async (deps, operation) => ({
22927
22968
  url: deps.handshakeAuthURL ? await deps.handshakeAuthURL(operation) : await operation(),
22928
22969
  openingLogged: deps.handshakeAuthURL !== void 0
22929
22970
  });
22930
- const pollForSeat = async (deps) => {
22931
- const sleep = deps.sleep ?? defaultSleep;
22932
- const now = deps.now ?? Date.now;
22933
- const startedAt = now();
22934
- while (now() - startedAt < SEAT_POLL_TIMEOUT_MS) {
22935
- if ((await deps.client.billing.status()).canConnect) return ae.ok();
22936
- await sleep(POLL_INTERVAL_MS);
22937
- }
22938
- return ae.err(new XBillingSeatTimedOut());
22939
- };
22940
- const prepareAccountConnect = async (deps) => {
22941
- if ((await deps.client.billing.status()).canConnect) return ae.ok();
22942
- const status = await deps.client.billing.prepareAccountConnect();
22943
- if (status.canConnect) return ae.ok();
22944
- if (status.paymentURL) surfaceURL(deps, status.paymentURL);
22945
- return pollForSeat(deps);
22946
- };
22947
- const accountKey = (account) => account.profileId;
22948
- const timestampMS = (value) => value instanceof Date ? value.getTime() : void 0;
22949
22971
  const normalizeIdentifier = (value) => value.trim().replace(/^@+/, "").toLowerCase();
22950
22972
  const accountSelectorFor$1 = (account) => account.username ? `@${account.username.replace(/^@+/, "")}` : `profile_id:${account.profileId}`;
22951
22973
  const parseXAccountSelector = (target, operation) => {
@@ -22976,34 +22998,35 @@ const listXLifecycleAccounts = async (deps, includeDisconnected) => ae.ok(await
22976
22998
  platform: "x",
22977
22999
  includeDisconnected
22978
23000
  }));
22979
- /**
22980
- * Resolve the X connect/reconnect URL without opening a browser or polling.
22981
- * Lets a non-TTY caller advance a connect handshake one step at a time.
22982
- */
22983
- const createXConnectURL = (deps, reconnectProfileId) => connectURLFor(deps, reconnectProfileId);
22984
- const connectXAccount = async (deps) => {
22985
- const beforeResult = await listXLifecycleAccounts(deps, true);
22986
- if (ae.isError(beforeResult)) return ae.err(beforeResult.error);
22987
- const before = beforeResult.value;
22988
- const connectedBefore = new Set(before.filter((account) => account.status === "connected").map(accountKey));
22989
- const lastSeenBefore = new Map(before.filter((account) => account.status === "connected").map((account) => [accountKey(account), timestampMS(account.lastSeenAt)]));
22990
- const prepared = await prepareAccountConnect(deps);
22991
- if (ae.isError(prepared)) return ae.err(prepared.error);
22992
- const authURL = await authURLFor(deps, () => connectURLFor(deps));
22993
- surfaceURL(deps, authURL.url, { log: !authURL.openingLogged });
22994
- const account = await pollForAccount(deps, "connect", (candidate) => {
22995
- if (candidate.status !== "connected") return false;
22996
- if (!connectedBefore.has(candidate.profileId)) return true;
22997
- const previousLastSeen = lastSeenBefore.get(candidate.profileId);
22998
- const currentLastSeen = timestampMS(candidate.lastSeenAt);
22999
- return previousLastSeen !== void 0 && currentLastSeen !== void 0 && currentLastSeen > previousLastSeen;
23000
- });
23001
- if (ae.isError(account)) return ae.err(account.error);
23002
- return ae.ok({
23003
- platform: "x",
23004
- status: "connected",
23005
- account: account.value
23006
- });
23001
+ const connectXAccount = async (deps, attemptId) => {
23002
+ const sleep = deps.sleep ?? defaultSleep;
23003
+ const now = deps.now ?? Date.now;
23004
+ const startedAt = now();
23005
+ let currentAttemptId = attemptId;
23006
+ const surfacedURLs = /* @__PURE__ */ new Set();
23007
+ while (now() - startedAt < CONNECT_TIMEOUT_MS) {
23008
+ const state = await deps.client.connectStep({
23009
+ platform: "x",
23010
+ ...currentAttemptId ? { attemptId: currentAttemptId } : {}
23011
+ });
23012
+ currentAttemptId = state.attemptId;
23013
+ if (state.status === "connected") return ae.ok({
23014
+ platform: "x",
23015
+ status: "connected",
23016
+ account: state.account
23017
+ });
23018
+ if (state.status === "expired" || state.status === "failed") return ae.err(new XConnectStepFailed(state));
23019
+ const url = state.status === "pending_billing" ? state.paymentURL : state.status === "pending_approval" ? state.connectURL : null;
23020
+ if (url && !surfacedURLs.has(url)) {
23021
+ surfacedURLs.add(url);
23022
+ surfaceURL(deps, url);
23023
+ } else if (state.status === "pending_billing" && state.requiredAction) deps.log?.(state.requiredAction.reason);
23024
+ await sleep(POLL_INTERVAL_MS);
23025
+ }
23026
+ return ae.err(new XConnectTimedOut({
23027
+ operation: "connect",
23028
+ timeoutMS: CONNECT_TIMEOUT_MS
23029
+ }));
23007
23030
  };
23008
23031
  const reconnectXAccount = async (deps, args) => {
23009
23032
  const selector = parseXAccountSelector(args.account, "reconnect");
@@ -23011,12 +23034,15 @@ const reconnectXAccount = async (deps, args) => {
23011
23034
  const accountsResult = await listXLifecycleAccounts(deps, true);
23012
23035
  if (ae.isError(accountsResult)) return ae.err(accountsResult.error);
23013
23036
  const accounts = accountsResult.value;
23014
- const existing = findXLifecycleAccount(accounts, selector.value);
23015
- if (!existing) return ae.err(new XAccountNotFound({
23016
- operation: "reconnect",
23017
- account: args.account
23018
- }));
23019
- const authURL = await authURLFor(deps, () => connectURLFor(deps, existing.profileId));
23037
+ const existing = findXLifecycleAccount(accounts.filter((account) => account.status !== "disconnected"), selector.value);
23038
+ if (!existing) {
23039
+ if (findXLifecycleAccount(accounts.filter((account) => account.status === "disconnected"), selector.value)) return ae.err(new XReconnectRequiresConnect(args.account));
23040
+ return ae.err(new XAccountNotFound({
23041
+ operation: "reconnect",
23042
+ account: args.account
23043
+ }));
23044
+ }
23045
+ const authURL = await authURLFor(deps, () => reconnectURLFor(deps, existing.profileId));
23020
23046
  surfaceURL(deps, authURL.url, { log: !authURL.openingLogged });
23021
23047
  const account = await pollForAccount(deps, "reconnect", (candidate) => candidate.profileId === existing.profileId && candidate.status === "connected");
23022
23048
  if (ae.isError(account)) return ae.err(account.error);
@@ -24448,7 +24474,7 @@ function createEnv(opts) {
24448
24474
  }
24449
24475
  //#endregion
24450
24476
  //#region package.json
24451
- var version$1 = "0.18.4";
24477
+ var version$1 = "0.19.1";
24452
24478
  //#endregion
24453
24479
  //#region src/lib/env.ts
24454
24480
  const URLWithTrailingSlash = url().transform(ensureTrailingSlash);
@@ -25575,23 +25601,39 @@ const configCommand = defineCommand({
25575
25601
  })
25576
25602
  }
25577
25603
  });
25578
- const BillingOutput = object({
25579
- seats: object({
25580
- total: number().int().nonnegative(),
25581
- used: number().int().nonnegative(),
25582
- available: number().int().nonnegative()
25583
- }),
25584
- subscription: object({
25585
- active: boolean$1(),
25586
- quantity: number().int().nonnegative(),
25587
- currentPeriodEnd: string().nullable()
25588
- }).nullable(),
25589
- usage: object({
25590
- calls: number().int().nonnegative(),
25591
- credit: number().nonnegative(),
25592
- cost: number().nonnegative()
25593
- })
25604
+ //#endregion
25605
+ //#region src/billing/index.ts
25606
+ const SeatsOutput = object({
25607
+ total: number().int().nonnegative(),
25608
+ used: number().int().nonnegative(),
25609
+ available: number().int().nonnegative()
25594
25610
  });
25611
+ const SubscriptionOutput = object({
25612
+ active: boolean$1(),
25613
+ quantity: number().int().nonnegative(),
25614
+ currentPeriodEnd: string().nullable(),
25615
+ canceling: boolean$1(),
25616
+ canceledAt: string().nullable()
25617
+ }).nullable();
25618
+ const UsageSummaryOutput$1 = object({
25619
+ calls: number().int().nonnegative(),
25620
+ credit: number().nonnegative(),
25621
+ cost: number().nonnegative()
25622
+ });
25623
+ const ProviderBillingOutput = object({
25624
+ platform: _enum(["linkedin", "x"]),
25625
+ plan: object({
25626
+ id: string(),
25627
+ name: string()
25628
+ }),
25629
+ seats: SeatsOutput,
25630
+ canConnect: boolean$1(),
25631
+ subscription: SubscriptionOutput
25632
+ });
25633
+ const BillingOutput = object({ providers: object({
25634
+ linkedin: ProviderBillingOutput,
25635
+ x: ProviderBillingOutput.extend({ usage: UsageSummaryOutput$1 })
25636
+ }) });
25595
25637
  const BillingPortalOutput = object({
25596
25638
  url: string(),
25597
25639
  opened: boolean$1()
@@ -25637,11 +25679,13 @@ const createBillingCommand = (deps = {}) => {
25637
25679
  run: async () => {
25638
25680
  const client = clientFrom(deps);
25639
25681
  const [status, usage] = await Promise.all([client.billing.status(), client.usage.summary({})]);
25640
- await writeOutput$2(deps, {
25641
- seats: status.seats,
25642
- subscription: status.subscription,
25643
- usage: usageSummaryForOutput(usage)
25644
- });
25682
+ await writeOutput$2(deps, { providers: {
25683
+ linkedin: status.providers.linkedin,
25684
+ x: {
25685
+ ...status.providers.x,
25686
+ usage: usageSummaryForOutput(usage)
25687
+ }
25688
+ } });
25645
25689
  }
25646
25690
  });
25647
25691
  };
@@ -33067,13 +33111,9 @@ const errorOutput = (error) => ({
33067
33111
  message: error instanceof Error ? error.message : String(error)
33068
33112
  });
33069
33113
  const nextCommands = ["social account connect linkedin", "social account connect x"];
33070
- const availableConnectCommands = (capabilities) => nextCommands.filter((command) => {
33071
- const platform = command.endsWith(" linkedin") ? "linkedin" : "x";
33072
- return capabilities.some((capability) => capability.startsWith(`${platform}:`));
33073
- });
33074
33114
  const setupOutputFor = (setup) => ({
33075
33115
  ...setup,
33076
- nextCommands: setup.status === "pending_billing" ? ["social account setup"] : availableConnectCommands(setup.capabilities)
33116
+ nextCommands: setup.status === "pending_billing" ? ["social account setup"] : nextCommands
33077
33117
  });
33078
33118
  const deviceExpiredMessage = "Sign-in expired before approval. Run `social account setup` again to restart.";
33079
33119
  const scopeUpgradeRequiresReauthorization = "Existing CLI session is read-only. Run `social account logout`, then `social account setup` to approve a new write-capable session.";
@@ -33160,7 +33200,7 @@ const createLoginCommand = (deps = {}) => {
33160
33200
  return defineCommand({
33161
33201
  meta: commandMeta({
33162
33202
  name: "setup",
33163
- description: "Authenticate Social and ensure billing is ready",
33203
+ description: "Authenticate Social and add a reusable payment method before connecting accounts",
33164
33204
  contract: localCLIContract({
33165
33205
  auth: {
33166
33206
  interactive: true,
@@ -33235,11 +33275,7 @@ const createLoginCommand = (deps = {}) => {
33235
33275
  }
33236
33276
  if (output.status === "ready") {
33237
33277
  analytics.identifyUser(output.user.id);
33238
- analytics.capture("login_completed", {
33239
- scope: output.scope,
33240
- seats_total: output.seats.total,
33241
- seats_available: output.seats.available
33242
- });
33278
+ analytics.capture("login_completed", { scope: output.scope });
33243
33279
  } else if (output.status === "expired") analytics.capture("login_failed", { code: "expired" });
33244
33280
  else if (output.status === "needs_input") analytics.capture("login_failed", {
33245
33281
  code: "needs_input",
@@ -33592,12 +33628,18 @@ const AccountDefaultSetInput = AccountDefaultGetInput.extend({ account: string()
33592
33628
  const AccountConnectStateOutput = discriminatedUnion("status", [
33593
33629
  object({
33594
33630
  status: literal("connected"),
33631
+ attemptId: uuid$1(),
33595
33632
  platform: _enum(["linkedin", "x"]),
33596
33633
  account: LifecycleAccountOutput
33597
33634
  }),
33598
33635
  object({
33599
33636
  status: literal("pending_billing"),
33637
+ attemptId: uuid$1(),
33600
33638
  platform: _enum(["linkedin", "x"]),
33639
+ plan: object({
33640
+ id: string(),
33641
+ name: string()
33642
+ }),
33601
33643
  paymentURL: string().nullable(),
33602
33644
  requiredAction: object({
33603
33645
  code: string(),
@@ -33611,8 +33653,17 @@ const AccountConnectStateOutput = discriminatedUnion("status", [
33611
33653
  }),
33612
33654
  object({
33613
33655
  status: literal("pending_approval"),
33656
+ attemptId: uuid$1(),
33657
+ platform: _enum(["linkedin", "x"]),
33658
+ connectURL: string().nullable(),
33659
+ expiresAt: string()
33660
+ }),
33661
+ object({
33662
+ status: _enum(["expired", "failed"]),
33663
+ attemptId: uuid$1(),
33614
33664
  platform: _enum(["linkedin", "x"]),
33615
- connectURL: string()
33665
+ code: string(),
33666
+ retryable: boolean$1()
33616
33667
  })
33617
33668
  ]);
33618
33669
  const AccountConnectOutput = union([string(), AccountConnectStateOutput]);
@@ -33702,7 +33753,15 @@ const platformLabel = (platform) => platform === "x" ? "X" : "LinkedIn";
33702
33753
  const lifecycleConnectContract = writeCLIContract({
33703
33754
  outputSchema: AccountConnectOutput,
33704
33755
  responseShaping: { supported: false },
33705
- idempotency: "non-idempotent"
33756
+ idempotency: {
33757
+ idempotent: false,
33758
+ retrySafeWith: "attemptId"
33759
+ },
33760
+ idField: "attemptId",
33761
+ hazards: [{
33762
+ code: "account_connect_billing",
33763
+ message: "The first call can start provider billing; pass the returned attemptId when polling so retries cannot start another charge."
33764
+ }]
33706
33765
  });
33707
33766
  const usernameLabelFor = (account) => account.username.startsWith("@") ? account.username : `@${account.username}`;
33708
33767
  const authHandshakeMessage = "Handshaking auth...";
@@ -33733,43 +33792,13 @@ const runConnectOutput = async (deps, connect) => {
33733
33792
  writeText(deps, `${usernameLabelFor(result.account)} connected!`);
33734
33793
  };
33735
33794
  const isInteractiveConnect = (deps) => deps.isInteractiveTerminal?.() === true;
33736
- /**
33737
- * One non-blocking step of a connect handshake for a non-TTY caller. Returns the
33738
- * connected account if one is already linked, otherwise emits the connect URL and
33739
- * reports `pending_approval`. A repeated call re-checks and advances — the skill
33740
- * polls this the same way it polls `social account setup`.
33741
- */
33742
- const runConnectStep = async (deps, platform, listConnected, connectURL) => {
33743
- const connected = (await listConnected()).find((account) => account.status === "connected");
33744
- if (connected) {
33745
- await writeOutput(deps, {
33746
- status: "connected",
33747
- platform,
33748
- account: connected
33749
- });
33750
- return;
33751
- }
33752
- const billing = await deps.client.billing.prepareAccountConnect();
33753
- if (!billing.canConnect) {
33754
- if (!billing.seats) throw new Error("billing_prepare_missing_seats");
33755
- if (billing.paymentURL) writeText(deps, `Open this URL: ${billing.paymentURL}`);
33756
- else if (billing.requiredAction) writeText(deps, billing.requiredAction.reason);
33757
- await writeOutput(deps, {
33758
- status: "pending_billing",
33759
- platform,
33760
- paymentURL: billing.paymentURL ?? null,
33761
- requiredAction: billing.requiredAction ?? null,
33762
- seats: billing.seats
33763
- });
33764
- return;
33765
- }
33766
- const url = await connectURL();
33767
- writeText(deps, `Open this URL: ${url}`);
33768
- await writeOutput(deps, {
33769
- status: "pending_approval",
33795
+ /** One retry-safe connect step for a non-TTY caller; the JSON carries its next attempt ID. */
33796
+ const runConnectStep = async (deps, platform, attemptId) => {
33797
+ const state = await deps.client.connectStep({
33770
33798
  platform,
33771
- connectURL: url
33799
+ ...attemptId ? { attemptId } : {}
33772
33800
  });
33801
+ await writeOutput(deps, state);
33773
33802
  };
33774
33803
  const createConnectPlatformCommand = (platform, run) => defineCommand({
33775
33804
  meta: commandMeta({
@@ -33779,8 +33808,12 @@ const createConnectPlatformCommand = (platform, run) => defineCommand({
33779
33808
  contract: lifecycleConnectContract,
33780
33809
  mutates: true
33781
33810
  }),
33782
- run: async () => {
33783
- await run();
33811
+ args: { attempt: {
33812
+ type: "string",
33813
+ description: "Resume the exact connect attempt returned by a previous call."
33814
+ } },
33815
+ run: async ({ args }) => {
33816
+ await run({ attempt: typeof args.attempt === "string" ? args.attempt : void 0 });
33784
33817
  }
33785
33818
  });
33786
33819
  const createAccountPlatformCommand = (platform, description, run, options = {}) => defineCommand({
@@ -33866,27 +33899,23 @@ const createAccountCommand = (deps, accountSetupCommand = setupCommand) => {
33866
33899
  description: "Connect a LinkedIn or X account."
33867
33900
  },
33868
33901
  subCommands: {
33869
- linkedin: createConnectPlatformCommand("linkedin", async () => {
33902
+ linkedin: createConnectPlatformCommand("linkedin", async ({ attempt }) => {
33870
33903
  if (isInteractiveConnect(deps)) {
33871
- await runConnectOutput(deps, connectLinkedinAccount);
33904
+ await runConnectOutput(deps, (connectDeps) => connectLinkedinAccount(connectDeps, attempt));
33872
33905
  return;
33873
33906
  }
33874
- await runConnectStep(deps, "linkedin", () => listLinkedinLifecycleAccounts(deps), () => createLinkedinConnectURL(deps));
33907
+ await runConnectStep(deps, "linkedin", attempt);
33875
33908
  }),
33876
- x: createConnectPlatformCommand("x", async () => {
33909
+ x: createConnectPlatformCommand("x", async ({ attempt }) => {
33877
33910
  if (isInteractiveConnect(deps)) {
33878
33911
  await runConnectOutput(deps, async (connectDeps) => {
33879
- const result = await connectXAccount(connectDeps);
33912
+ const result = await connectXAccount(connectDeps, attempt);
33880
33913
  if (ae.isError(result)) throwXLifecycleError(result.error);
33881
33914
  return result.value;
33882
33915
  });
33883
33916
  return;
33884
33917
  }
33885
- await runConnectStep(deps, "x", async () => {
33886
- const result = await listXLifecycleAccounts(deps, true);
33887
- if (ae.isError(result)) throwXLifecycleError(result.error);
33888
- return result.value;
33889
- }, () => createXConnectURL(deps));
33918
+ await runConnectStep(deps, "x", attempt);
33890
33919
  })
33891
33920
  }
33892
33921
  });
@@ -39237,25 +39266,19 @@ const createCLIDeps = () => {
39237
39266
  client: {
39238
39267
  listAccounts: client.accounts.list,
39239
39268
  createHostedAuthURL: client.accounts.reconnectURL,
39269
+ connectStep: client.accounts.connectStep,
39240
39270
  disconnectAccount: client.accounts.disconnect,
39241
39271
  accounts: {
39242
39272
  list: client.accounts.list,
39243
39273
  default: client.accounts.default,
39274
+ connectStep: client.accounts.connectStep,
39244
39275
  reconnectURL: client.accounts.reconnectURL,
39245
39276
  disconnect: client.accounts.disconnect
39246
39277
  },
39247
39278
  billing: {
39248
- status: async () => {
39249
- return await client.billing.status();
39250
- },
39251
- prepareAccountConnect: async () => {
39252
- const status = await client.billing.prepareAccountConnect();
39253
- return {
39254
- canConnect: status.canConnect,
39255
- paymentURL: status.paymentURL,
39256
- requiredAction: status.requiredAction,
39257
- seats: status.seats
39258
- };
39279
+ status: client.billing.status,
39280
+ providerStatus: async ({ platform }) => {
39281
+ return (await client.billing.status()).providers[platform];
39259
39282
  },
39260
39283
  portalURL: client.billing.portalURL
39261
39284
  },