@usesocial/cli 0.18.0 → 0.18.2

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
@@ -454,7 +454,7 @@ const productBrand = {
454
454
  const brand = {
455
455
  org,
456
456
  name: productBrand.name,
457
- tagline: "Let your agent run LinkedIn & X for you",
457
+ tagline: "Agentic founder-led distribution",
458
458
  description: productBrand.description
459
459
  };
460
460
  const brandURLs = {
@@ -15677,6 +15677,16 @@ const buildSql$1 = (deps, platform) => defineCommand({
15677
15677
  }
15678
15678
  }
15679
15679
  });
15680
+ const patchChatReadStatus = async (deps, chatId, headers, read) => {
15681
+ const response = await deps.api.patch("linkedin/chats/".concat(encodeURIComponent(chatId)), {
15682
+ headers,
15683
+ json: { read_status: read }
15684
+ });
15685
+ return {
15686
+ data: await response.json(),
15687
+ response
15688
+ };
15689
+ };
15680
15690
  const buildMark = (deps) => {
15681
15691
  const schemaContract = {
15682
15692
  inputSchema: schemas$1.MessagesMarkInput,
@@ -15767,11 +15777,7 @@ const buildMark = (deps) => {
15767
15777
  });
15768
15778
  const accountIdHeader = selectedAccount.selector;
15769
15779
  const headers = { ...accountIdHeader === void 0 ? {} : { "x-social-account-id": accountIdHeader } };
15770
- const response = await deps.api.patch("linkedin/chats/".concat(encodeURIComponent(chat_id)), {
15771
- headers,
15772
- json: { read_status: input.status === "read" }
15773
- });
15774
- const data = await response.json();
15780
+ const { data, response } = await patchChatReadStatus(deps, chat_id, headers, input.status === "read");
15775
15781
  await deps.printResult({
15776
15782
  account: selectedAccount,
15777
15783
  contract: schemaContractFrom(cmd),
@@ -16286,6 +16292,7 @@ const buildMessage$1 = (deps, sendCommand) => {
16286
16292
  const data = await response.json();
16287
16293
  const messageId = responseStringOrFirst(data, ["message_id"]);
16288
16294
  const chatId = classified.kind === "thread" ? classified.id : responseString$1(data, ["chat_id", "id"]);
16295
+ if (responseSucceeded$1(response) && chatId !== void 0) await patchChatReadStatus(deps, chatId, headers, true);
16289
16296
  if (responseSucceeded$1(response) && messageId !== void 0 && chatId !== void 0) {
16290
16297
  const ownAccountId = requireAccountSelector$1(own.accountIdHeader);
16291
16298
  writeThroughLinkedinCache({
@@ -22594,16 +22601,16 @@ const resolveLinkedinDisconnectAccount = (accounts, identifier) => {
22594
22601
  const LINKEDIN_PLATFORM = "linkedin";
22595
22602
  const DEFAULT_POLL_INTERVAL_MS = 2e3;
22596
22603
  const DEFAULT_POLL_TIMEOUT_MS = 12e4;
22597
- const SEAT_POLL_TIMEOUT_MS$2 = 600 * 1e3;
22604
+ const SEAT_POLL_TIMEOUT_MS$1 = 600 * 1e3;
22598
22605
  const surfaceURL$1 = (deps, url, options = {}) => {
22599
22606
  const log = deps.log ?? console.error;
22600
22607
  if (options.log ?? true) log(`Open this URL: ${url}`);
22601
22608
  };
22602
- const pollForSeat$2 = async (deps) => {
22609
+ const pollForSeat$1 = async (deps) => {
22603
22610
  const intervalMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
22604
22611
  const sleep = deps.sleep ?? setTimeout$1;
22605
22612
  const startedAt = Date.now();
22606
- while (Date.now() - startedAt < SEAT_POLL_TIMEOUT_MS$2) {
22613
+ while (Date.now() - startedAt < SEAT_POLL_TIMEOUT_MS$1) {
22607
22614
  if ((await deps.client.billing.status()).canConnect) return;
22608
22615
  await sleep(intervalMs);
22609
22616
  }
@@ -22614,7 +22621,7 @@ const prepareAccountConnect$1 = async (deps) => {
22614
22621
  const status = await deps.client.billing.prepareAccountConnect();
22615
22622
  if (status.canConnect) return;
22616
22623
  if (status.paymentURL) surfaceURL$1(deps, status.paymentURL);
22617
- await pollForSeat$2(deps);
22624
+ await pollForSeat$1(deps);
22618
22625
  };
22619
22626
  const accountUsername = (account) => account.username.replace(/^@+/, "");
22620
22627
  const listLinkedinLifecycleAccounts = (deps, includeDisconnected = true) => deps.client.listAccounts({
@@ -22701,7 +22708,7 @@ const disconnectLinkedinAccount = async (deps, identifier) => {
22701
22708
  //#endregion
22702
22709
  //#region ../../packages/x/src/cli/lifecycle.ts
22703
22710
  const CONNECT_TIMEOUT_MS = 300 * 1e3;
22704
- const SEAT_POLL_TIMEOUT_MS$1 = 600 * 1e3;
22711
+ const SEAT_POLL_TIMEOUT_MS = 600 * 1e3;
22705
22712
  const POLL_INTERVAL_MS = 2 * 1e3;
22706
22713
  var XConnectTimedOut = class extends h("XConnectTimedOut")() {
22707
22714
  constructor(args) {
@@ -22716,7 +22723,7 @@ var XBillingSeatTimedOut = class extends h("XBillingSeatTimedOut")() {
22716
22723
  constructor() {
22717
22724
  super({
22718
22725
  operation: "prepareAccountConnect",
22719
- timeoutMS: SEAT_POLL_TIMEOUT_MS$1,
22726
+ timeoutMS: SEAT_POLL_TIMEOUT_MS,
22720
22727
  message: "billing_seat_timed_out"
22721
22728
  });
22722
22729
  this.name = "XBillingSeatTimedOut";
@@ -22784,11 +22791,11 @@ const authURLFor = async (deps, operation) => ({
22784
22791
  url: deps.handshakeAuthURL ? await deps.handshakeAuthURL(operation) : await operation(),
22785
22792
  openingLogged: deps.handshakeAuthURL !== void 0
22786
22793
  });
22787
- const pollForSeat$1 = async (deps) => {
22794
+ const pollForSeat = async (deps) => {
22788
22795
  const sleep = deps.sleep ?? defaultSleep;
22789
22796
  const now = deps.now ?? Date.now;
22790
22797
  const startedAt = now();
22791
- while (now() - startedAt < SEAT_POLL_TIMEOUT_MS$1) {
22798
+ while (now() - startedAt < SEAT_POLL_TIMEOUT_MS) {
22792
22799
  if ((await deps.client.billing.status()).canConnect) return G.ok();
22793
22800
  await sleep(POLL_INTERVAL_MS);
22794
22801
  }
@@ -22799,7 +22806,7 @@ const prepareAccountConnect = async (deps) => {
22799
22806
  const status = await deps.client.billing.prepareAccountConnect();
22800
22807
  if (status.canConnect) return G.ok();
22801
22808
  if (status.paymentURL) surfaceURL(deps, status.paymentURL);
22802
- return pollForSeat$1(deps);
22809
+ return pollForSeat(deps);
22803
22810
  };
22804
22811
  const accountKey = (account) => account.profileId;
22805
22812
  const timestampMS = (value) => value instanceof Date ? value.getTime() : void 0;
@@ -24265,7 +24272,7 @@ function createEnv(opts) {
24265
24272
  }
24266
24273
  //#endregion
24267
24274
  //#region package.json
24268
- var version$1 = "0.18.0";
24275
+ var version$1 = "0.18.2";
24269
24276
  //#endregion
24270
24277
  //#region src/lib/env.ts
24271
24278
  const URLWithTrailingSlash = url().transform(ensureTrailingSlash);
@@ -24446,7 +24453,7 @@ const retryContextKey = (request) => `${request.method} ${request.url}`;
24446
24453
  const isLinkedInRateLimitError = (error) => error instanceof HTTPError && error.response.status === 429 && isLinkedInProxyRequest(error.request);
24447
24454
  const readBearerToken = async () => {
24448
24455
  const credentials = await readCredentials();
24449
- if (!credentials?.accessToken) throw new AuthError("Not logged in. Run `social account login` first.");
24456
+ if (!credentials?.accessToken) throw new AuthError("Not logged in. Run `social account setup` first.");
24450
24457
  return credentials.accessToken;
24451
24458
  };
24452
24459
  const linkedInRateLimitFallbackDelaySeconds = (retryCount) => Math.min(2 ** Math.max(0, retryCount - 1), LINKEDIN_RATE_LIMIT_MAX_FALLBACK_SECONDS);
@@ -30609,8 +30616,8 @@ const FIRST_RUN_NOTICE = [
30609
30616
  const ALLOWLISTED_MESSAGES = /* @__PURE__ */ new Set([
30610
30617
  "Cancelled.",
30611
30618
  "Invalid credentials.",
30612
- "Not logged in. Run `social account login` first.",
30613
- "Session expired before login finished. Run `social account login` again."
30619
+ "Not logged in. Run `social account setup` first.",
30620
+ "Session expired before login finished. Run `social account setup` again."
30614
30621
  ]);
30615
30622
  const hasCittyErrorShape = (error) => error instanceof Error && error.name === "CLIError" && "code" in error && typeof error.code === "string";
30616
30623
  const errorName = (error) => error instanceof Error && error.name ? error.name : "Error";
@@ -32162,7 +32169,7 @@ const pollDeviceTokenOnce = async (deviceCode, poster = authAPI) => {
32162
32169
  /**
32163
32170
  * Device-authorization onboarding state machine.
32164
32171
  *
32165
- * Non-TTY `social account login` is a poll: each invocation is a fresh process,
32172
+ * Non-TTY `social account setup` is a poll: each invocation is a fresh process,
32166
32173
  * so the in-flight device code is persisted to `~/.social/device-login*.json`
32167
32174
  * (namespaced by API URL exactly like credentials). The engine advances and
32168
32175
  * reports onboarding state as a discriminated union — a skill can call login
@@ -32207,6 +32214,7 @@ const defaultClearPending = async (apiURL) => {
32207
32214
  const resolveDeps = (deps) => ({
32208
32215
  now: deps.now ?? Date.now,
32209
32216
  apiURL: deps.apiURL ?? env.SOCIAL_API_URL,
32217
+ webURL: deps.webURL ?? env.SOCIAL_WEB_URL,
32210
32218
  poster: deps.poster,
32211
32219
  readPending: deps.readPending ?? defaultReadPending,
32212
32220
  writePending: deps.writePending ?? defaultWritePending,
@@ -32224,9 +32232,15 @@ const accountFromCredentials = (credentials) => ({
32224
32232
  scope: credentials.scope ?? null,
32225
32233
  expiresAt: credentials.expiresAt ? new Date(credentials.expiresAt).toISOString() : null
32226
32234
  });
32227
- const pendingState = (pending) => ({
32235
+ const trustedVerificationURL = (value, webURL) => {
32236
+ const candidate = new URL(value);
32237
+ const trusted = new URL(webURL);
32238
+ if (candidate.origin !== trusted.origin || candidate.username.length > 0 || candidate.password.length > 0) throw new Error("untrusted_device_verification_url");
32239
+ return candidate.toString();
32240
+ };
32241
+ const pendingState = (pending, webURL) => ({
32228
32242
  status: "pending_approval",
32229
- verificationURL: pending.verificationURL,
32243
+ verificationURL: trustedVerificationURL(pending.verificationURL, webURL),
32230
32244
  userCode: pending.userCode,
32231
32245
  expiresAt: pending.expiresAt,
32232
32246
  scope: pending.scope
@@ -32234,17 +32248,18 @@ const pendingState = (pending) => ({
32234
32248
  const startDeviceFlow = async (scope, resolved) => {
32235
32249
  const deviceCode = await createDeviceCode(scope, resolved.poster);
32236
32250
  const expiresAt = new Date(resolved.now() + deviceCode.expires_in * 1e3).toISOString();
32251
+ const verificationURL = trustedVerificationURL(deviceCode.verification_uri_complete, resolved.webURL);
32237
32252
  const pending = {
32238
32253
  version: STATE_VERSION,
32239
32254
  apiURL: resolved.apiURL,
32240
32255
  scope,
32241
32256
  deviceCode: deviceCode.device_code,
32242
32257
  userCode: deviceCode.user_code,
32243
- verificationURL: deviceCode.verification_uri_complete,
32258
+ verificationURL,
32244
32259
  expiresAt
32245
32260
  };
32246
32261
  await resolved.writePending(pending);
32247
- return pendingState(pending);
32262
+ return pendingState(pending, resolved.webURL);
32248
32263
  };
32249
32264
  /**
32250
32265
  * Advance the non-TTY device login by exactly one step.
@@ -32268,7 +32283,7 @@ const advanceDeviceLogin = async (scope, deps = {}) => {
32268
32283
  return { status: "expired" };
32269
32284
  }
32270
32285
  const outcome = await pollDeviceTokenOnce(pending.deviceCode, resolved.poster);
32271
- if (outcome.kind === "pending") return pendingState(pending);
32286
+ if (outcome.kind === "pending") return pendingState(pending, resolved.webURL);
32272
32287
  if (outcome.kind === "expired") {
32273
32288
  await resolved.clearPending(resolved.apiURL);
32274
32289
  return { status: "expired" };
@@ -32545,56 +32560,6 @@ const parseScopeAlias = (value) => {
32545
32560
  if (G.isOk(parsed)) return parsed.value;
32546
32561
  throw new Error(parsed.error.message);
32547
32562
  };
32548
- const scopePhase = async (ctx) => {
32549
- const scopeAlias = parseScopeAlias(ctx.args.scope);
32550
- return {
32551
- status: "done",
32552
- data: await ctx.client.cli.session.upsert({ scopeAlias })
32553
- };
32554
- };
32555
- //#endregion
32556
- //#region src/login/phases/2.seat.ts
32557
- const SEAT_BILLING_DETAILS_URL = publicRouteURLs.pricing;
32558
- const SEAT_PRICING_MESSAGE = `${productBrand.name} costs $20/month/account + usage. Full details at ${SEAT_BILLING_DETAILS_URL}. Continue?`;
32559
- const SEAT_CHECKOUT_RETURN_PATH = "/setup/billing/done";
32560
- const SEAT_POLL_INTERVAL_MS = 2e3;
32561
- const SEAT_POLL_TIMEOUT_MS = 1800 * 1e3;
32562
- const seatAvailable = (status) => status.seats.available > 0;
32563
- const pollForSeat = async (ctx, deps = {}) => {
32564
- const sleep = deps.sleep ?? setTimeout$1;
32565
- const now = deps.now ?? Date.now;
32566
- const startedAt = now();
32567
- const intervalMs = deps.pollIntervalMs ?? SEAT_POLL_INTERVAL_MS;
32568
- const timeoutMs = deps.pollTimeoutMs ?? SEAT_POLL_TIMEOUT_MS;
32569
- while (now() - startedAt <= timeoutMs) {
32570
- const status = await ctx.client.billing.status();
32571
- if (seatAvailable(status)) return status;
32572
- await sleep(intervalMs);
32573
- }
32574
- throw new Error("Billing checkout did not complete within 30 minutes. Finish checkout in the browser, then run `social account login` again.");
32575
- };
32576
- const runSeatPhase = async (ctx, deps = {}) => {
32577
- const status = await ctx.client.billing.status();
32578
- if (seatAvailable(status)) return {
32579
- status: "done",
32580
- data: status
32581
- };
32582
- if (!await ctx.ui.confirm({
32583
- message: SEAT_PRICING_MESSAGE,
32584
- initialValue: true
32585
- })) return {
32586
- status: "needs_input",
32587
- missing: ["billing_confirmation"],
32588
- reason: "Checkout was not started."
32589
- };
32590
- const checkout = await ctx.client.billing.checkoutURL({ returnPath: SEAT_CHECKOUT_RETURN_PATH });
32591
- ctx.ui.info(checkout.url);
32592
- return {
32593
- status: "done",
32594
- data: await ctx.ui.spinElapsed("Waiting for billing checkout", () => pollForSeat(ctx, deps), "Billing ready")
32595
- };
32596
- };
32597
- const seatPhase = (ctx) => runSeatPhase(ctx);
32598
32563
  //#endregion
32599
32564
  //#region src/login/index.ts
32600
32565
  const ScopeAliasOutput = _enum(CLI_SCOPE_ALIASES);
@@ -32609,37 +32574,22 @@ const LoginSeatsOutput = object({
32609
32574
  used: number().int().nonnegative(),
32610
32575
  available: number().int().nonnegative()
32611
32576
  });
32612
- const LoginCredentialOutput = object({
32613
- apiURL: string(),
32614
- namespace: string().nullable(),
32615
- account: string(),
32616
- path: string(),
32617
- present: boolean$1(),
32618
- valid: boolean$1(),
32619
- expiresAt: string().nullable(),
32620
- scope: string().nullable(),
32621
- capabilities: array(string())
32622
- });
32623
- const DeviceAccountOutput = object({
32624
- scope: string().nullable(),
32625
- expiresAt: string().nullable()
32626
- });
32627
32577
  const LoginOutput = discriminatedUnion("status", [
32628
32578
  object({
32629
- status: literal("ok"),
32579
+ status: literal("pending_billing"),
32630
32580
  user: LoginUserOutput,
32631
32581
  scope: ScopeAliasOutput,
32582
+ capabilities: array(string()),
32632
32583
  seats: LoginSeatsOutput,
32584
+ checkoutURL: string(),
32633
32585
  nextCommands: array(string())
32634
32586
  }),
32635
32587
  object({
32636
- status: literal("already_logged_in"),
32637
- message: string(),
32588
+ status: literal("ready"),
32638
32589
  user: LoginUserOutput,
32639
- sessionId: string(),
32640
32590
  scope: ScopeAliasOutput,
32641
32591
  capabilities: array(string()),
32642
- credential: LoginCredentialOutput,
32592
+ seats: LoginSeatsOutput,
32643
32593
  nextCommands: array(string())
32644
32594
  }),
32645
32595
  object({
@@ -32650,11 +32600,6 @@ const LoginOutput = discriminatedUnion("status", [
32650
32600
  scope: ScopeAliasOutput,
32651
32601
  nextCommands: array(string())
32652
32602
  }),
32653
- object({
32654
- status: literal("logged_in"),
32655
- account: DeviceAccountOutput,
32656
- nextCommands: array(string())
32657
- }),
32658
32603
  object({
32659
32604
  status: literal("expired"),
32660
32605
  message: string()
@@ -32671,60 +32616,37 @@ const LoginOutput = discriminatedUnion("status", [
32671
32616
  details: unknown().optional()
32672
32617
  })
32673
32618
  ]);
32674
- const phases = [
32675
- {
32676
- name: "access",
32677
- run: accessPhase
32678
- },
32679
- {
32680
- name: "sign-in",
32681
- run: signInPhase
32682
- },
32683
- {
32684
- name: "scope",
32685
- run: scopePhase
32686
- },
32687
- {
32688
- name: "seat",
32689
- run: seatPhase
32690
- }
32691
- ];
32619
+ const phases = [{
32620
+ name: "access",
32621
+ run: accessPhase
32622
+ }, {
32623
+ name: "sign-in",
32624
+ run: signInPhase
32625
+ }];
32692
32626
  const errorOutput = (error) => ({
32693
32627
  status: "error",
32694
32628
  code: error instanceof Error ? error.name : "Error",
32695
32629
  message: error instanceof Error ? error.message : String(error)
32696
32630
  });
32697
32631
  const nextCommands = ["social account connect linkedin", "social account connect x"];
32698
- const deviceExpiredMessage = "Sign-in expired before approval. Run `social account login` again to restart.";
32699
- const scopeUpgradeRequiresReauthorization = "Existing CLI session is read-only. Run `social account logout`, then `social account login` to approve a new write-capable session.";
32700
- const scopeAliasIncludes = (granted, requested) => granted === requested || granted === "read,write";
32701
- const credentialScopeFor = (session) => {
32702
- const parsed = ScopeAliasOutput.safeParse(session.credential.scope);
32703
- return parsed.success ? parsed.data : null;
32704
- };
32705
- const existingSessionSupportsScope = (session, requested) => {
32706
- if (scopeAliasIncludes(session.session.scope, requested)) return true;
32707
- const credentialScope = credentialScopeFor(session);
32708
- return credentialScope ? scopeAliasIncludes(credentialScope, requested) : false;
32709
- };
32710
- const nextCommandsMessage = `Now run \`${nextCommands[0]}\` or \`${nextCommands[1]}\`.`;
32711
- const billingReady = (billing) => billing.seats.available > 0;
32712
- const alreadyLoggedInOutput = ({ credential, session }) => ({
32713
- status: "already_logged_in",
32714
- message: "Already logged in.",
32715
- user: session.user,
32716
- sessionId: session.sessionId,
32717
- scope: session.scope,
32718
- capabilities: session.capabilities,
32719
- credential,
32720
- nextCommands
32632
+ const availableConnectCommands = (capabilities) => nextCommands.filter((command) => {
32633
+ const platform = command.endsWith(" linkedin") ? "linkedin" : "x";
32634
+ return capabilities.some((capability) => capability.startsWith(`${platform}:`));
32721
32635
  });
32636
+ const setupOutputFor = (setup) => ({
32637
+ ...setup,
32638
+ nextCommands: setup.status === "pending_billing" ? ["social account setup"] : availableConnectCommands(setup.capabilities)
32639
+ });
32640
+ const deviceExpiredMessage = "Sign-in expired before approval. Run `social account setup` again to restart.";
32641
+ const scopeUpgradeRequiresReauthorization = "Existing CLI session is read-only. Run `social account logout`, then `social account setup` to approve a new write-capable session.";
32642
+ const scopeAliasIncludes = (granted, requested) => granted === requested || granted === "read,write";
32643
+ const existingSessionSupportsScope = (session, requested) => scopeAliasIncludes(session.session.scope, requested);
32722
32644
  const offlineOutput = () => ({
32723
32645
  status: "error",
32724
32646
  code: "offline",
32725
32647
  message: "Couldn't reach the server. Check your network connection and try again."
32726
32648
  });
32727
- const loginOutputForDeviceState = (state, sessionScope) => {
32649
+ const loginOutputForDeviceState = (state) => {
32728
32650
  switch (state.status) {
32729
32651
  case "pending_approval": return {
32730
32652
  status: "pending_approval",
@@ -32732,16 +32654,9 @@ const loginOutputForDeviceState = (state, sessionScope) => {
32732
32654
  userCode: state.userCode,
32733
32655
  expiresAt: state.expiresAt,
32734
32656
  scope: state.scope,
32735
- nextCommands: ["social account login"]
32736
- };
32737
- case "logged_in": return {
32738
- status: "logged_in",
32739
- account: {
32740
- ...state.account,
32741
- scope: sessionScope ?? state.account.scope
32742
- },
32743
- nextCommands
32657
+ nextCommands: ["social account setup"]
32744
32658
  };
32659
+ case "logged_in": throw new Error("Approved device login must continue through account setup.");
32745
32660
  case "expired": return {
32746
32661
  status: "expired",
32747
32662
  message: deviceExpiredMessage
@@ -32752,10 +32667,10 @@ const loginOutputForDeviceState = (state, sessionScope) => {
32752
32667
  };
32753
32668
  }
32754
32669
  };
32755
- const planLoginStep = ({ billingSeatAvailable, deviceSessionScope, deviceState, existing, isInteractiveTerminal, requestedScope }) => {
32670
+ const planLoginStep = ({ deviceState, existing, isInteractiveTerminal, requestedScope }) => {
32756
32671
  if (deviceState) return {
32757
32672
  action: "printOutput",
32758
- output: loginOutputForDeviceState(deviceState, deviceSessionScope)
32673
+ output: loginOutputForDeviceState(deviceState)
32759
32674
  };
32760
32675
  if (existing.kind === "existing") {
32761
32676
  if (!existingSessionSupportsScope(existing.session, requestedScope)) return {
@@ -32766,15 +32681,7 @@ const planLoginStep = ({ billingSeatAvailable, deviceSessionScope, deviceState,
32766
32681
  message: scopeUpgradeRequiresReauthorization
32767
32682
  }
32768
32683
  };
32769
- if (billingSeatAvailable === true || !isInteractiveTerminal) return {
32770
- action: "useExistingSession",
32771
- output: alreadyLoggedInOutput(existing.session),
32772
- repairScope: requestedScope
32773
- };
32774
- return {
32775
- action: "runInteractiveSeatOnly",
32776
- repairScope: requestedScope
32777
- };
32684
+ return { action: "useExistingSession" };
32778
32685
  }
32779
32686
  if (existing.kind === "offline") return {
32780
32687
  action: "offline",
@@ -32787,25 +32694,12 @@ const runLogin = async (ctx, loginPhases = phases, deps = {}) => {
32787
32694
  const readLocalCredentials = deps.readCredentials ?? readCredentials;
32788
32695
  analytics.capture("login_started");
32789
32696
  for (const phase of loginPhases) {
32790
- if (phase.name !== "access" && phase.name !== "sign-in" && deps.authenticated !== true && !bearerIsValid(await readLocalCredentials())) throw new AuthError("Session expired before login finished. Run `social account login` again.");
32697
+ if (phase.name !== "access" && phase.name !== "sign-in" && deps.authenticated !== true && !bearerIsValid(await readLocalCredentials())) throw new AuthError("Session expired before login finished. Run `social account setup` again.");
32791
32698
  const result = await phase.run(ctx);
32792
32699
  if (result.status !== "done") return result;
32793
32700
  analytics.capture("login_phase_completed", { phase: phase.name });
32794
32701
  }
32795
- const session = await ctx.client.cli.session.me();
32796
- const billing = await ctx.client.billing.status();
32797
- ctx.ui.info(nextCommandsMessage);
32798
- return {
32799
- status: "ok",
32800
- user: session.user,
32801
- scope: session.scopeAlias,
32802
- seats: {
32803
- total: billing.seats.total,
32804
- used: billing.seats.used,
32805
- available: billing.seats.available
32806
- },
32807
- nextCommands
32808
- };
32702
+ return setupOutputFor(await ctx.client.billing.accountSetup());
32809
32703
  };
32810
32704
  const loginExitCodeFor = (output) => {
32811
32705
  if (output.status === "error") return exitCodeFor(new Error(output.message));
@@ -32819,15 +32713,16 @@ const loginExitCodeFor = (output) => {
32819
32713
  */
32820
32714
  const createLoginCommand = (deps = {}) => {
32821
32715
  const commandDeps = {
32822
- advanceDeviceLogin: deps.advanceDeviceLogin ?? advanceDeviceLogin,
32716
+ advanceDeviceLogin: deps.advanceDeviceLogin ?? ((scope) => advanceDeviceLogin(scope, deps.deviceDeps)),
32823
32717
  createClient: deps.createClient ?? createORPCAPIClient,
32718
+ deviceDeps: deps.deviceDeps ?? {},
32824
32719
  isInteractiveTerminal: deps.isInteractiveTerminal ?? (() => process.stdin.isTTY === true && process.stdout.isTTY === true),
32825
32720
  readExistingAuthSession: deps.readExistingAuthSession ?? readExistingAuthSession
32826
32721
  };
32827
32722
  return defineCommand({
32828
32723
  meta: commandMeta({
32829
- name: "login",
32830
- description: "Log in, choose CLI scope, and ensure billing",
32724
+ name: "setup",
32725
+ description: "Authenticate Social and ensure billing is ready",
32831
32726
  contract: localCLIContract({
32832
32727
  auth: {
32833
32728
  interactive: true,
@@ -32854,21 +32749,15 @@ const createLoginCommand = (deps = {}) => {
32854
32749
  const existing = await commandDeps.readExistingAuthSession(client);
32855
32750
  const requestedScope = parseScopeAlias(loginArgs.scope);
32856
32751
  const isInteractive = commandDeps.isInteractiveTerminal();
32857
- const billingSeatAvailable = existing.kind === "existing" && existingSessionSupportsScope(existing.session, requestedScope) ? billingReady(await client.billing.status()) : void 0;
32858
32752
  const plan = planLoginStep({
32859
32753
  existing,
32860
32754
  requestedScope,
32861
- isInteractiveTerminal: isInteractive,
32862
- billingSeatAvailable
32755
+ isInteractiveTerminal: isInteractive
32863
32756
  });
32864
32757
  switch (plan.action) {
32865
32758
  case "useExistingSession": {
32866
- const grant = await client.cli.session.upsert({ scopeAlias: plan.repairScope });
32867
- output = {
32868
- ...plan.output,
32869
- scope: grant.scopeAlias,
32870
- capabilities: grant.capabilities
32871
- };
32759
+ const setup = await client.billing.accountSetup();
32760
+ output = setupOutputFor(setup);
32872
32761
  break;
32873
32762
  }
32874
32763
  case "requireScopeReauth":
@@ -32876,17 +32765,6 @@ const createLoginCommand = (deps = {}) => {
32876
32765
  case "printOutput":
32877
32766
  output = plan.output;
32878
32767
  break;
32879
- case "runInteractiveSeatOnly":
32880
- await client.cli.session.upsert({ scopeAlias: plan.repairScope });
32881
- output = await runLogin({
32882
- ui: createUI(true),
32883
- client,
32884
- args: loginArgs
32885
- }, [{
32886
- name: "seat",
32887
- run: seatPhase
32888
- }], { authenticated: true });
32889
- break;
32890
32768
  case "runInteractiveFullLogin":
32891
32769
  output = await runLogin({
32892
32770
  ui: createUI(true),
@@ -32896,13 +32774,17 @@ const createLoginCommand = (deps = {}) => {
32896
32774
  break;
32897
32775
  case "advanceDeviceLogin": {
32898
32776
  const state = await commandDeps.advanceDeviceLogin(requestedScope);
32899
- const sessionScope = state.status === "logged_in" ? (await client.cli.session.upsert({ scopeAlias: requestedScope })).scopeAlias : void 0;
32777
+ if (state.status === "logged_in") {
32778
+ const approvedScope = ScopeAliasOutput.safeParse(state.account.scope);
32779
+ if (!(approvedScope.success && scopeAliasIncludes(approvedScope.data, requestedScope))) throw new Error("Device authorization returned an insufficient scope.");
32780
+ output = setupOutputFor(await client.billing.accountSetup());
32781
+ break;
32782
+ }
32900
32783
  const devicePlan = planLoginStep({
32901
32784
  existing,
32902
32785
  requestedScope,
32903
32786
  isInteractiveTerminal: isInteractive,
32904
- deviceState: state,
32905
- deviceSessionScope: sessionScope
32787
+ deviceState: state
32906
32788
  });
32907
32789
  if (devicePlan.action !== "printOutput") throw new Error("Device login produced no printable state.");
32908
32790
  output = devicePlan.output;
@@ -32913,21 +32795,14 @@ const createLoginCommand = (deps = {}) => {
32913
32795
  output = errorOutput(error);
32914
32796
  exitCode = exitCodeFor(error);
32915
32797
  }
32916
- if (output.status === "ok" || output.status === "already_logged_in") {
32798
+ if (output.status === "ready") {
32917
32799
  analytics.identifyUser(output.user.id);
32918
32800
  analytics.capture("login_completed", {
32919
32801
  scope: output.scope,
32920
- already_logged_in: output.status === "already_logged_in",
32921
- ...output.status === "ok" ? {
32922
- seats_total: output.seats.total,
32923
- seats_available: output.seats.available
32924
- } : {}
32802
+ seats_total: output.seats.total,
32803
+ seats_available: output.seats.available
32925
32804
  });
32926
- } else if (output.status === "logged_in") analytics.capture("login_completed", {
32927
- already_logged_in: false,
32928
- non_tty: true
32929
- });
32930
- else if (output.status === "expired") analytics.capture("login_failed", { code: "expired" });
32805
+ } else if (output.status === "expired") analytics.capture("login_failed", { code: "expired" });
32931
32806
  else if (output.status === "needs_input") analytics.capture("login_failed", {
32932
32807
  code: "needs_input",
32933
32808
  reason: output.reason
@@ -32938,7 +32813,19 @@ const createLoginCommand = (deps = {}) => {
32938
32813
  }
32939
32814
  });
32940
32815
  };
32941
- const loginCommand = createLoginCommand();
32816
+ const setupCommand = createLoginCommand();
32817
+ const hiddenLoginAliasFor = (command) => {
32818
+ const meta = {
32819
+ ...command.meta,
32820
+ hidden: true,
32821
+ schemaHidden: true
32822
+ };
32823
+ return {
32824
+ ...command,
32825
+ meta
32826
+ };
32827
+ };
32828
+ hiddenLoginAliasFor(setupCommand);
32942
32829
  //#endregion
32943
32830
  //#region src/logout.ts
32944
32831
  const revokeServerSide = async (accessToken) => {
@@ -32980,7 +32867,7 @@ const logoutCommand = defineCommand({
32980
32867
  const credentials = await readCredentials();
32981
32868
  if (!credentials?.accessToken) {
32982
32869
  await clearCredentials();
32983
- throw new AuthError("Not logged in. Run `social account login` first.");
32870
+ throw new AuthError("Not logged in. Run `social account setup` first.");
32984
32871
  }
32985
32872
  const revoked = await revokeServerSide(credentials.accessToken);
32986
32873
  await clearCredentials();
@@ -33412,7 +33299,7 @@ const isInteractiveConnect = (deps) => deps.isInteractiveTerminal?.() === true;
33412
33299
  * One non-blocking step of a connect handshake for a non-TTY caller. Returns the
33413
33300
  * connected account if one is already linked, otherwise emits the connect URL and
33414
33301
  * reports `pending_approval`. A repeated call re-checks and advances — the skill
33415
- * polls this the same way it polls `social account login`.
33302
+ * polls this the same way it polls `social account setup`.
33416
33303
  */
33417
33304
  const runConnectStep = async (deps, platform, listConnected, connectURL) => {
33418
33305
  const connected = (await listConnected()).find((account) => account.status === "connected");
@@ -33479,7 +33366,7 @@ const listConnectedAccounts = async (deps) => {
33479
33366
  });
33480
33367
  };
33481
33368
  const defaultWhoamiOutput = () => authWhoamiOutput(createORPCAPIClient());
33482
- const createAccountCommand = (deps) => {
33369
+ const createAccountCommand = (deps, accountSetupCommand = setupCommand) => {
33483
33370
  const accountDefaultsClient = deps.client.accounts.default;
33484
33371
  const defaultCommand = defineCommand({
33485
33372
  meta: {
@@ -33535,67 +33422,79 @@ const createAccountCommand = (deps) => {
33535
33422
  })
33536
33423
  }
33537
33424
  });
33538
- const subCommands = {
33539
- login: loginCommand,
33540
- logout: logoutCommand,
33541
- connect: defineCommand({
33542
- meta: {
33543
- name: "connect",
33544
- description: "Connect a LinkedIn or X account."
33545
- },
33546
- subCommands: {
33547
- linkedin: createConnectPlatformCommand("linkedin", async () => {
33548
- if (isInteractiveConnect(deps)) {
33549
- await runConnectOutput(deps, connectLinkedinAccount);
33550
- return;
33551
- }
33552
- await runConnectStep(deps, "linkedin", () => listLinkedinLifecycleAccounts(deps), () => createLinkedinConnectURL(deps));
33553
- }),
33554
- x: createConnectPlatformCommand("x", async () => {
33555
- if (isInteractiveConnect(deps)) {
33556
- await runConnectOutput(deps, async (connectDeps) => {
33557
- const result = await connectXAccount(connectDeps);
33558
- if (G.isError(result)) throwXLifecycleError(result.error);
33559
- return result.value;
33560
- });
33561
- return;
33562
- }
33563
- await runConnectStep(deps, "x", async () => {
33564
- const result = await listXLifecycleAccounts(deps, true);
33565
- if (G.isError(result)) throwXLifecycleError(result.error);
33566
- return result.value;
33567
- }, () => createXConnectURL(deps));
33568
- })
33569
- }
33570
- }),
33571
- reconnect: defineCommand({
33572
- meta: {
33573
- name: "reconnect",
33574
- description: "Reconnect a LinkedIn or X account."
33575
- },
33576
- subCommands: {
33577
- linkedin: createAccountPlatformCommand("linkedin", "Reconnect a LinkedIn account.", async (args) => {
33578
- await runConnectOutput(deps, (connectDeps) => reconnectLinkedinAccount(connectDeps, String(args.account)));
33579
- }, { accountArg: linkedinReconnectAccountArg }),
33580
- x: createAccountPlatformCommand("x", "Reconnect an X account.", async (args) => {
33425
+ const connect = defineCommand({
33426
+ meta: {
33427
+ name: "connect",
33428
+ description: "Connect a LinkedIn or X account."
33429
+ },
33430
+ subCommands: {
33431
+ linkedin: createConnectPlatformCommand("linkedin", async () => {
33432
+ if (isInteractiveConnect(deps)) {
33433
+ await runConnectOutput(deps, connectLinkedinAccount);
33434
+ return;
33435
+ }
33436
+ await runConnectStep(deps, "linkedin", () => listLinkedinLifecycleAccounts(deps), () => createLinkedinConnectURL(deps));
33437
+ }),
33438
+ x: createConnectPlatformCommand("x", async () => {
33439
+ if (isInteractiveConnect(deps)) {
33581
33440
  await runConnectOutput(deps, async (connectDeps) => {
33582
- const result = await reconnectXAccount(connectDeps, { account: String(args.account) });
33441
+ const result = await connectXAccount(connectDeps);
33583
33442
  if (G.isError(result)) throwXLifecycleError(result.error);
33584
33443
  return result.value;
33585
33444
  });
33586
- }, { accountArg: xAccountArg })
33587
- }
33588
- }),
33589
- disconnect: defineCommand({
33590
- meta: {
33591
- name: "disconnect",
33592
- description: "Disconnect a LinkedIn or X account."
33593
- },
33594
- subCommands: {
33595
- linkedin: createAccountPlatformCommand("linkedin", "Disconnect a LinkedIn account.", async (args) => {
33596
- const result = await disconnectLinkedinAccount(deps, String(args.account));
33597
- await writeOutput(deps, result);
33598
- }, { contract: writeCLIContract({
33445
+ return;
33446
+ }
33447
+ await runConnectStep(deps, "x", async () => {
33448
+ const result = await listXLifecycleAccounts(deps, true);
33449
+ if (G.isError(result)) throwXLifecycleError(result.error);
33450
+ return result.value;
33451
+ }, () => createXConnectURL(deps));
33452
+ })
33453
+ }
33454
+ });
33455
+ const reconnect = defineCommand({
33456
+ meta: {
33457
+ name: "reconnect",
33458
+ description: "Reconnect a LinkedIn or X account."
33459
+ },
33460
+ subCommands: {
33461
+ linkedin: createAccountPlatformCommand("linkedin", "Reconnect a LinkedIn account.", async (args) => {
33462
+ await runConnectOutput(deps, (connectDeps) => reconnectLinkedinAccount(connectDeps, String(args.account)));
33463
+ }, { accountArg: linkedinReconnectAccountArg }),
33464
+ x: createAccountPlatformCommand("x", "Reconnect an X account.", async (args) => {
33465
+ await runConnectOutput(deps, async (connectDeps) => {
33466
+ const result = await reconnectXAccount(connectDeps, { account: String(args.account) });
33467
+ if (G.isError(result)) throwXLifecycleError(result.error);
33468
+ return result.value;
33469
+ });
33470
+ }, { accountArg: xAccountArg })
33471
+ }
33472
+ });
33473
+ const disconnect = defineCommand({
33474
+ meta: {
33475
+ name: "disconnect",
33476
+ description: "Disconnect a LinkedIn or X account."
33477
+ },
33478
+ subCommands: {
33479
+ linkedin: createAccountPlatformCommand("linkedin", "Disconnect a LinkedIn account.", async (args) => {
33480
+ const result = await disconnectLinkedinAccount(deps, String(args.account));
33481
+ await writeOutput(deps, result);
33482
+ }, { contract: writeCLIContract({
33483
+ outputSchema: AccountDisconnectOutput,
33484
+ idempotency: "non-idempotent",
33485
+ hazard: advisoryHazard("destructive"),
33486
+ hazards: [{
33487
+ code: "account_disconnect",
33488
+ message: "Destructive account disconnect; requires an exact account identifier."
33489
+ }]
33490
+ }) }),
33491
+ x: createAccountPlatformCommand("x", "Disconnect an X account.", async (args) => {
33492
+ const result = await disconnectXAccount(deps, String(args.account));
33493
+ if (G.isError(result)) throwXLifecycleError(result.error);
33494
+ await writeOutput(deps, result.value);
33495
+ }, {
33496
+ accountArg: xAccountArg,
33497
+ contract: writeCLIContract({
33599
33498
  outputSchema: AccountDisconnectOutput,
33600
33499
  idempotency: "non-idempotent",
33601
33500
  hazard: advisoryHazard("destructive"),
@@ -33603,25 +33502,17 @@ const createAccountCommand = (deps) => {
33603
33502
  code: "account_disconnect",
33604
33503
  message: "Destructive account disconnect; requires an exact account identifier."
33605
33504
  }]
33606
- }) }),
33607
- x: createAccountPlatformCommand("x", "Disconnect an X account.", async (args) => {
33608
- const result = await disconnectXAccount(deps, String(args.account));
33609
- if (G.isError(result)) throwXLifecycleError(result.error);
33610
- await writeOutput(deps, result.value);
33611
- }, {
33612
- accountArg: xAccountArg,
33613
- contract: writeCLIContract({
33614
- outputSchema: AccountDisconnectOutput,
33615
- idempotency: "non-idempotent",
33616
- hazard: advisoryHazard("destructive"),
33617
- hazards: [{
33618
- code: "account_disconnect",
33619
- message: "Destructive account disconnect; requires an exact account identifier."
33620
- }]
33621
- })
33622
33505
  })
33623
- }
33624
- }),
33506
+ })
33507
+ }
33508
+ });
33509
+ const subCommands = {
33510
+ setup: accountSetupCommand,
33511
+ login: hiddenLoginAliasFor(accountSetupCommand),
33512
+ logout: logoutCommand,
33513
+ connect,
33514
+ reconnect,
33515
+ disconnect,
33625
33516
  default: defaultCommand,
33626
33517
  billing: createBillingCommand(deps),
33627
33518
  usage: createUsageCommand(deps),
@@ -39108,6 +38999,7 @@ const pathPartsFrom = (...values) => {
39108
38999
  const commandName = (command, fallback) => typeof command.meta?.name === "string" ? command.meta.name : fallback;
39109
39000
  const commandDescription = (command) => typeof command.meta?.description === "string" ? command.meta.description : "";
39110
39001
  const isHiddenCommand = (command) => command.meta?.hidden === true;
39002
+ const isSchemaHiddenCommand = (command) => command.meta?.schemaHidden === true;
39111
39003
  const inputSourceFor = (command) => command.meta?.stdin === true ? { inputSource: "stdin" } : {};
39112
39004
  const isRecord = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value));
39113
39005
  const childCommandsFor = (command) => ({
@@ -39409,7 +39301,7 @@ const commandAtPath = (command, path) => {
39409
39301
  const resolved = [];
39410
39302
  for (const [index, part] of parts.entries()) {
39411
39303
  const next = childCommandsFor(current)[part];
39412
- if (!next) {
39304
+ if (!next || isSchemaHiddenCommand(next)) {
39413
39305
  const tail = parts.slice(index);
39414
39306
  const match = positionalPathMatch(current, resolved, tail);
39415
39307
  if (match) return {
@@ -40082,10 +39974,10 @@ process.emitWarning = ((warning, ...rest) => {
40082
39974
  const asMutableCommand = (command) => {
40083
39975
  return command;
40084
39976
  };
40085
- const loginExtraArgError = (rawArgs, path) => {
40086
- if (path.join(" ") !== "account login") return;
40087
- const loginIndex = rawArgs.lastIndexOf("login");
40088
- const extra = rawArgs.slice(loginIndex + 1).filter((arg) => arg !== "--").at(0);
39977
+ const setupExtraArgError = (rawArgs, path) => {
39978
+ if (!["account setup", "account login"].includes(path.join(" "))) return;
39979
+ const setupIndex = Math.max(rawArgs.lastIndexOf("setup"), rawArgs.lastIndexOf("login"));
39980
+ const extra = rawArgs.slice(setupIndex + 1).filter((arg) => arg !== "--").at(0);
40089
39981
  if (!extra) return;
40090
39982
  const message = extra.startsWith("-") ? `Unknown option: ${extra}` : `Unknown argument: ${extra}`;
40091
39983
  return Object.assign(new Error(message), {
@@ -40252,8 +40144,8 @@ const printUsage = async (command, rawArgs) => {
40252
40144
  const usage = await commandForUsage(command, rawArgs);
40253
40145
  printLine(`${await renderUsage(usage.command, usage.parent)}\n`);
40254
40146
  };
40255
- const createSocialCommand = (deps = createCLIDeps()) => {
40256
- const accountCommand = asMutableCommand(createAccountCommand(deps));
40147
+ const createSocialCommand = (deps = createCLIDeps(), options = {}) => {
40148
+ const accountCommand = asMutableCommand(createAccountCommand(deps, options.setupCommand));
40257
40149
  const linkedinCommand = asMutableCommand(createLinkedinCommands(deps));
40258
40150
  const xCommand = asMutableCommand(createXCommands(deps));
40259
40151
  const feedbackCommand = asMutableCommand(createFeedbackCommand(deps));
@@ -40305,8 +40197,8 @@ const runSocial = async ({ command = createSocialCommand(), now = Date.now, rawA
40305
40197
  startedAt: now()
40306
40198
  };
40307
40199
  try {
40308
- const loginArgError = loginExtraArgError(rawArgs, path);
40309
- if (loginArgError) throw loginArgError;
40200
+ const setupArgError = setupExtraArgError(rawArgs, path);
40201
+ if (setupArgError) throw setupArgError;
40310
40202
  await runCommand(command, { rawArgs });
40311
40203
  } catch (error) {
40312
40204
  if (error instanceof SilentExit) return await finish(error.code, telemetry, now);