@usesocial/cli 0.10.2 → 0.11.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
@@ -151,6 +151,24 @@ var CancelledError = class extends Error {
151
151
  };
152
152
  /** True for any of the typed errors above (single-instance instanceof is safe within this package graph). */
153
153
  const isTypedCLIError = (error) => error instanceof UsageError || error instanceof AuthError || error instanceof NotFoundError || error instanceof CancelledError;
154
+ const MARKUP_BPS = 5e3;
155
+ //#endregion
156
+ //#region ../../packages/billing/src/markup.ts
157
+ const billedBPSFor = (costBPS) => costBPS + Math.floor(costBPS * MARKUP_BPS / 1e4);
158
+ const creditsForBPS = (billedBPS) => Math.ceil(billedBPS / 10);
159
+ //#endregion
160
+ //#region ../../packages/billing/src/usage-price.ts
161
+ const priceUsage = (costBPS) => {
162
+ const billedBPS = billedBPSFor(costBPS);
163
+ const credits = creditsForBPS(billedBPS);
164
+ return {
165
+ costBPS,
166
+ billedBPS,
167
+ credits,
168
+ customerUSD: creditsToUsageUSD(credits)
169
+ };
170
+ };
171
+ const creditsToUsageUSD = (credits) => credits * 10 / 1e4;
154
172
  //#endregion
155
173
  //#region ../../node_modules/.bun/es-toolkit@1.47.0/node_modules/es-toolkit/dist/string/words.mjs
