deepline 0.1.104 → 0.1.106

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.
@@ -216,10 +216,13 @@ var SDK_RELEASE = {
216
216
  // scrubbing, and word-boundary watch truncation.
217
217
  // 0.1.103 ships the refined SDK CLI command surface.
218
218
  // 0.1.104 ships postgres_fast suspension/billing parity and runtime worker hardening.
219
- version: "0.1.104",
219
+ // 0.1.105 ships the billing catalog surface: billing plans, subscribe,
220
+ // subscription status/cancel, invoices, and the client.billing namespace.
221
+ // 0.1.106 ships play cell provenance metadata and v2 preview retry hardening.
222
+ version: "0.1.106",
220
223
  apiContract: "2026-06-dataset-column-cell-stale-hard-cutover",
221
224
  supportPolicy: {
222
- latest: "0.1.104",
225
+ latest: "0.1.106",
223
226
  minimumSupported: "0.1.53",
224
227
  deprecatedBelow: "0.1.53"
225
228
  }
@@ -350,7 +353,7 @@ var HttpClient = class {
350
353
  signal: controller.signal
351
354
  });
352
355
  clearTimeout(timeoutId);
353
- if (response.status === 401 || response.status === 403) {
356
+ if (response.status === 401 || response.status === 403 && !options?.forbiddenAsApiError) {
354
357
  throw new AuthError();
355
358
  }
356
359
  if (response.status === 429) {
@@ -1442,6 +1445,9 @@ var INCLUDE_TOOL_METADATA_HEADER = "x-deepline-include-tool-metadata";
1442
1445
  var EXECUTE_RESPONSE_CONTRACT_HEADER = "x-deepline-execute-response-contract";
1443
1446
  var V2_EXECUTE_RESPONSE_CONTRACT = "v2-tool-response";
1444
1447
  var COMPILE_MANIFEST_RETRY_DELAYS_MS = [250, 1e3];
1448
+ var REGISTER_PLAY_ARTIFACTS_COMPILE_CONCURRENCY = 3;
1449
+ var REGISTER_PLAY_ARTIFACTS_MAX_BATCH_COUNT = 3;
1450
+ var REGISTER_PLAY_ARTIFACTS_MAX_BATCH_BYTES = 25e5;
1445
1451
  function sleep2(ms) {
1446
1452
  return new Promise((resolve16) => setTimeout(resolve16, ms));
1447
1453
  }
@@ -1454,6 +1460,45 @@ function isTransientCompileManifestError(error) {
1454
1460
  message
1455
1461
  );
1456
1462
  }
1463
+ async function mapWithConcurrency(items, concurrency, mapper) {
1464
+ const results = new Array(items.length);
1465
+ let nextIndex = 0;
1466
+ const workerCount = Math.min(Math.max(1, concurrency), items.length);
1467
+ await Promise.all(
1468
+ Array.from({ length: workerCount }, async () => {
1469
+ for (; ; ) {
1470
+ const index = nextIndex;
1471
+ nextIndex += 1;
1472
+ if (index >= items.length) {
1473
+ return;
1474
+ }
1475
+ results[index] = await mapper(items[index], index);
1476
+ }
1477
+ })
1478
+ );
1479
+ return results;
1480
+ }
1481
+ function jsonUtf8Bytes(value) {
1482
+ return new TextEncoder().encode(JSON.stringify(value)).length;
1483
+ }
1484
+ function chunkRegisterPlayArtifacts(artifacts) {
1485
+ const chunks = [];
1486
+ let current = [];
1487
+ for (const artifact of artifacts) {
1488
+ const candidate = [...current, artifact];
1489
+ const candidateTooLarge = candidate.length > REGISTER_PLAY_ARTIFACTS_MAX_BATCH_COUNT || jsonUtf8Bytes({ artifacts: candidate }) > REGISTER_PLAY_ARTIFACTS_MAX_BATCH_BYTES;
1490
+ if (current.length > 0 && candidateTooLarge) {
1491
+ chunks.push(current);
1492
+ current = [artifact];
1493
+ } else {
1494
+ current = candidate;
1495
+ }
1496
+ }
1497
+ if (current.length > 0) {
1498
+ chunks.push(current);
1499
+ }
1500
+ return chunks;
1501
+ }
1457
1502
  var RUN_LOGS_PAGE_LIMIT = 1e3;
1458
1503
  function isRecord2(value) {
1459
1504
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
@@ -1621,6 +1666,8 @@ var DeeplineClient = class {
1621
1666
  config;
1622
1667
  /** Canonical run lifecycle namespace backed by `/api/v2/runs`. */
1623
1668
  runs;
1669
+ /** Billing namespace: subscription status/cancel and invoice history. */
1670
+ billing;
1624
1671
  /**
1625
1672
  * Create a low-level SDK client.
1626
1673
  *
@@ -1641,6 +1688,16 @@ var DeeplineClient = class {
1641
1688
  exportDatasetRows: (input2) => this.getPlaySheetRows(input2),
1642
1689
  stop: (runId, options2) => this.stopRun(runId, options2)
1643
1690
  };
1691
+ this.billing = {
1692
+ plans: () => this.getBillingPlans(),
1693
+ subscription: {
1694
+ status: () => this.getBillingSubscriptionStatus(),
1695
+ cancel: (options2) => this.cancelBillingSubscription(options2)
1696
+ },
1697
+ invoices: {
1698
+ list: (options2) => this.listBillingInvoices(options2)
1699
+ }
1700
+ };
1644
1701
  }
1645
1702
  /** The resolved base URL this client is targeting (e.g. `"http://localhost:3000"`). */
1646
1703
  get baseUrl() {
@@ -2009,8 +2066,13 @@ var DeeplineClient = class {
2009
2066
  * first when a compiler manifest is not already supplied.
2010
2067
  */
2011
2068
  async registerPlayArtifacts(artifacts) {
2012
- const compiledArtifacts = await Promise.all(
2013
- artifacts.map(async (artifact) => ({
2069
+ if (artifacts.length === 0) {
2070
+ return this.http.post("/api/v2/plays/artifacts", { artifacts });
2071
+ }
2072
+ const compiledArtifacts = await mapWithConcurrency(
2073
+ artifacts,
2074
+ REGISTER_PLAY_ARTIFACTS_COMPILE_CONCURRENCY,
2075
+ async (artifact) => ({
2014
2076
  ...artifact,
2015
2077
  compilerManifest: artifact.compilerManifest ?? await this.compilePlayManifest({
2016
2078
  name: artifact.name,
@@ -2018,11 +2080,20 @@ var DeeplineClient = class {
2018
2080
  sourceFiles: artifact.sourceFiles,
2019
2081
  artifact: artifact.artifact
2020
2082
  })
2021
- }))
2083
+ })
2022
2084
  );
2023
- return this.http.post("/api/v2/plays/artifacts", {
2024
- artifacts: compiledArtifacts
2025
- });
2085
+ const responses = [];
2086
+ for (const chunk of chunkRegisterPlayArtifacts(compiledArtifacts)) {
2087
+ responses.push(
2088
+ await this.http.post("/api/v2/plays/artifacts", {
2089
+ artifacts: chunk
2090
+ })
2091
+ );
2092
+ }
2093
+ return {
2094
+ success: responses.every((response) => response.success),
2095
+ artifacts: responses.flatMap((response) => response.artifacts)
2096
+ };
2026
2097
  }
2027
2098
  /**
2028
2099
  * Compile a bundled play artifact into the server-side compiler manifest.
@@ -2995,6 +3066,61 @@ var DeeplineClient = class {
2995
3066
  // ——————————————————————————————————————————————————————————
2996
3067
  // Health
2997
3068
  // ——————————————————————————————————————————————————————————
3069
+ /**
3070
+ * Published plans plus the caller's active plan: prices, monthly grant
3071
+ * credits, rollover policy, and which plans are open for subscription.
3072
+ * Prefer `client.billing.plans()`.
3073
+ *
3074
+ * @returns Snake_case catalog from `GET /api/v2/billing/catalog/current`
3075
+ */
3076
+ async getBillingPlans() {
3077
+ return this.http.get("/api/v2/billing/catalog/current");
3078
+ }
3079
+ /**
3080
+ * Subscription state for the active workspace: active plan, whether a
3081
+ * Stripe subscription backs it, renewal/cancellation facts, and remaining
3082
+ * Deepline credit pools. Prefer `client.billing.subscription.status()`.
3083
+ *
3084
+ * @returns Snake_case subscription status from `GET /api/v2/billing/subscription/status`
3085
+ */
3086
+ async getBillingSubscriptionStatus() {
3087
+ return this.http.get(
3088
+ "/api/v2/billing/subscription/status"
3089
+ );
3090
+ }
3091
+ /**
3092
+ * Schedule subscription cancellation at period end, or reverse a pending
3093
+ * cancellation with `{ undo: true }`. The customer keeps the cycle they
3094
+ * paid for and every remaining credit — cancellation never claws back
3095
+ * credits. Prefer `client.billing.subscription.cancel(...)`.
3096
+ *
3097
+ * @throws {@link DeeplineError} with `statusCode: 409` when the workspace
3098
+ * has no active subscription, and `statusCode: 502` when Stripe rejects
3099
+ * the update (the server message is preserved).
3100
+ */
3101
+ async cancelBillingSubscription(options) {
3102
+ return this.http.post(
3103
+ "/api/v2/billing/subscription/cancel",
3104
+ { action: options?.undo ? "undo_cancel" : "cancel" }
3105
+ );
3106
+ }
3107
+ /**
3108
+ * Customer-facing billing history: subscription invoices plus one-time
3109
+ * credit purchase receipts, newest first, with Stripe-hosted links.
3110
+ * Prefer `client.billing.invoices.list(...)`.
3111
+ *
3112
+ * @param options.limit - Maximum entries to return (server clamps to 1–100, default 24).
3113
+ */
3114
+ async listBillingInvoices(options) {
3115
+ const params = new URLSearchParams();
3116
+ if (options?.limit !== void 0) {
3117
+ params.set("limit", String(options.limit));
3118
+ }
3119
+ const suffix = Array.from(params).length > 0 ? `?${params.toString()}` : "";
3120
+ return this.http.get(
3121
+ `/api/v2/billing/invoices${suffix}`
3122
+ );
3123
+ }
2998
3124
  /**
2999
3125
  * Check API connectivity and server health.
3000
3126
  *
@@ -4131,6 +4257,56 @@ import { Command } from "commander";
4131
4257
  import { appendFile, mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
4132
4258
  import { dirname as dirname4, resolve as resolve3 } from "path";
4133
4259
  import { stringify as stringify2 } from "csv-stringify/sync";
4260
+ var SUBSCRIPTION_STATUS_NEXT_COMMAND = "deepline billing subscription status --json";
4261
+ var SUBSCRIPTION_CANCEL_PATH = "/api/v2/billing/subscription/cancel";
4262
+ function billingFailureFromError(error, options) {
4263
+ if (error instanceof AuthError) {
4264
+ return {
4265
+ exitCode: 3,
4266
+ code: "AUTH_ERROR",
4267
+ message: error.message,
4268
+ next: "deepline auth status --json"
4269
+ };
4270
+ }
4271
+ if (!(error instanceof DeeplineError) || typeof error.statusCode !== "number") {
4272
+ return null;
4273
+ }
4274
+ if (error.statusCode === 404 || error.statusCode === 409) {
4275
+ return {
4276
+ exitCode: 4,
4277
+ code: options.notFoundCode,
4278
+ message: error.message,
4279
+ next: SUBSCRIPTION_STATUS_NEXT_COMMAND
4280
+ };
4281
+ }
4282
+ if (error.statusCode >= 500) {
4283
+ return {
4284
+ exitCode: 5,
4285
+ code: "BILLING_SERVER_ERROR",
4286
+ message: error.message,
4287
+ next: SUBSCRIPTION_STATUS_NEXT_COMMAND
4288
+ };
4289
+ }
4290
+ return null;
4291
+ }
4292
+ function reportBillingFailure(failure, options) {
4293
+ const textLines = [failure.message];
4294
+ if (failure.next) {
4295
+ textLines.push(`Next: ${failure.next}`);
4296
+ }
4297
+ printCommandEnvelope(
4298
+ {
4299
+ ok: false,
4300
+ exitCode: failure.exitCode,
4301
+ code: failure.code,
4302
+ message: failure.message,
4303
+ ...failure.next ? { next: failure.next } : {}
4304
+ },
4305
+ { json: options.json, text: `${textLines.join("\n")}
4306
+ ` }
4307
+ );
4308
+ process.exitCode = failure.exitCode;
4309
+ }
4134
4310
  function humanize(value) {
4135
4311
  return String(value || "").split("_").filter(Boolean).map((token) => token[0]?.toUpperCase() + token.slice(1)).join(" ") || "Unknown";
4136
4312
  }
@@ -4406,6 +4582,273 @@ async function handleLedgerExportAll(options) {
4406
4582
  { json: options.json }
4407
4583
  );
4408
4584
  }
4585
+ function planPriceText(priceUsd, priceInterval) {
4586
+ if (priceUsd === null || priceUsd === void 0) {
4587
+ return "no list price";
4588
+ }
4589
+ return `$${priceUsd}${priceInterval ? `/${priceInterval}` : ""}`;
4590
+ }
4591
+ function planRolloverText(rollover) {
4592
+ const mode = rollover?.mode ?? "none";
4593
+ if (mode === "none") return "no rollover";
4594
+ if (mode === "bounded") {
4595
+ return `rollover up to ${rollover?.max_credits ?? "(unknown)"} credits`;
4596
+ }
4597
+ return `rollover ${mode}`;
4598
+ }
4599
+ async function handlePlans(options) {
4600
+ const { http } = getAuthedHttpClient();
4601
+ const payload = await http.get(
4602
+ "/api/v2/billing/catalog/current"
4603
+ );
4604
+ const activePlan = payload.active_plan ?? {};
4605
+ const plans = Array.isArray(payload.plans) ? payload.plans : [];
4606
+ const metrics = Array.isArray(payload.metrics) ? payload.metrics : [];
4607
+ const lines = [
4608
+ `Catalog: ${payload.catalog_id ?? "(unknown)"} (version ${payload.catalog_version ?? "(unknown)"})`,
4609
+ `Active plan: ${activePlan.public_name ?? "(unknown)"} (${activePlan.plan_version_id ?? "(unknown)"})`,
4610
+ `Assigned by: ${activePlan.assigned_by ?? "default"} | subscription: ${activePlan.has_subscription ? "yes" : "no"}`,
4611
+ ...plans.length === 0 ? ["Plans: none published"] : [
4612
+ "Plans:",
4613
+ ...plans.map(
4614
+ (plan) => `${plan.public_name ?? "(unknown)"} (${plan.plan_version_id ?? "(unknown)"}) | ${planPriceText(plan.price_usd, plan.price_interval)} | ${plan.monthly_grant_credits ?? 0} credits/cycle | ${planRolloverText(plan.rollover)} | ${plan.acquirable ? "acquirable" : "not acquirable"}`
4615
+ )
4616
+ ],
4617
+ ...metrics.length === 0 ? ["Metrics: none"] : [
4618
+ "Metrics:",
4619
+ ...metrics.map(
4620
+ (metric) => `${metric.id ?? "(unknown)"} | ${metric.name ?? "(unknown)"}`
4621
+ )
4622
+ ]
4623
+ ];
4624
+ printCommandEnvelope(
4625
+ {
4626
+ ...payload,
4627
+ render: { sections: [{ title: "billing plans", lines }] }
4628
+ },
4629
+ { json: options.json }
4630
+ );
4631
+ }
4632
+ async function handleSubscribe(planVersionId, options) {
4633
+ const { http } = getAuthedHttpClient();
4634
+ const payload = await http.request(
4635
+ "/api/v2/billing/subscription/checkout",
4636
+ {
4637
+ method: "POST",
4638
+ body: { plan_version_id: planVersionId },
4639
+ forbiddenAsApiError: true
4640
+ }
4641
+ );
4642
+ const url = String(payload.checkout_url || "");
4643
+ if (!options.json && options.open !== false && url) openInBrowser(url);
4644
+ printCommandEnvelope(
4645
+ {
4646
+ ...payload,
4647
+ render: {
4648
+ sections: [
4649
+ {
4650
+ title: "billing subscribe",
4651
+ lines: [url || "Subscription checkout session created."]
4652
+ }
4653
+ ]
4654
+ }
4655
+ },
4656
+ { json: options.json }
4657
+ );
4658
+ }
4659
+ async function handleSubscriptionStatus(options) {
4660
+ const client2 = new DeeplineClient();
4661
+ const payload = await client2.billing.subscription.status();
4662
+ const pools = payload.credit_pools ?? [];
4663
+ const lines = [
4664
+ `Plan: ${payload.plan_name ?? "(unknown)"} (${payload.plan_version_id ?? "(unknown)"})`,
4665
+ `Subscribed: ${payload.subscribed ? "yes" : "no"}`,
4666
+ ...payload.cancel_at_period_end ? [
4667
+ `Cancellation scheduled: ends ${payload.current_period_end ?? "(unknown)"} at period end (credits are kept)`
4668
+ ] : [],
4669
+ `Price: ${planPriceText(payload.price_usd, payload.price_interval)}`,
4670
+ `Monthly grant: ${payload.monthly_grant_credits ?? 0} credits`,
4671
+ `Pooled credits remaining: ${payload.pooled_credits_remaining ?? 0}`,
4672
+ ...pools.length === 0 ? ["Credit pools: none"] : [
4673
+ "Credit pools:",
4674
+ ...pools.map(
4675
+ (pool) => `${pool.pool ?? "(unknown)"} | ${pool.credits_remaining ?? 0}/${pool.credits_granted ?? 0} credits remaining | ${pool.source ?? "(unknown)"}`
4676
+ )
4677
+ ],
4678
+ `Assigned by: ${payload.assigned_by ?? "default"}`
4679
+ ];
4680
+ printCommandEnvelope(
4681
+ {
4682
+ ...payload,
4683
+ render: { sections: [{ title: "billing subscription", lines }] }
4684
+ },
4685
+ { json: options.json }
4686
+ );
4687
+ }
4688
+ async function handleSubscriptionCancel(options) {
4689
+ const client2 = new DeeplineClient();
4690
+ const action = options.undo ? "undo_cancel" : "cancel";
4691
+ if (options.dryRun) {
4692
+ const status = await client2.billing.subscription.status();
4693
+ if (!status.subscribed) {
4694
+ reportBillingFailure(
4695
+ {
4696
+ exitCode: 4,
4697
+ code: "NO_ACTIVE_SUBSCRIPTION",
4698
+ message: "This workspace has no active subscription to cancel.",
4699
+ next: SUBSCRIPTION_STATUS_NEXT_COMMAND
4700
+ },
4701
+ options
4702
+ );
4703
+ return;
4704
+ }
4705
+ const consequence = action === "cancel" ? `Would schedule cancellation at period end${status.current_period_end ? ` (${status.current_period_end})` : ""}. The subscription stays active until then and remaining credits are kept.` : "Would reverse the pending cancellation; the subscription would renew normally.";
4706
+ printCommandEnvelope(
4707
+ {
4708
+ ok: true,
4709
+ dry_run: true,
4710
+ action,
4711
+ plan_version_id: status.plan_version_id,
4712
+ plan_name: status.plan_name,
4713
+ cancel_at_period_end: status.cancel_at_period_end,
4714
+ current_period_end: status.current_period_end,
4715
+ consequence,
4716
+ planned_request: {
4717
+ method: "POST",
4718
+ path: SUBSCRIPTION_CANCEL_PATH,
4719
+ body: { action }
4720
+ },
4721
+ render: {
4722
+ sections: [
4723
+ {
4724
+ title: "billing subscription cancel (dry run)",
4725
+ lines: [
4726
+ `Plan: ${status.plan_name} (${status.plan_version_id})`,
4727
+ `Planned request: POST ${SUBSCRIPTION_CANCEL_PATH} {"action":"${action}"}`,
4728
+ consequence,
4729
+ "No request was sent. Re-run without --dry-run to apply."
4730
+ ]
4731
+ }
4732
+ ]
4733
+ }
4734
+ },
4735
+ { json: options.json }
4736
+ );
4737
+ return;
4738
+ }
4739
+ let result;
4740
+ try {
4741
+ result = await client2.billing.subscription.cancel({
4742
+ undo: Boolean(options.undo)
4743
+ });
4744
+ } catch (error) {
4745
+ const failure = billingFailureFromError(error, {
4746
+ notFoundCode: "NO_ACTIVE_SUBSCRIPTION"
4747
+ });
4748
+ if (!failure) throw error;
4749
+ reportBillingFailure(failure, options);
4750
+ return;
4751
+ }
4752
+ const lines = options.undo ? [
4753
+ "Pending cancellation reversed; the subscription will renew normally.",
4754
+ `Subscription: ${result.subscription_id}`
4755
+ ] : [
4756
+ `Cancellation scheduled for subscription ${result.subscription_id}.`,
4757
+ `The subscription stays active until ${result.current_period_end ?? "the end of the current billing period"}, then cancels at period end.`,
4758
+ "Remaining credits are yours to keep \u2014 cancellation never removes credits.",
4759
+ "Undo with: deepline billing subscription cancel --undo"
4760
+ ];
4761
+ printCommandEnvelope(
4762
+ {
4763
+ ok: true,
4764
+ ...result,
4765
+ render: {
4766
+ sections: [{ title: "billing subscription cancel", lines }]
4767
+ }
4768
+ },
4769
+ { json: options.json }
4770
+ );
4771
+ }
4772
+ function invoiceAmountText(amountCents, currency) {
4773
+ const value = (Number(amountCents ?? 0) / 100).toFixed(2);
4774
+ return String(currency ?? "usd").toLowerCase() === "usd" ? `$${value}` : `${value} ${String(currency).toUpperCase()}`;
4775
+ }
4776
+ function invoiceDateText(createdAt) {
4777
+ return String(createdAt ?? "").slice(0, 10);
4778
+ }
4779
+ function invoiceLine(entry, compact) {
4780
+ const amount = invoiceAmountText(entry.amount_cents, entry.currency);
4781
+ const link = entry.url ?? "(no link)";
4782
+ if (compact) {
4783
+ return [
4784
+ entry.id,
4785
+ invoiceDateText(entry.created_at),
4786
+ amount,
4787
+ entry.status,
4788
+ link
4789
+ ].join(" | ");
4790
+ }
4791
+ return [
4792
+ invoiceDateText(entry.created_at),
4793
+ entry.description,
4794
+ amount,
4795
+ entry.status,
4796
+ link
4797
+ ].join(" | ");
4798
+ }
4799
+ async function handleInvoices(options) {
4800
+ let limit;
4801
+ if (options.limit !== void 0) {
4802
+ limit = Number.parseInt(options.limit, 10);
4803
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
4804
+ reportBillingFailure(
4805
+ {
4806
+ exitCode: 2,
4807
+ code: "INVALID_LIMIT",
4808
+ message: "--limit must be an integer between 1 and 100."
4809
+ },
4810
+ options
4811
+ );
4812
+ return;
4813
+ }
4814
+ }
4815
+ const client2 = new DeeplineClient();
4816
+ let payload;
4817
+ try {
4818
+ payload = await client2.billing.invoices.list(
4819
+ limit === void 0 ? void 0 : { limit }
4820
+ );
4821
+ } catch (error) {
4822
+ const failure = billingFailureFromError(error, {
4823
+ notFoundCode: "NOT_FOUND"
4824
+ });
4825
+ if (!failure) throw error;
4826
+ reportBillingFailure(failure, options);
4827
+ return;
4828
+ }
4829
+ const entries = Array.isArray(payload.entries) ? payload.entries : [];
4830
+ const compact = Boolean(options.compact);
4831
+ const header = compact ? "id | date | amount | status | link" : "date | description | amount | status | link";
4832
+ const lines = entries.length === 0 ? ["No invoices or receipts yet."] : [header, ...entries.map((entry) => invoiceLine(entry, compact))];
4833
+ const envelope = compact ? {
4834
+ org_id: payload.org_id,
4835
+ count: entries.length,
4836
+ entries: entries.map((entry) => ({
4837
+ id: entry.id,
4838
+ date: invoiceDateText(entry.created_at),
4839
+ amount: invoiceAmountText(entry.amount_cents, entry.currency),
4840
+ status: entry.status,
4841
+ url: entry.url
4842
+ }))
4843
+ } : { ...payload, count: entries.length };
4844
+ printCommandEnvelope(
4845
+ {
4846
+ ...envelope,
4847
+ render: { sections: [{ title: "billing invoices", lines }] }
4848
+ },
4849
+ { json: options.json }
4850
+ );
4851
+ }
4409
4852
  async function handleCheckout(options) {
4410
4853
  const { http } = getAuthedHttpClient();
4411
4854
  const payload = await http.post(
@@ -4454,19 +4897,33 @@ async function handleRedeemCode(code, options) {
4454
4897
  );
4455
4898
  }
4456
4899
  function registerBillingCommands(program) {
4457
- const billing = program.command("billing").description("Inspect balance, usage, limits, and checkout flows.").addHelpText(
4900
+ const billing = program.command("billing").description("See your plan and credits, buy more, and manage billing.").addHelpText(
4458
4901
  "after",
4459
4902
  `
4460
4903
  Concepts:
4461
4904
  Billing commands show Deepline credits, not raw provider spend.
4462
- set-limit/off mutate the monthly workspace cap. checkout/redeem-code can open
4463
- a browser unless --no-open is set.
4905
+ checkout/subscribe/redeem-code can open a browser unless --no-open is set.
4464
4906
 
4465
4907
  Examples:
4908
+ # See where you stand
4466
4909
  deepline billing balance --json
4467
4910
  deepline billing usage --limit 20 --json
4468
- deepline billing set-limit 500 --json
4911
+ deepline billing plans --json
4912
+ deepline billing subscription status --json
4913
+
4914
+ # Buy credits or a plan
4469
4915
  deepline billing checkout --credits 1000 --no-open --json
4916
+ deepline billing subscribe runtime-395-2026-07-v1 --no-open --json
4917
+ deepline billing redeem-code --code ABC123 --no-open --json
4918
+
4919
+ # Manage
4920
+ deepline billing subscription cancel --dry-run --json
4921
+ deepline billing set-limit 500 --json
4922
+
4923
+ # Records
4924
+ deepline billing invoices --limit 12 --json
4925
+ deepline billing history --time 1m --json
4926
+ deepline billing ledger export all --json
4470
4927
  `
4471
4928
  );
4472
4929
  billing.command("balance").description("Show current billing balance.").addHelpText(
@@ -4592,6 +5049,110 @@ Examples:
4592
5049
  deepline billing checkout --credits 1000 --discount-code LAUNCH --no-open
4593
5050
  `
4594
5051
  ).option("--tier <tierId>", "Named pricing tier").option("--credits <credits>", "Custom credit amount").option("--discount-code <code>", "Apply a discount code").option("--no-open", "Print the checkout URL without opening a browser").option("--json", "Emit JSON output. Also automatic when stdout is piped").action(handleCheckout);
5052
+ billing.command("plans").description("Show published plans and the plan you are on.").addHelpText(
5053
+ "after",
5054
+ `
5055
+ Notes:
5056
+ Read-only. Answers "what plans exist and what am I on": each plan's price,
5057
+ monthly grant credits, rollover policy, and whether it is open for
5058
+ subscription, plus the catalog's usage metrics. All amounts are Deepline
5059
+ credits and Deepline-facing USD, never raw provider spend. Subscribe to a
5060
+ listed plan with: deepline billing subscribe <plan_version_id>
5061
+
5062
+ Examples:
5063
+ deepline billing plans
5064
+ deepline billing plans --json
5065
+ `
5066
+ ).option("--json", "Emit JSON output. Also automatic when stdout is piped").action(handlePlans);
5067
+ billing.command("subscribe").description(
5068
+ "Start a subscription checkout for a plan and optionally open it in your browser."
5069
+ ).addHelpText(
5070
+ "after",
5071
+ `
5072
+ Notes:
5073
+ Creates a Stripe subscription checkout session for the given plan version.
5074
+ Opens the checkout URL in a browser unless --no-open is set. Fails loudly
5075
+ with the server error when subscription checkout is not enabled or the plan
5076
+ is not open for subscription.
5077
+
5078
+ Examples:
5079
+ deepline billing subscribe runtime-395-2026-07-v1
5080
+ deepline billing subscribe runtime-395-2026-07-v1 --no-open --json
5081
+ `
5082
+ ).argument("<plan_version_id>", "Plan version id from `billing plans`").option("--no-open", "Print the checkout URL without opening a browser").option("--json", "Emit JSON output. Also automatic when stdout is piped").action(handleSubscribe);
5083
+ billing.command("subscription").description("Inspect and manage subscription state for the workspace.").addHelpText(
5084
+ "after",
5085
+ `
5086
+ Examples:
5087
+ deepline billing subscription status
5088
+ deepline billing subscription status --json
5089
+ deepline billing subscription cancel --dry-run
5090
+ deepline billing subscription cancel --json
5091
+ deepline billing subscription cancel --undo --json
5092
+ `
5093
+ ).addCommand(
5094
+ new Command("status").description("Show active plan, subscription state, and credit pools.").addHelpText(
5095
+ "after",
5096
+ `
5097
+ Notes:
5098
+ Read-only. Shows the active plan, whether a Stripe subscription backs it,
5099
+ scheduled cancellation state, and remaining Deepline credits per grant pool.
5100
+
5101
+ Examples:
5102
+ deepline billing subscription status
5103
+ deepline billing subscription status --json
5104
+ `
5105
+ ).option(
5106
+ "--json",
5107
+ "Emit JSON output. Also automatic when stdout is piped"
5108
+ ).action(handleSubscriptionStatus)
5109
+ ).addCommand(
5110
+ new Command("cancel").description("Cancel the subscription at period end. Credits are kept.").addHelpText(
5111
+ "after",
5112
+ `
5113
+ Notes:
5114
+ Mutates subscription state. Cancellation is always AT PERIOD END: the
5115
+ subscription stays active until the end of the paid cycle and remaining
5116
+ Deepline credits are kept \u2014 cancellation never removes credits. --undo
5117
+ reverses a pending cancellation before the period ends. --dry-run reads
5118
+ subscription status and prints the planned mutation without calling the
5119
+ cancel endpoint.
5120
+
5121
+ Exit codes:
5122
+ 0 cancellation scheduled (or reversed with --undo)
5123
+ 3 auth error
5124
+ 4 no active subscription to cancel
5125
+ 5 Stripe/server failure (the server message is preserved)
5126
+
5127
+ Examples:
5128
+ deepline billing subscription cancel --dry-run
5129
+ deepline billing subscription cancel
5130
+ deepline billing subscription cancel --undo
5131
+ deepline billing subscription cancel --json
5132
+ `
5133
+ ).option("--undo", "Reverse a pending cancellation before period end").option(
5134
+ "--dry-run",
5135
+ "Print the planned cancellation without calling the cancel endpoint"
5136
+ ).option(
5137
+ "--json",
5138
+ "Emit JSON output. Also automatic when stdout is piped"
5139
+ ).action(handleSubscriptionCancel)
5140
+ );
5141
+ billing.command("invoices").description("List subscription invoices and credit purchase receipts.").addHelpText(
5142
+ "after",
5143
+ `
5144
+ Notes:
5145
+ Read-only. Shows customer-facing billing history from Stripe, newest first:
5146
+ subscription invoices plus one-time Deepline credit purchase receipts, with
5147
+ Stripe-hosted links. Amounts are what you paid \u2014 never provider spend.
5148
+ --compact keeps id/date/amount/status/url only.
5149
+
5150
+ Examples:
5151
+ deepline billing invoices
5152
+ deepline billing invoices --limit 12 --json
5153
+ deepline billing invoices --compact --json
5154
+ `
5155
+ ).option("--limit <n>", "Maximum entries to return (1-100, default 24)").option("--compact", "Keep only id, date, amount, status, and url").option("--json", "Emit JSON output. Also automatic when stdout is piped").action(handleInvoices);
4595
5156
  billing.command("redeem-code").description("Redeem a billing code.").addHelpText(
4596
5157
  "after",
4597
5158
  `
@@ -11728,8 +12289,13 @@ function exportableSheetRow(row) {
11728
12289
  function mergeExportColumns(preferredColumns, rows) {
11729
12290
  const columns = [];
11730
12291
  const seen = /* @__PURE__ */ new Set();
12292
+ const hasActualColumn = (column) => rows.some((row) => Object.prototype.hasOwnProperty.call(row, column));
12293
+ const hasCanonicalReplacement = (column) => {
12294
+ const canonical = sqlSafeExportColumnName(column);
12295
+ return canonical !== column && hasActualColumn(canonical);
12296
+ };
11731
12297
  for (const column of preferredColumns) {
11732
- if (!column || seen.has(column)) {
12298
+ if (!column || seen.has(column) || hasCanonicalReplacement(column)) {
11733
12299
  continue;
11734
12300
  }
11735
12301
  seen.add(column);
@@ -11737,7 +12303,7 @@ function mergeExportColumns(preferredColumns, rows) {
11737
12303
  }
11738
12304
  for (const row of rows) {
11739
12305
  for (const column of Object.keys(row)) {
11740
- if (seen.has(column)) {
12306
+ if (seen.has(column) || hasCanonicalReplacement(column)) {
11741
12307
  continue;
11742
12308
  }
11743
12309
  seen.add(column);
@@ -11746,6 +12312,11 @@ function mergeExportColumns(preferredColumns, rows) {
11746
12312
  }
11747
12313
  return columns;
11748
12314
  }
12315
+ function sqlSafeExportColumnName(id) {
12316
+ const normalized = id.trim().replace(/\.+/g, "__").replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
12317
+ const safe = normalized || "column";
12318
+ return /^[A-Za-z_]/.test(safe) ? safe : `c_${safe}`;
12319
+ }
11749
12320
  async function fetchBackingDatasetRows(input2) {
11750
12321
  const playName = extractRunPlayName(input2.status);
11751
12322
  const tableNamespace = input2.rowsInfo.tableNamespace?.trim();