156
174
  /**
@@ -511,10 +529,10 @@ const costFor = (adapter, op) => {
511
529
  metered: true,
512
530
  cacheable,
513
531
  ...cacheable ? { cacheHitCost: 0 } : {},
514
- unit: "usage_credit",
532
+ unit: "usage_usd",
515
533
  estimate: {
516
534
  kind: op.endpoint.maxUsageUnits === 1 ? "per_call" : "per_page",
517
- credits: adapter.priceUsage(op.endpoint.costBPS * op.endpoint.maxUsageUnits).credits,
535
+ usageUSD: adapter.priceUsage(op.endpoint.costBPS * op.endpoint.maxUsageUnits).customerUSD,
518
536
  basis: op.endpoint.maxUsageUnits === 1 ? "successful upstream read" : "limit/cursor page"
519
537
  },
520
538
  notes
@@ -522,10 +540,10 @@ const costFor = (adapter, op) => {
522
540
  if (op.endpoint.method !== "GET") return {
523
541
  metered: true,
524
542
  cacheable,
525
- unit: "usage_credit",
543
+ unit: "usage_usd",
526
544
  estimate: {
527
545
  kind: "per_call",
528
- credits: adapter.priceUsage(op.endpoint.costBPS).credits,
546
+ usageUSD: adapter.priceUsage(op.endpoint.costBPS).customerUSD,
529
547
  basis: "successful upstream write"
530
548
  },
531
549
  notes
@@ -535,10 +553,10 @@ const costFor = (adapter, op) => {
535
553
  metered: true,
536
554
  cacheable,
537
555
  ...cacheable ? { cacheHitCost: 0 } : {},
538
- unit: "usage_credit",
556
+ unit: "usage_usd",
539
557
  estimate: {
540
558
  kind: "per_item",
541
- creditsPerItem: adapter.priceUsage(op.endpoint.costBPS).credits,
559
+ usageUSDPerItem: adapter.priceUsage(op.endpoint.costBPS).customerUSD,
542
560
  basis: "successful returned resource",
543
561
  ...maximumItemsHint === void 0 ? {} : { maximumItemsHint }
544
562
  },
@@ -10271,7 +10289,7 @@ const LINKEDIN_OPERATIONS = [
10271
10289
  command: "list",
10272
10290
  group: "messages",
10273
10291
  root: false,
10274
- summary: "List LinkedIn inbox conversations. Costs 150 usage credits per page when not served from cache",
10292
+ summary: "List LinkedIn inbox conversations. Costs $0.150 usage per page when not served from cache",
10275
10293
  expose: false
10276
10294
  },
10277
10295
  endpoint: {
@@ -10332,7 +10350,7 @@ const LINKEDIN_OPERATIONS = [
10332
10350
  command: "read",
10333
10351
  group: "messages",
10334
10352
  root: false,
10335
- summary: "List messages in a LinkedIn inbox conversation. Costs 75 usage credits per page when not served from cache",
10353
+ summary: "List messages in a LinkedIn inbox conversation. Costs $0.075 usage per page when not served from cache",
10336
10354
  expose: false,
10337
10355
  paramLabels: { chat_id: "target" },
10338
10356
  targetKind: "chat"
@@ -11420,23 +11438,6 @@ const LINKEDIN_OPERATIONS = [
11420
11438
  }]
11421
11439
  }
11422
11440
  ];
11423
- const MARKUP_BPS = 5e3;
11424
- //#endregion
11425
- //#region ../../packages/billing/src/markup.ts
11426
- const billedBPSFor = (costBPS) => costBPS + Math.floor(costBPS * MARKUP_BPS / 1e4);
11427
- const creditsForBPS = (billedBPS) => Math.ceil(billedBPS / 10);
11428
- //#endregion
11429
- //#region ../../packages/billing/src/usage-price.ts
11430
- const priceUsage = (costBPS) => {
11431
- const billedBPS = billedBPSFor(costBPS);
11432
- const credits = creditsForBPS(billedBPS);
11433
- return {
11434
- costBPS,
11435
- billedBPS,
11436
- credits,
11437
- customerUSD: credits * 10 / 1e4
11438
- };
11439
- };
11440
11441
  //#endregion
11441
11442
  //#region ../../packages/lib/src/social-values.ts
11442
11443
  const UNSAFE_RESOURCE_CHARACTER_PATTERN = /[/?#%]/;
@@ -12475,6 +12476,13 @@ const syncOutput$1 = (data, migration) => ({
12475
12476
  data,
12476
12477
  meta: migration === void 0 ? {} : { cache: { migration } }
12477
12478
  });
12479
+ const syncSummaryForOutput$1 = (summary) => {
12480
+ const { creditsSpent, ...rest } = summary;
12481
+ return {
12482
+ ...rest,
12483
+ usageUSDSpent: creditsToUsageUSD(creditsSpent)
12484
+ };
12485
+ };
12478
12486
  const quoteIdentifier$1 = (identifier) => `\`${identifier.replaceAll("`", "``")}\``;
12479
12487
  const syncTotalRowsFor$1 = (cache, collection) => {
12480
12488
  const totalRows = cache.query(`SELECT count(*) AS totalRows FROM ${quoteIdentifier$1(collection.key)}`)[0]?.totalRows;
@@ -12492,8 +12500,8 @@ const syncListRowFor$1 = (collection, shortName, state, totalRows) => {
12492
12500
  totalRows
12493
12501
  };
12494
12502
  };
12495
- const syncProgressMessage = (progress) => `${progress.collectionKey}: ${progress.pagesCompleted} page(s), ${progress.objectsUpserted} object(s), ${progress.creditsSpent} credits.`;
12496
- const syncCompleteMessage = (summary) => `Synced ${summary.collection}: ${summary.pages} page(s), ${summary.objectsUpserted} object(s), ${summary.creditsSpent} credits.`;
12503
+ const syncProgressMessage = (progress) => `${progress.collectionKey}: ${progress.pagesCompleted} page(s), ${progress.objectsUpserted} object(s), $${creditsToUsageUSD(progress.creditsSpent).toFixed(3)} usage.`;
12504
+ const syncCompleteMessage = (summary) => `Synced ${summary.collection}: ${summary.pages} page(s), ${summary.objectsUpserted} object(s), $${summary.usageUSDSpent.toFixed(3)} usage.`;
12497
12505
  const createSyncProgressReporter = (deps, collectionKey) => {
12498
12506
  if ((deps.isInteractiveTerminal?.() ?? process.stdout.isTTY === true) && deps.ui) {
12499
12507
  const spinner = deps.ui.spinner();
@@ -12567,7 +12575,7 @@ const syncRateLimitOptions$1 = (timeoutSeconds) => ({
12567
12575
  const buildSync$1 = (deps, platform) => defineCommand({
12568
12576
  meta: commandMeta$2({
12569
12577
  name: "sync",
12570
- description: "Sync a collection into the local cache (spends credits)",
12578
+ description: "Sync a collection into the local cache (spends usage)",
12571
12579
  method: "GET",
12572
12580
  capability: "read",
12573
12581
  mutates: true,
@@ -12579,13 +12587,13 @@ const buildSync$1 = (deps, platform) => defineCommand({
12579
12587
  },
12580
12588
  capability: "read",
12581
12589
  hazard: {
12582
- kind: "spends_credits",
12590
+ kind: "spends_usage",
12583
12591
  confirm: "advisory"
12584
12592
  },
12585
12593
  idempotency: {
12586
12594
  safe: false,
12587
12595
  retry: "never",
12588
- reason: "Repeated syncs can spend additional usage credits and update local rows."
12596
+ reason: "Repeated syncs can spend additional usage dollars and update local rows."
12589
12597
  },
12590
12598
  method: "GET",
12591
12599
  mutates: true,
@@ -12599,15 +12607,15 @@ const buildSync$1 = (deps, platform) => defineCommand({
12599
12607
  examples: [{ command: "social linkedin sync connections" }],
12600
12608
  cost: {
12601
12609
  metered: true,
12602
- unit: "usage_credit",
12610
+ unit: "usage_usd",
12603
12611
  notes: ["Upstream reads during sync are metered."]
12604
12612
  },
12605
12613
  hazards: [{
12606
12614
  code: "local_cache_write",
12607
12615
  message: "Writes synced LinkedIn rows and cursor state to the local cache."
12608
12616
  }, {
12609
- code: "usage_credit_spend",
12610
- message: "May spend usage credits while reading upstream LinkedIn data."
12617
+ code: "usage_usd_spend",
12618
+ message: "May spend usage dollars while reading upstream LinkedIn data."
12611
12619
  }]
12612
12620
  }
12613
12621
  }),
@@ -12712,7 +12720,7 @@ const buildSync$1 = (deps, platform) => defineCommand({
12712
12720
  const onProgress = (message) => process.stderr.write(`${message}\n`);
12713
12721
  const progress = createSyncProgressReporter(deps, collection.key);
12714
12722
  try {
12715
- const summary = await runSync({
12723
+ const outputSummary = syncSummaryForOutput$1(await runSync({
12716
12724
  api: deps.api,
12717
12725
  cache,
12718
12726
  platform,
@@ -12726,9 +12734,9 @@ const buildSync$1 = (deps, platform) => defineCommand({
12726
12734
  onPage: progress.onPage,
12727
12735
  onProgress,
12728
12736
  rateLimit: syncRateLimitOptions$1(timeoutSeconds)
12729
- });
12730
- progress.stop(summary);
12731
- deps.printData(syncOutput$1(summary, cacheMigration));
12737
+ }));
12738
+ progress.stop(outputSummary);
12739
+ deps.printData(syncOutput$1(outputSummary, cacheMigration));
12732
12740
  } catch (error) {
12733
12741
  progress.error();
12734
12742
  const rateLimitError = enrichRateLimitSyncError$1({
@@ -12879,10 +12887,10 @@ const buildMark = (deps) => {
12879
12887
  cost: {
12880
12888
  metered: true,
12881
12889
  cacheable: false,
12882
- unit: "usage_credit",
12890
+ unit: "usage_usd",
12883
12891
  estimate: {
12884
12892
  kind: "per_call",
12885
- credits: creditsForCostBPS(DM_INTERACTION_ENDPOINT_BILLING.costBPS),
12893
+ usageUSD: creditsToUsageUSD(creditsForCostBPS(DM_INTERACTION_ENDPOINT_BILLING.costBPS)),
12886
12894
  basis: "successful upstream write"
12887
12895
  },
12888
12896
  notes: ["Fresh upstream calls are metered."]
@@ -12953,13 +12961,13 @@ const messageIdFrom = (deps, value) => {
12953
12961
  if (token === void 0 || !token.startsWith(prefix)) throw new UsageError("Pass message_id:<id>.");
12954
12962
  return deps.parseResourceId("message_id", token.slice(11));
12955
12963
  };
12956
- const writeCost = (credits) => ({
12964
+ const writeCost = (usageUSD) => ({
12957
12965
  metered: true,
12958
12966
  cacheable: false,
12959
- unit: "usage_credit",
12967
+ unit: "usage_usd",
12960
12968
  estimate: {
12961
12969
  kind: "per_call",
12962
- credits,
12970
+ usageUSD,
12963
12971
  basis: "successful upstream write"
12964
12972
  },
12965
12973
  notes: ["Fresh upstream calls are metered."]
@@ -13180,7 +13188,7 @@ const buildMessageDelete = (deps) => {
13180
13188
  formats: ["json"],
13181
13189
  projection: true
13182
13190
  },
13183
- cost: writeCost(creditsForCostBPS(DM_INTERACTION_ENDPOINT_BILLING.costBPS)),
13191
+ cost: writeCost(creditsToUsageUSD(creditsForCostBPS(DM_INTERACTION_ENDPOINT_BILLING.costBPS))),
13184
13192
  examples: [{ command: "linkedin message <target> delete message_id:<id>" }],
13185
13193
  hazards: [{
13186
13194
  code: "remote_delete",
@@ -13273,7 +13281,7 @@ const buildMessageEdit = (deps) => {
13273
13281
  formats: ["json"],
13274
13282
  projection: true
13275
13283
  },
13276
- cost: writeCost(creditsForCostBPS(DM_INTERACTION_ENDPOINT_BILLING.costBPS)),
13284
+ cost: writeCost(creditsToUsageUSD(creditsForCostBPS(DM_INTERACTION_ENDPOINT_BILLING.costBPS))),
13277
13285
  examples: [{ command: "echo \"fixed text\" | linkedin message <target> edit message_id:<id>" }],
13278
13286
  hazards: [{
13279
13287
  code: "remote_write",
@@ -16913,6 +16921,13 @@ const syncOutput = (data, migration) => ({
16913
16921
  data,
16914
16922
  meta: migration === void 0 ? {} : { cache: { migration } }
16915
16923
  });
16924
+ const syncSummaryForOutput = (summary) => {
16925
+ const { creditsSpent, ...rest } = summary;
16926
+ return {
16927
+ ...rest,
16928
+ usageUSDSpent: creditsToUsageUSD(creditsSpent)
16929
+ };
16930
+ };
16916
16931
  const quoteIdentifier = (identifier) => `\`${identifier.replaceAll("`", "``")}\``;
16917
16932
  const syncTotalRowsFor = (cache, collection) => {
16918
16933
  const totalRows = cache.query(`SELECT count(*) AS totalRows FROM ${quoteIdentifier(collection.key)}`)[0]?.totalRows;
@@ -16977,7 +16992,7 @@ const syncRateLimitOptions = () => ({
16977
16992
  const buildSync = (deps, platform) => defineCommand({
16978
16993
  meta: commandMeta$1({
16979
16994
  name: "sync",
16980
- description: "Sync a collection into the local cache (spends credits)",
16995
+ description: "Sync a collection into the local cache (spends usage)",
16981
16996
  method: "GET",
16982
16997
  capability: "read",
16983
16998
  mutates: true,
@@ -16988,12 +17003,12 @@ const buildSync = (deps, platform) => defineCommand({
16988
17003
  },
16989
17004
  capability: "read",
16990
17005
  hazard: {
16991
- kind: "spends_credits",
17006
+ kind: "spends_usage",
16992
17007
  confirm: "advisory"
16993
17008
  },
16994
17009
  idempotency: {
16995
17010
  kind: "non-idempotent",
16996
- description: "Repeated syncs can spend additional usage credits and update local rows."
17011
+ description: "Repeated syncs can spend additional usage dollars and update local rows."
16997
17012
  },
16998
17013
  method: "GET",
16999
17014
  mutates: true,
@@ -17003,15 +17018,15 @@ const buildSync = (deps, platform) => defineCommand({
17003
17018
  examples: [{ command: "social x sync followers" }],
17004
17019
  cost: {
17005
17020
  metered: true,
17006
- unit: "usage_credit",
17021
+ unit: "usage_usd",
17007
17022
  notes: ["Upstream reads during sync are metered."]
17008
17023
  },
17009
17024
  hazards: [{
17010
17025
  code: "local_cache_write",
17011
17026
  message: "Writes synced X rows and cursor state to the local cache."
17012
17027
  }, {
17013
- code: "usage_credit_spend",
17014
- message: "May spend usage credits while reading upstream X data."
17028
+ code: "usage_usd_spend",
17029
+ message: "May spend usage dollars while reading upstream X data."
17015
17030
  }]
17016
17031
  }
17017
17032
  }),
@@ -17116,7 +17131,7 @@ const buildSync = (deps, platform) => defineCommand({
17116
17131
  onProgress,
17117
17132
  rateLimit: syncRateLimitOptions()
17118
17133
  });
17119
- deps.printData(syncOutput(summary, cacheMigration));
17134
+ deps.printData(syncOutput(syncSummaryForOutput(summary), cacheMigration));
17120
17135
  } catch (error) {
17121
17136
  const rateLimitError = enrichRateLimitSyncError({
17122
17137
  error,
@@ -21399,7 +21414,7 @@ function createEnv(opts) {
21399
21414
  }
21400
21415
  //#endregion
21401
21416
  //#region package.json
21402
- var version$1 = "0.10.2";
21417
+ var version$1 = "0.11.1";
21403
21418
  //#endregion
21404
21419
  //#region src/lib/env.ts
21405
21420
  const URLWithTrailingSlash = url().transform(ensureTrailingSlash);
@@ -22006,21 +22021,44 @@ const numberFromHeader = (headers, name) => {
22006
22021
  const number = Number(value);
22007
22022
  return Number.isFinite(number) ? number : void 0;
22008
22023
  };
22024
+ const usageUSDFromCredits = (credits) => creditsToUsageUSD(credits);
22009
22025
  const costFromContract = (contract, itemCount, cached, headers) => {
22010
22026
  const cost = isRecord$6(contract) && isRecord$6(contract.cost) ? contract.cost : void 0;
22011
22027
  const billedCredits = numberFromHeader(headers, "social-x-credits-used");
22012
22028
  if (billedCredits !== void 0) return {
22013
- credits: billedCredits,
22029
+ usageUSD: usageUSDFromCredits(billedCredits),
22014
22030
  metered: cost?.metered === true && billedCredits > 0
22015
22031
  };
22016
22032
  const estimate = isRecord$6(cost?.estimate) ? cost.estimate : void 0;
22017
- const credits = cached && cost?.cacheHitCost === 0 ? 0 : typeof estimate?.credits === "number" ? estimate.credits : typeof estimate?.creditsPerItem === "number" ? estimate.creditsPerItem * itemCount : void 0;
22033
+ const usageUSD = cached && cost?.cacheHitCost === 0 ? 0 : typeof estimate?.usageUSD === "number" ? estimate.usageUSD : typeof estimate?.usageUSDPerItem === "number" ? estimate.usageUSDPerItem * itemCount : void 0;
22018
22034
  return {
22019
- ...credits === void 0 ? {} : { credits },
22020
- metered: cost?.metered === true && !(cached && credits === 0),
22035
+ ...usageUSD === void 0 ? {} : { usageUSD },
22036
+ metered: cost?.metered === true && !(cached && usageUSD === 0),
22021
22037
  estimated: true
22022
22038
  };
22023
22039
  };
22040
+ const usageSummaryForOutput = (usage) => {
22041
+ if (!(isRecord$6(usage) && isRecord$6(usage.credits))) return usage;
22042
+ const included = typeof usage.credits.included === "number" ? usageUSDFromCredits(usage.credits.included) : usage.credits.included;
22043
+ const used = typeof usage.credits.used === "number" ? usageUSDFromCredits(usage.credits.used) : usage.credits.used;
22044
+ const { credits: _credits, ...rest } = usage;
22045
+ return {
22046
+ ...rest,
22047
+ usageUSD: {
22048
+ included,
22049
+ used
22050
+ }
22051
+ };
22052
+ };
22053
+ const errorBodyForOutput = (body) => {
22054
+ if (Array.isArray(body)) return body.map(errorBodyForOutput);
22055
+ if (!isRecord$6(body)) return body;
22056
+ const entries = Object.entries(body).flatMap(([key, value]) => {
22057
+ if (key === "requiredCredits" && typeof value === "number") return [["requiredUsageUSD", usageUSDFromCredits(value)]];
22058
+ return [[key, errorBodyForOutput(value)]];
22059
+ });
22060
+ return Object.fromEntries(entries);
22061
+ };
22024
22062
  const cacheFromHeaders = (headers) => {
22025
22063
  const status = headers?.get("x-social-cache-status");
22026
22064
  const age = headers?.get("age");
@@ -22069,13 +22107,13 @@ const resultEnvelope = ({ account, contract, data, local, resolved = [], respons
22069
22107
  meta: {
22070
22108
  resolved,
22071
22109
  cost: local === void 0 ? costFromContract(contract, itemCount, cache.hit, responseHeaders) : {
22072
- credits: 0,
22110
+ usageUSD: 0,
22073
22111
  metered: false
22074
22112
  },
22075
22113
  cache,
22076
22114
  ...cursor === void 0 ? {} : { cursor },
22077
22115
  ...totalCount === void 0 ? {} : { totalCount },
22078
- ...usage === void 0 ? {} : { usage }
22116
+ ...usage === void 0 ? {} : { usage: usageSummaryForOutput(usage) }
22079
22117
  }
22080
22118
  };
22081
22119
  };
@@ -22094,7 +22132,7 @@ const errorPayload = (error) => {
22094
22132
  status: error.status,
22095
22133
  code: error.code,
22096
22134
  requestId: error.requestId,
22097
- body: error.body,
22135
+ body: errorBodyForOutput(error.body),
22098
22136
  retryAfterSeconds: error.retryAfterSeconds,
22099
22137
  resumeAt: error.resumeAt,
22100
22138
  retryCommand: error.retryCommand,
@@ -22112,19 +22150,29 @@ const errorPayload = (error) => {
22112
22150
  type: "Error"
22113
22151
  };
22114
22152
  };
22115
- const errorDetails = (error) => Object.fromEntries(Object.entries(error).filter(([key, value]) => ![
22116
- "name",
22117
- "message",
22118
- "stack",
22119
- "cause"
22120
- ].includes(key) && value !== void 0));
22153
+ const errorDetails = (error) => {
22154
+ const details = Object.fromEntries(Object.entries(error).filter(([key, value]) => ![
22155
+ "name",
22156
+ "message",
22157
+ "stack",
22158
+ "cause"
22159
+ ].includes(key) && value !== void 0));
22160
+ if (typeof details.creditsSpent === "number") {
22161
+ const { creditsSpent, ...rest } = details;
22162
+ return {
22163
+ ...rest,
22164
+ usageUSDSpent: usageUSDFromCredits(creditsSpent)
22165
+ };
22166
+ }
22167
+ return details;
22168
+ };
22121
22169
  const apiErrorCause = (error) => ({
22122
22170
  type: error.name,
22123
22171
  error: error.message,
22124
22172
  status: error.status,
22125
22173
  code: error.code,
22126
22174
  requestId: error.requestId,
22127
- body: error.body,
22175
+ body: errorBodyForOutput(error.body),
22128
22176
  retryAfterSeconds: error.retryAfterSeconds,
22129
22177
  resumeAt: error.resumeAt,
22130
22178
  retryCommand: error.retryCommand,
@@ -22530,7 +22578,7 @@ const BillingOutput = object({
22530
22578
  }).nullable(),
22531
22579
  usage: object({
22532
22580
  calls: object({ total: number().int().nonnegative() }),
22533
- credits: object({
22581
+ usageUSD: object({
22534
22582
  included: number().nonnegative(),
22535
22583
  used: number().nonnegative()
22536
22584
  })
@@ -22593,7 +22641,7 @@ const createBillingCommand = (deps = {}) => {
22593
22641
  await writeOutput$2(deps, {
22594
22642
  seats: status.seats,
22595
22643
  subscription: status.subscription,
22596
- usage
22644
+ usage: usageSummaryForOutput(usage)
22597
22645
  });
22598
22646
  }
22599
22647
  });
@@ -28735,13 +28783,16 @@ const errorOutput = (error) => ({
28735
28783
  const isInteractiveTerminal = () => process.stdin.isTTY === true && process.stdout.isTTY === true;
28736
28784
  const nextCommands = ["social account connect linkedin", "social account connect x"];
28737
28785
  const deviceExpiredMessage = "Sign-in expired before approval. Run `social account login` again to restart.";
28786
+ const scopeUpgradeRequiresReauthorization = "Existing CLI session is read-only. Run `social account logout`, then `social account login` to approve a new write-capable session.";
28787
+ const scopeAliasIncludes = (granted, requested) => granted === requested || granted === "read,write";
28738
28788
  /**
28739
28789
  * Drive one step of the non-TTY device-authorization login and map it onto the
28740
28790
  * login output union. The first call starts the device flow and returns
28741
28791
  * `pending_approval`; later calls poll until `logged_in` or `expired`.
28742
28792
  */
28743
- const deviceLoginOutput = async (loginArgs) => {
28744
- const state = await advanceDeviceLogin(parseScopeAlias(loginArgs.scope));
28793
+ const deviceLoginOutput = async (client, loginArgs) => {
28794
+ const scope = parseScopeAlias(loginArgs.scope);
28795
+ const state = await advanceDeviceLogin(scope);
28745
28796
  switch (state.status) {
28746
28797
  case "pending_approval": return {
28747
28798
  status: "pending_approval",
@@ -28753,7 +28804,10 @@ const deviceLoginOutput = async (loginArgs) => {
28753
28804
  };
28754
28805
  case "logged_in": return {
28755
28806
  status: "logged_in",
28756
- account: state.account,
28807
+ account: {
28808
+ ...state.account,
28809
+ scope: (await client.cli.session.upsert({ scopeAlias: scope })).scopeAlias
28810
+ },
28757
28811
  nextCommands
28758
28812
  };
28759
28813
  case "expired": return {
@@ -28843,23 +28897,30 @@ const loginCommand = defineCommand({
28843
28897
  try {
28844
28898
  const client = createORPCAPIClient();
28845
28899
  const existing = await readExistingAuthSession(client);
28846
- if (existing.kind === "existing") if (billingReady(await client.billing.status())) output = alreadyLoggedInOutput(existing.session);
28847
- else if (isInteractiveTerminal()) output = await runLogin({
28848
- ui: createUI(true),
28849
- client,
28850
- args: loginArgs
28851
- }, [{
28852
- name: "seat",
28853
- run: seatPhase
28854
- }], { authenticated: true });
28855
- else output = alreadyLoggedInOutput(existing.session);
28856
- else if (existing.kind === "offline") output = offlineOutput();
28900
+ if (existing.kind === "existing") {
28901
+ const requestedScope = parseScopeAlias(loginArgs.scope);
28902
+ if (!scopeAliasIncludes(existing.session.session.scope, requestedScope)) output = {
28903
+ status: "error",
28904
+ code: "scope_upgrade_requires_reauthorization",
28905
+ message: scopeUpgradeRequiresReauthorization
28906
+ };
28907
+ else if (billingReady(await client.billing.status())) output = alreadyLoggedInOutput(existing.session);
28908
+ else if (isInteractiveTerminal()) output = await runLogin({
28909
+ ui: createUI(true),
28910
+ client,
28911
+ args: loginArgs
28912
+ }, [{
28913
+ name: "seat",
28914
+ run: seatPhase
28915
+ }], { authenticated: true });
28916
+ else output = alreadyLoggedInOutput(existing.session);
28917
+ } else if (existing.kind === "offline") output = offlineOutput();
28857
28918
  else if (isInteractiveTerminal()) output = await runLogin({
28858
28919
  ui: createUI(true),
28859
28920
  client,
28860
28921
  args: loginArgs
28861
28922
  });
28862
- else output = await deviceLoginOutput(loginArgs);
28923
+ else output = await deviceLoginOutput(client, loginArgs);
28863
28924
  } catch (error) {
28864
28925
  output = errorOutput(error);
28865
28926
  exitCode = exitCodeFor(error);
@@ -28992,7 +29053,7 @@ const UsageLogOutput = object({
28992
29053
  "n/a"
28993
29054
  ]),
28994
29055
  errorCode: string().nullable(),
28995
- credits: number().int().nonnegative(),
29056
+ usageUSD: number().nonnegative(),
28996
29057
  latencyMs: number().int().nonnegative(),
28997
29058
  createdAt: ISODateString
28998
29059
  });
@@ -29019,7 +29080,7 @@ const UsageLogsCommandOutput = union([object({
29019
29080
  "n/a"
29020
29081
  ]).optional(),
29021
29082
  calls: number().int().nonnegative(),
29022
- credits: number().nonnegative(),
29083
+ usageUSD: number().nonnegative(),
29023
29084
  errors: number().int().nonnegative()
29024
29085
  })),
29025
29086
  meta: object({
@@ -29030,7 +29091,7 @@ const UsageLogsCommandOutput = union([object({
29030
29091
  })]);
29031
29092
  const UsageSummaryOutput = object({
29032
29093
  calls: object({ total: number().int().nonnegative() }),
29033
- credits: object({
29094
+ usageUSD: object({
29034
29095
  included: number().nonnegative(),
29035
29096
  used: number().nonnegative()
29036
29097
  })
@@ -29038,11 +29099,22 @@ const UsageSummaryOutput = object({
29038
29099
  const USAGE_LOG_PAGE_LIMIT = 100;
29039
29100
  const USAGE_LOG_MAX_AUTO_PAGES = 50;
29040
29101
  const cursorFrom = (usage) => usage.nextCursor ?? null;
29041
- const normalizeUsageLogCreatedAt = (item) => {
29042
- if (typeof item === "object" && item !== null && "createdAt" in item && item.createdAt instanceof Date) return {
29043
- ...item,
29044
- createdAt: item.createdAt.toISOString()
29045
- };
29102
+ const normalizeUsageLogForOutput = (item) => {
29103
+ if (typeof item === "object" && item !== null && "createdAt" in item && item.createdAt instanceof Date) {
29104
+ const { credits, ...rest } = item;
29105
+ return {
29106
+ ...rest,
29107
+ createdAt: item.createdAt.toISOString(),
29108
+ ...typeof credits === "number" ? { usageUSD: creditsToUsageUSD(credits) } : {}
29109
+ };
29110
+ }
29111
+ if (typeof item === "object" && item !== null && "credits" in item) {
29112
+ const { credits, ...rest } = item;
29113
+ return {
29114
+ ...rest,
29115
+ ...typeof credits === "number" ? { usageUSD: creditsToUsageUSD(credits) } : {}
29116
+ };
29117
+ }
29046
29118
  return item;
29047
29119
  };
29048
29120
  const sumByFrom = (value) => {
@@ -29072,7 +29144,7 @@ const fetchUsageLogs = async (client, input) => {
29072
29144
  from: input.from,
29073
29145
  to: input.to
29074
29146
  });
29075
- items.push(...UsageLogOutput.array().parse(usage.items.map(normalizeUsageLogCreatedAt)));
29147
+ items.push(...UsageLogOutput.array().parse(usage.items.map(normalizeUsageLogForOutput)));
29076
29148
  nextCursor = cursorFrom(usage);
29077
29149
  cursor = nextCursor ?? void 0;
29078
29150
  pages += 1;
@@ -29090,15 +29162,15 @@ const aggregateLogs = (logs, fields) => {
29090
29162
  const current = groups.get(key) ?? {
29091
29163
  ...keyFields,
29092
29164
  calls: 0,
29093
- credits: 0,
29165
+ usageUSD: 0,
29094
29166
  errors: 0
29095
29167
  };
29096
29168
  current.calls = Number(current.calls) + 1;
29097
- current.credits = Number(current.credits) + log.credits;
29169
+ current.usageUSD = Number(current.usageUSD) + log.usageUSD;
29098
29170
  current.errors = Number(current.errors) + (log.responseStatus >= 400 ? 1 : 0);
29099
29171
  groups.set(key, current);
29100
29172
  }
29101
- return [...groups.values()].sort((left, right) => Number(right.credits) - Number(left.credits));
29173
+ return [...groups.values()].sort((left, right) => Number(right.usageUSD) - Number(left.usageUSD));
29102
29174
  };
29103
29175
  const createUsageLogsCommand = (deps = {}) => defineCommand({
29104
29176
  meta: commandMeta({
@@ -29192,7 +29264,7 @@ const createUsageCommand = (deps = {}) => defineCommand({
29192
29264
  }),
29193
29265
  args: {},
29194
29266
  run: async () => {
29195
- await writeOutput$1(deps, await (deps.client ?? createORPCAPIClient()).usage.summary({}));
29267
+ await writeOutput$1(deps, usageSummaryForOutput(await (deps.client ?? createORPCAPIClient()).usage.summary({})));
29196
29268
  }
29197
29269
  });
29198
29270
  //#endregion
@@ -34787,7 +34859,7 @@ const CLIHazardMetadata = object({
34787
34859
  }).strict();
34788
34860
  const CLIAdvisoryHazardMetadata = object({
34789
34861
  kind: _enum([
34790
- "spends_credits",
34862
+ "spends_usage",
34791
34863
  "destructive",
34792
34864
  "outbound_write"
34793
34865
  ]),
@@ -35134,7 +35206,7 @@ const schemaCommand = defineCommand({
35134
35206
  path: []
35135
35207
  } : commandAtPath(rootCommand, parts);
35136
35208
  printData({
35137
- schemaVersion: "1.0",
35209
+ schemaVersion: "2.0",
35138
35210
  commands: Object.fromEntries(leafSchemasForCommand(command, path))
35139
35211
  });
35140
35212
  return;
@@ -35145,28 +35217,28 @@ const schemaCommand = defineCommand({
35145
35217
  path: []
35146
35218
  } : commandAtPath(rootCommand, parts);
35147
35219
  printData({
35148
- schemaVersion: "1.0",
35220
+ schemaVersion: "2.0",
35149
35221
  commands: Object.fromEntries(compactLeafSchemasForCommand(command, path))
35150
35222
  });
35151
35223
  return;
35152
35224
  }
35153
35225
  if (parts.length === 0) {
35154
35226
  printData({
35155
- schemaVersion: "1.0",
35227
+ schemaVersion: "2.0",
35156
35228
  ...treeForCommand(rootCommand)
35157
35229
  });
35158
35230
  return;
35159
35231
  }
35160
35232
  const { command, path, positionalMatch } = commandAtPath(rootCommand, parts);
35161
35233
  printData(positionalMatch ? {
35162
- schemaVersion: "1.0",
35234
+ schemaVersion: "2.0",
35163
35235
  ...schemaForCommand(command, path),
35164
35236
  ...positionalMatch
35165
35237
  } : command.subCommands && typeof command.run !== "function" ? {
35166
- schemaVersion: "1.0",
35238
+ schemaVersion: "2.0",
35167
35239
  ...treeForCommand(command, path)
35168
35240
  } : {
35169
- schemaVersion: "1.0",
35241
+ schemaVersion: "2.0",
35170
35242
  ...schemaForCommand(command, path)
35171
35243
  });
35172
35244
  }