@thinkingai/ae-cli 6.1.40 → 6.1.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +1 -1
  2. package/README.zh.md +1 -1
  3. package/cli-installation-guide.md +17 -10
  4. package/dist/{ai-monitor-DST4NDOK.js → ai-monitor-OOOD4QDK.js} +5 -7
  5. package/dist/ai-monitor.js +6 -8
  6. package/dist/{auth-BD3NIY3T.js → auth-6BUUY5XS.js} +4 -4
  7. package/dist/{capability-3NJOQHZQ.js → capability-XXFCANX7.js} +8 -10
  8. package/dist/{chunk-FRJUB66C.js → chunk-5YQSCMGS.js} +2 -2
  9. package/dist/{chunk-KBJHBVO7.js → chunk-6W56UQPO.js} +1 -1
  10. package/dist/{chunk-RW6Z2NN3.js → chunk-BEVWMPCZ.js} +6 -6
  11. package/dist/{chunk-WRYXVIJP.js → chunk-DZRQGI2Z.js} +1 -1
  12. package/dist/{chunk-VXKKTUU2.js → chunk-EHH3ZF7D.js} +2 -2
  13. package/dist/{chunk-IY5G42YY.js → chunk-FPPCXG6K.js} +2 -2
  14. package/dist/{chunk-SQEK6S4X.js → chunk-I7H72CMN.js} +1182 -178
  15. package/dist/{chunk-24DCOJBJ.js → chunk-KDRE7SWM.js} +2 -2
  16. package/dist/{chunk-STHIGWWC.js → chunk-WG27BD67.js} +75 -4
  17. package/dist/{compat-check-7VBBE7KO.js → compat-check-AO3BFA3N.js} +2 -2
  18. package/dist/{config-LFRZBPH5.js → config-N5V4VNER.js} +4 -4
  19. package/dist/index.js +28 -31
  20. package/dist/{metadata-AR64J76Z.js → metadata-OUJPEMLD.js} +5 -7
  21. package/dist/{personal-semantic-preference-BCOSI4DO.js → personal-semantic-preference-WEAIZQXM.js} +4 -6
  22. package/dist/{project-semantic-DJLXAXLD.js → project-semantic-6VXUYU4A.js} +4 -6
  23. package/dist/{sync-4TUIQ2PZ.js → sync-BAV3UY46.js} +3 -3
  24. package/dist/{te-agent-EMDWA3M6.js → te-agent-QWZC36YS.js} +1 -3
  25. package/dist/{te-analysis-NJHSEKGW.js → te-analysis-43RCOPUA.js} +29 -14
  26. package/dist/{te-community-JSUSZEYH.js → te-community-ECNTP35Z.js} +5 -8
  27. package/dist/{te-dataops-I264BUTI.js → te-dataops-ISEKYRLZ.js} +3 -4
  28. package/dist/{te-engage-XNMQYO5N.js → te-engage-LBKIZXZO.js} +4 -6
  29. package/dist/{te-experiment-5SCHMYVO.js → te-experiment-5TPQKN6B.js} +4 -6
  30. package/dist/{te-kb-QQ53TNRZ.js → te-kb-SHL56BJ5.js} +4 -6
  31. package/dist/{te-team-V6BBI52R.js → te-team-EZ3TZTLV.js} +4 -6
  32. package/dist/{things-THHGDSEC.js → things-UBMLTY3S.js} +1 -3
  33. package/dist/{update-53ZUXWV5.js → update-WE7VNRKZ.js} +3 -3
  34. package/dist/{web-runtime-HIXOSNJ6.js → web-runtime-H53QKJS2.js} +338 -663
  35. package/package.json +1 -1
  36. package/skills/ae-onboarding/SKILL.md +44 -23
  37. package/skills/ae-onboarding/references/about-ae.md +68 -0
  38. package/skills/ae-onboarding/references/business-data.md +46 -0
  39. package/skills/ae-onboarding/references/business-sdk.md +1 -1
  40. package/skills/ae-onboarding/references/demo-journey.md +58 -0
  41. package/skills/ae-onboarding/references/demo-operations.md +45 -21
  42. package/skills/ae-onboarding/references/onboarding_experiment_launch.md +5 -4
  43. package/skills/ae-onboarding/references/onboarding_experiment_plan.md +9 -2
  44. package/skills/ae-onboarding/references/onboarding_growth.md +37 -5
  45. package/skills/ae-onboarding/references/onboarding_run.md +16 -2
  46. package/skills/ae-onboarding/references/onboarding_status.md +2 -0
  47. package/skills/ae-onboarding/references/presentation.md +79 -0
  48. package/skills/ae-onboarding/scripts/experiment-requests.mjs +9 -4
  49. package/skills/ae-onboarding/scripts/generate.mjs +5 -5
  50. package/skills/ae-onboarding/scripts/resolve-experiment-preset.mjs +5 -2
  51. package/skills/ae-onboarding/scripts/web-journey.mjs +39 -27
  52. package/dist/chunk-6E6HCTP2.js +0 -60
  53. package/dist/chunk-PUSFEC6B.js +0 -29
  54. package/dist/chunk-QOJXLXDJ.js +0 -55
@@ -13,24 +13,56 @@ The CLI scopes the query to the session's Demo project, item and sample dates. I
13
13
 
14
14
  `follow_up_count` counts eligible accounts for the selected scenario. For checkout recovery, `checkout_recovery.unpaid_count` counts accounts that viewed the item, then started checkout, and had no payment for the item in the seed window. `unpaid_rate` divides this count by checkout starters and is `null` when there are none.
15
15
 
16
+ `data_basis` identifies the seed-event source and distinct-account counting unit. Its `funnel_transitions` give each pair of ordered events, the distinct accounts at each step, the difference in counts (`dropoff_accounts`), and the next-step count divided by the prior-step count (`conversion_rate`). A conversion rate is `null` when the prior step is empty. With an older CLI, derive these counts and rates from `funnel`.
17
+
18
+ `charts.daily_viewers` is a seven-day line series with a distinct count of item-detail viewers per sample-local date, in chronological order. A player can appear on several dates. The series comes from the same query and cache as the funnel. A zero means nobody viewed the item that day. If the series is absent in an older CLI or an existing cached result, continue with the verified overview or diagnosis without a trend.
19
+
20
+ Use the ready response's `markdown_charts` for the inline figures. They use the same scoped counts as `charts`, `visuals` and `data_basis`. Select the layout for the current finding using the [Markdown chart guide](presentation.md#choose-and-render-a-chart).
21
+
16
22
  The account IDs are stored in the private `cohort_path` receipt for the same session and sample. The checkout experiment reads this cohort automatically. Show only aggregate counts in chat.
17
23
 
18
24
  For `poll_demo`, resume `analysis onboarding run` to advance sample preparation. For `retry_growth`, repeat the same growth command after `poll_after_ms`. For `action_required`, report the returned blocker. Use `analysis onboarding run` to select another sample before calling `growth` for it.
19
25
 
20
26
  Use `--dry-run` only to preview the CLI workflow without querying AE. `cached`, `query_ms`, and `elapsed_ms` report cache use and command timings.
21
27
 
28
+ ## Demo overview
29
+
30
+ For the local V5 picker, follow [Project overview](demo-journey.md#project-overview). The following steps describe the baseline read and the existing Web picker.
31
+
32
+ Start the overview with the localized Demo name and the [sample's opening question](presentation.md#differentiate-the-samples). Use the item, sample dates and time zone from the ready `run` response.
33
+
34
+ For the first overview of a sample, reuse a matching ready growth response when one is already in the conversation. Otherwise call `growth --session-id <session-id> --format json` once to read the baseline. Use only a ready response for the same project, sample, item and date range. Show one finding and one [sample-specific chart](presentation.md#choose-and-render-a-chart). For older CLI versions, build the chart from `purchase_rates` or subtract `checkout_recovery.unpaid_count` from `funnel.checkout` to obtain the remainder of the checkout group. Save the audience recommendation for after the user picks a question. If the read is pending, blocked or fails, show the sample scope and available links, then show the picker.
35
+
36
+ Link the available Demo dashboard and funnel using `evidence` from the ready `run` response or the matching baseline. In Web, keep the two routes by value. Use **找出回访未购玩家** and **找出结账未付玩家** for Star Island, and **看看谁在回看通行证** and **找出可召回的通行证玩家** for Season Pass. After a baseline read use one read-only `status --session-id <session-id> --format json` call to refresh the sample-ready interaction before the `options` block. If the status read fails, use the last confirmed ready interaction.
37
+
22
38
  ## Presentation
23
39
 
24
- Show the sample and dates with the counts. For `item-coupon`, use `charts.purchase_rate` with viewer and buyer counts and describe the difference as an observed association. For `checkout-recovery`, lead with the checkout starters, unpaid count and rate. Use `charts.funnel` as the main chart. Describe the behavior as checkout without payment.
40
+ Present the finding and one visual suited to the selected question. Then show a visible evidence section. Use **数据依据** in Chinese, **Data basis** in English, **データの根拠** in Japanese, or **데이터 근거** in Korean. Identify the selected sample and item, date range, time zone and distinct-account counting unit. Use the current sample's seed activity and translate the visible labels. Render inline using the current result.
41
+
42
+ If the preceding overview already showed the same comparison, state the finding with exact counts and use the [seven-day trend](presentation.md#markdown-layouts) as additional context when available. Keep the daily count separate from the weekly purchase rate.
43
+
44
+ ### Growth opportunity
45
+
46
+ For `item-coupon`, compare one-day and multi-day viewers. Use the [purchase-rate comparison](presentation.md#choose-and-render-a-chart) from `charts.purchase_rate`. Read counts from `single_day` and `multi_day` and rates from `purchase_rates`. Include both denominators in the data note. Display unavailable rates as unavailable.
47
+
48
+ In the evidence section, explain that each rate is buyers divided by viewers, that `difference_pp` is a percentage-point difference, and that eligible follow-up accounts equal multi-day viewers minus multi-day buyers. Describe the gap as an observed association in the sample.
49
+
50
+ ### Checkout recovery
51
+
52
+ For `checkout-recovery`, lead with checkout starters, the unpaid count and unpaid share. Use a three-stage funnel with **Viewed item → Started checkout → Paid** and the account count at each stage from `funnel`. Annotate each transition with `data_basis.funnel_transitions[].dropoff_accounts`. With an older CLI, subtract the next-stage count from the preceding count.
53
+
54
+ Use the [Markdown funnel](presentation.md#markdown-layouts) to show the ordered purchase stages with their transition labels. Use the checkout share when the finding is about the final step alone and the split has not just been shown.
55
+
56
+ In the evidence section, identify the stage with the largest account loss and show `checkout_recovery.unpaid_count` divided by `funnel.checkout` for the unpaid share. If nobody started checkout, show the share as unavailable. Describe the observed behavior as checkout without payment. Explain the reason only if the evidence supports it.
25
57
 
26
- Web uses the native `chart` fence with localized labels. External agents use short inline bars with exact values, or a Markdown table if the host cannot display the bars. Render from the current result without building a file or running another analysis query.
58
+ ### Report links
27
59
 
28
- Place the returned `evidence.dashboard_url` and `evidence.funnel_report_url` below the chart as clickable links. Include `evidence.purchase_rate_report_url` when pointing to the comparison itself. Web uses the relative product links. If evidence is still preparing, show the result and the next choice immediately. A later normal status or growth response can supply the links once ready.
60
+ Place the returned `evidence.dashboard_url` and `evidence.funnel_report_url` below the evidence as clickable links. Include `evidence.purchase_rate_report_url` when pointing to the comparison itself. Web uses the relative product links. If evidence is still preparing, show the result and the next choice immediately. A later normal status or growth response can supply the links once ready.
29
61
 
30
62
  ## Follow-up
31
63
 
32
- Lead with `follow_up_count` and the target audience. Show one chart from `follow_up_chart` before giving the recommendation and the next choice. In Web, use the native `chart` fence with the returned `type` and `data`. In a local agent, display the returned `markdown` as visible Markdown with its bars and counts. Translate labels only. If the host cannot show the bars, show the same rows and counts in a Markdown table. Reuse the last ready growth response for this sample and scenario. Render inline without creating an asset or issuing an extra analysis query for the chart.
64
+ Lead with `follow_up_count` and the target audience. For Season Pass, show the audience overlap composition when comparing follow-up groups. For Star Island, show a count comparison based on `follow_up_chart.data`. Give the recommendation below the chart. Reuse the last ready growth response for this sample and scenario and the matching [chart layout](presentation.md#choose-and-render-a-chart). Use the exact counts beside the chart; the Markdown fallback also works when the CLI supplies only the base counts.
33
65
 
34
- With an older CLI, use a Markdown table built from the existing counts. For `checkout-recovery`, show `funnel.checkout`, `funnel.buyers` (paid after checkout), and `checkout_recovery.unpaid_count`. For `item-coupon`, show multi-day unpaid, single-day unpaid, and paid viewers from `multi_day` and `single_day`. If a matching ready result is unavailable in the conversation, resume growth for the selected sample and scenario.
66
+ With an older CLI, apply the Markdown layouts to the existing counts. For `checkout-recovery`, use `funnel.checkout`, `funnel.buyers` (paid after checkout), and `checkout_recovery.unpaid_count`. For `item-coupon`, derive the multi-day unpaid, single-day unpaid, and paid viewers from `multi_day` and `single_day`. If a matching ready result is unavailable in the conversation, resume growth for the selected sample and scenario.
35
67
 
36
68
  For `item-coupon`, compare a full-price reminder with a 20% coupon for multi-day viewers who did not buy. For `checkout-recovery`, compare a reminder leading to item details with one leading directly to checkout for the same unpaid audience. Keep the price and timing the same in that scenario. Compare distinct buyers, payment rate, and paid amount.
@@ -4,8 +4,22 @@ Run `ae-cli analysis onboarding run` when the customer starts or resumes AE PLG,
4
4
 
5
5
  In an external Agent, the CLI opens new login and authorization pages in the system default browser. If opening fails, give the user the exact returned URL. Web onboarding uses the platform identity and does not open these pages.
6
6
 
7
- For local website onboarding, use the customer's production market (`cn`, `jp`, `kr`, or `us`). If a saved test session cannot resume, keep its original account and start a separate session only when the customer asks to register in a supported production market.
8
-
9
7
  Use `interaction.options` as the choices for a user decision and `next_action` for what to run next. A successful sign-in can return `choose_experience` immediately. If Demo evidence links are ready, `evidence` contains links for the current Demo project.
10
8
 
11
9
  Use `ae-cli analysis onboarding run --help` to look up the available flags.
10
+
11
+ In Web, pass the conversation locale with `--language`. The Web `run` result and its `--dry-run` preview include `product_resource_market` (`cn`, `us`, `jp`, `kr`, or `null`) for selecting [public product links](about-ae.md#web-onboarding).
12
+
13
+ ## Website signup
14
+
15
+ After the user chooses to create an account, run `ae-cli analysis onboarding run --region <market> --browser system --format json` for production (`cn`, `jp`, `kr`, or `us`). For overseas testing, add `--website-env test` with `--region us`, `jp`, or `kr`. Use `us` for an overseas test request without a specific market. Resume with the returned `--session-id` to keep the original environment. Start a separate continuation when the user requests a different environment.
16
+
17
+ ## Shared progress
18
+
19
+ Use `ae-cli analysis onboarding progress --format json` to read the signed-in account's current version. When the user enters the Demo, `run --choice demo` starts or resumes the shared round. Retain the latest `session_id` returned by `run`.
20
+
21
+ - `not_started` offers the current Demo. `in_progress` resumes it. `completed` routes returning users to their ordinary AE task.
22
+ - If the response has a bound `run_id`, reuse it. If a different conversation owns that run, use the existing run's report and wait for its replay checkpoint. Continue experiment launch from its original session if the checkpoint is still missing.
23
+ - Once the replay events are persisted, run `ae-cli analysis onboarding progress --run-id <run-id> --format json`. This checks the events in the Demo project and records completion on both surfaces. If it still returns `in_progress`, retry the same run after ingestion. For `unavailable`, preserve the current run and retry the completion call.
24
+ - On `check_demo_license`, explain that the Demo needs active Operations and Experiment permissions. Keep the same session to retry after those permissions take effect.
25
+ - A `disabled` result uses the existing unversioned flow. The completion choice in Web still controls when to show the workspace entry.
@@ -2,4 +2,6 @@
2
2
 
3
3
  Use `ae-cli analysis onboarding status --session-id <session-id>` only when checking an existing PLG session. The output includes the current next action, browser receipt if applicable, and sample preparation state. To advance, follow the session Skill and run the action the user selected.
4
4
 
5
+ For a signed-in local session, `business_data.interaction` and `business_data.tools` give the choices for [business data integration](business-data.md). `business_project` identifies the registration project candidate and `project_id` identifies the bound business project when confirmed. `demo_project_id` identifies the sample project.
6
+
5
7
  Use `ae-cli analysis onboarding status --help` to look up the available flags.
@@ -0,0 +1,79 @@
1
+ # Onboarding copy and charts
2
+
3
+ Use a short question or action as the choice label. Name the item or audience when that helps the user decide. Put sample scope, expected effects and approval consequences in the message immediately above the picker. Keep report, product and contact URLs in Markdown links. Localize visible copy and retain the underlying option values. Understand earlier labels when a user types them or replies to an older picker.
4
+
5
+ ## Common choices
6
+
7
+ | Moment | 中文 |
8
+ | --- | --- |
9
+ | Account entry | 创建 AE 账号 · 先了解 ThinkingAI |
10
+ | Website sign-in | 我已完成登录 · 登录遇到问题 |
11
+ | CLI access | 我已授权 CLI · 授权遇到问题 |
12
+ | Resume sign-in | 重新打开登录页 · 稍后再试 |
13
+ | Reconnect CLI | 重新授权 CLI · 稍后再试 |
14
+ | Demo entry | 开始样例体验 · 看看 ThinkingAI 能做什么 |
15
+ | After a finding | 看看怎么跟进 |
16
+ | Generate a draft | 生成 A/B 草稿 |
17
+ | Confirm a runnable draft | 审核通过并启动 |
18
+ | Confirm a review-only draft | 确认这份草稿 |
19
+ | Draft questions | 为什么选这批人? · 小批试点怎么做? · 不加奖励可以测什么? |
20
+ | Web opening | 开始样例体验 · 先了解 ThinkingAI · 稍后再试 |
21
+ | Web after verification | 换个 Demo 继续 · 完成体验 |
22
+ | Local completion | 继续体验Demo · 接入数据 |
23
+ | Sample selection | 星屿游戏 · 星光冒险礼包 / 赛季通行证 · 从结账到付款 |
24
+
25
+ For draft review, keep the approval choice first until the user confirms. Continue to remove only answered questions. For a runnable draft, explain that approval starts the Demo and replays simulated events. For a review-only draft, explain that confirmation records the user's review. Accept the earlier **审核通过** label for the action already shown. Use the [business data choices](business-data.md) for data integration.
26
+
27
+ ## Differentiate the samples
28
+
29
+ | Stage | 星屿游戏 | 赛季通行证 |
30
+ | --- | --- | --- |
31
+ | Opening question | 玩家反复看礼包,后来更容易买吗? | 有多少玩家开始结账,最后没有付款? |
32
+ | Opening visual | Horizontal bars comparing single-day and multi-day purchase rates | Ring chart of checkout outcomes with the unpaid count and share emphasized |
33
+ | Start of business diagnosis | Seven-day line showing interest in the bundle | Seven-day line showing interest in the pass |
34
+ | Main visual in purchase diagnosis | Step widths and losses from viewing the bundle to paying | Step widths and losses from opening the pass to paying |
35
+ | Audience follow-up | Bars for the follow-up counts | 100% stacked bar for the disjoint audience groups |
36
+ | Explore route | 深挖礼包购买表现 | 深挖通行证转化 |
37
+ | Follow-up route for revisits | 找出回访未购玩家 | 找出回看通行证的玩家 |
38
+ | Follow-up route for checkout | 找出结账未付玩家 | 找出可召回的通行证玩家 |
39
+ | Follow-up route for conversion | 找出礼包购买卡点 | 找出通行证购买卡点 |
40
+ | Diagnosis topics | 礼包回访 · 礼包结账未付 · 礼包购买漏斗 | 通行证回访 · 通行证结账未付 · 通行证购买漏斗 |
41
+ | A/B result | Compare purchase rates for the bundle and show the cost if a coupon was tested | Compare payment completion for the pass and show both exposure denominators |
42
+
43
+ Use the sample's initial finding when entering its overview. Use the rotated `featured_topic` for the follow-up choice. Keep the question and its counts specific to the selected item. In Season Pass, consider the overlap between checkout and repeat viewing when presenting audience choices. Use sample-specific arm labels in the report, such as **返回礼包详情** or **返回通行证详情** when relevant.
44
+
45
+ ## Choose and render a chart
46
+
47
+ Use pure Markdown for the default walkthrough in every host. Place one primary visual above the next choice. Use the current verified result in the same reply, without images, render jobs, or extra queries. Copy the matching field from `markdown_charts` when present. Translate table headers, labels and legends, and preserve the exact values, shapes and whitespace inside `text` fences. With an older CLI, use the underlying counts to reproduce the same layout.
48
+
49
+ | Finding | Markdown layout | Field from `markdown_charts` |
50
+ | --- | --- | --- |
51
+ | Compare purchase rates | Horizontal bars on a common 0–100% scale | `purchase_rate` |
52
+ | Show the checkout split | Ring with a legend and exact counts and shares | `checkout_share` |
53
+ | Show change over the sample week | Text line chart with axes, plus exact daily counts | `daily_viewers` |
54
+ | Show loss along the purchase flow | Centered funnel with loss and conversion columns | `purchase_funnel` |
55
+ | Compare eligible audiences | Horizontal bars with exact counts | `follow_up` |
56
+ | Show audience overlap | 100% stacked bar for the three disjoint parts | `audience_overlap` |
57
+ | Review or read A/B results | Side-by-side Markdown table | Saved plan or verified event counts |
58
+
59
+ Use the host's Markdown typography. Use blue for a single series and blue and purple for different series when using colored blocks. Pair each color or texture with a text label. Keep the main result in bold once, use short metric titles and right-align numbers. Put units, dates, timezone and the counting rule where they help interpret the figure. Use `▲` or `▼` with the actual signed change and unit. Show a missing value as `—` and leave a gap in a trend. Preserve verified zeroes.
60
+
61
+ If the user requests an interactive chart and the host supports native `chart`, use strict JSON with `type`, localized `title`, and `data` entries. Use numeric `value` with `label` for `bar`, `line` and `pie`. Leave the colors and typography to the host theme. When a native pie groups small slices, keep their exact counts and shares beside it.
62
+
63
+ ### Markdown layouts
64
+
65
+ **Rate or count comparison.** Use a zero-based scale of 12 blue blocks. Use a shared 100% maximum for rates and the largest count for counts. Keep the exact value in a right-aligned column.
66
+
67
+ **Composition.** For checkout, draw the two verified parts of the total as a ring inside a `text` fence with two distinguishable textures. Keep the precise count and percentage in the legend table. For audience overlap, divide 20 blocks at cumulative share boundaries so the bar sums to 100%. The three parts are intersection, checkout-only and revisit-only. Label each segment with its exact count and share. Omit a composition visual with a zero denominator.
68
+
69
+ **Seven-day trend.** Use a `text` fence with the y-axis ticks, dates along the x-axis, and connected points. Keep dates in chronological order and include the exact daily counts in a compact table. When the source has no verified trend, continue with the current finding.
70
+
71
+ **Purchase funnel.** Keep steps in the order they happen. Center the marks, and use the first stage as the width reference throughout. Next to each later stage show the loss and the conversion rate from the preceding one. A verified zero has an empty bar and a displayed zero. An undefined transition rate is unavailable.
72
+
73
+ | 通行证购买步骤 | 人数 | 规模 | 较上一步流失 | 较上一步转化率 |
74
+ | --- | ---: | :---: | ---: | ---: |
75
+ | 浏览详情 | 120 | `━━━━━━━━━━━━` | — | — |
76
+ | 开始结账 | 48 | `━━━━━` | 72 | 40.0% |
77
+ | 完成付款 | 20 | `━━` | 28 | 41.7% |
78
+
79
+ **A/B draft and report.** Use a side-by-side Markdown table. For a draft, use the two destinations or offers, split and price from the plan. For a verified report, lead with the rate difference in percentage points and show both denominators, buyers, rates and amounts. Include claims, order costs and profit for a coupon test. Use the experiment's saved currency and the scenario-specific labels.
@@ -3,8 +3,10 @@ import { readFileSync } from 'node:fs';
3
3
 
4
4
  import { isDemoAccountId, resolveExperimentPreset } from './resolve-experiment-preset.mjs';
5
5
 
6
- function buildRequests({ industry, experimentType, sampleId, itemId, runId, bucketId: requestedBucketId, accountIds: requestedAccountIds, metricIds }) {
7
- const { preset, sample, experimentType: selectedType } = resolveExperimentPreset({ industry, experimentType, sampleId, itemId });
6
+ function buildRequests({ industry, experimentType, sampleId, itemId, runId, bucketId: requestedBucketId, accountIds: requestedAccountIds, metricIds, currency: requestedCurrency }) {
7
+ const { preset, sample, experimentType: selectedType, currency } = resolveExperimentPreset({
8
+ industry, experimentType, sampleId, itemId, currency: requestedCurrency,
9
+ });
8
10
  const bucketId = requestedBucketId === undefined ? preset.audience.bucketId : requestedBucketId;
9
11
  const accountIds = requestedAccountIds === undefined ? sample.followUpAccountIds : requestedAccountIds;
10
12
  if (typeof runId !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,31}$/.test(runId)) {
@@ -22,7 +24,9 @@ function buildRequests({ industry, experimentType, sampleId, itemId, runId, buck
22
24
  || !accountIds.every(id => isDemoAccountId(id, sampleId, sample.userCount)))) {
23
25
  throw new Error('Checkout recovery requires the verified cohort for this Demo sample.');
24
26
  }
25
- const revenueMetricId = metricIds === undefined ? sample.netRevenueMetricId : metricIds?.secondary;
27
+ const usd = currency === 'USD';
28
+ const defaultRevenueMetricId = usd ? `${sample.netRevenueMetricId}_usd` : sample.netRevenueMetricId;
29
+ const revenueMetricId = metricIds === undefined ? defaultRevenueMetricId : metricIds?.secondary;
26
30
  if (typeof revenueMetricId !== 'string' || !revenueMetricId.trim() || revenueMetricId !== revenueMetricId.trim()) {
27
31
  throw new Error('metricIds.secondary must contain the verified net revenue metric ID.');
28
32
  }
@@ -43,6 +47,7 @@ function buildRequests({ industry, experimentType, sampleId, itemId, runId, buck
43
47
  items: [
44
48
  { field: preset.metricFilters[0], operator: 'eq', values: [sampleId] },
45
49
  { field: preset.metricFilters[1], operator: 'eq', values: [itemId] },
50
+ ...(usd ? [{ field: 'currency', operator: 'eq', values: [currency] }] : []),
46
51
  ],
47
52
  };
48
53
  const { role, format, ...definition } = preset.metrics.find((entry) => entry.role === 'primary');
@@ -61,7 +66,7 @@ function buildRequests({ industry, experimentType, sampleId, itemId, runId, buck
61
66
  const secondary = preset.metrics.find((entry) => entry.role === 'secondary');
62
67
  const revenueMetric = {
63
68
  metricId: revenueMetricId,
64
- metricName: `PLG net revenue (${sampleId})`,
69
+ metricName: usd ? `PLG net revenue (${sampleId}, USD)` : `PLG net revenue (${sampleId})`,
65
70
  createType: 'event',
66
71
  goalDirection: 'up',
67
72
  metricPurpose: 'confidence_statistics',
@@ -13,7 +13,7 @@ function main() {
13
13
  const { values: args } = parseArgs({
14
14
  options: Object.fromEntries([
15
15
  'phase', 'run-id', 'output-dir', 'start', 'end', 'timezone', 'experiment-id', 'control-id', 'treatment-id',
16
- 'cohort-file', 'sample-id', 'item-id', 'industry', 'experiment-type',
16
+ 'cohort-file', 'sample-id', 'item-id', 'industry', 'experiment-type', 'currency',
17
17
  ].map((name) => [name, { type: 'string' }])),
18
18
  });
19
19
  if (args.phase !== 'plg-experiment-today') {
@@ -65,8 +65,8 @@ function generatePlgReplay(args, start) {
65
65
  'experiment-id': experimentId, 'control-id': controlId, 'treatment-id': treatmentId,
66
66
  } = args;
67
67
  if (!cohortFile) throw new Error('Pass --cohort-file for the selected Demo sample.');
68
- const { preset, sample, industry, experimentType } = resolveExperimentPreset({
69
- industry: args.industry, experimentType: args['experiment-type'], sampleId, itemId,
68
+ const { preset, sample, industry, experimentType, currency } = resolveExperimentPreset({
69
+ industry: args.industry, experimentType: args['experiment-type'], sampleId, itemId, currency: args.currency,
70
70
  });
71
71
  const { exposureProperties, events } = preset;
72
72
  const cohort = JSON.parse(readFileSync(cohortFile, 'utf8'));
@@ -104,7 +104,7 @@ function generatePlgReplay(args, start) {
104
104
  })));
105
105
  claims.forEach((id) => outcomes.push(event(id, groupId, outcomeDelayMs, events.couponClaim, tags)));
106
106
  paid.forEach((id) => outcomes.push(event(id, groupId, outcomeDelayMs, events.payment, {
107
- ...tags, order_id: stableUuid(['order', ...replayIdentity, groupId, id]), amount: config.price, currency: preset.currency,
107
+ ...tags, order_id: stableUuid(['order', ...replayIdentity, groupId, id]), amount: config.price, currency,
108
108
  })));
109
109
  arms[name] = {
110
110
  group_id: groupId, assigned_account_ids: assigned, exposed_account_ids: exposed,
@@ -119,7 +119,7 @@ function generatePlgReplay(args, start) {
119
119
  ];
120
120
  const receipt = {
121
121
  version: 'ae-plg-demo-experiment-replay/v1', synthetic: true, phase: args.phase, run_id: runId,
122
- sample_id: sampleId, item_id: itemId, industry, experiment_type: experimentType,
122
+ sample_id: sampleId, item_id: itemId, industry, experiment_type: experimentType, currency,
123
123
  experiment_id: experimentId, timezone: args.timezone,
124
124
  start: args.start, end: args.end, arms,
125
125
  event_uuids: { exposure: exposure.map((row) => row.event_uuid), outcomes: outcomes.map((row) => row.event_uuid) },
@@ -8,7 +8,7 @@ export function isDemoAccountId(id, sampleId, userCount) {
8
8
  return /^[1-9][0-9]{0,2}$/.test(number) && number === number.trim() && Number(number) <= userCount;
9
9
  }
10
10
 
11
- export function resolveExperimentPreset({ industry, experimentType, sampleId, itemId }) {
11
+ export function resolveExperimentPreset({ industry, experimentType, sampleId, itemId, currency }) {
12
12
  const matches = Object.entries(catalog.industries).filter(([id, { samples }]) =>
13
13
  (industry === undefined || industry === id) && Object.hasOwn(samples, sampleId)
14
14
  && samples[sampleId].itemId === itemId);
@@ -22,5 +22,8 @@ export function resolveExperimentPreset({ industry, experimentType, sampleId, it
22
22
  if (!sample.experimentTypes.includes(experimentTypeId) || !Object.hasOwn(catalog.experimentTypes, experimentTypeId)) {
23
23
  throw new Error(`Unsupported experiment type for ${industryId}/${sampleId}. Available: ${sample.experimentTypes.join(', ')}.`);
24
24
  }
25
- return { industry: industryId, experimentType: experimentTypeId, sample, preset: catalog.experimentTypes[experimentTypeId] };
25
+ const preset = catalog.experimentTypes[experimentTypeId];
26
+ const resolvedCurrency = currency === undefined ? preset.currency : currency;
27
+ if (resolvedCurrency !== 'CNY' && resolvedCurrency !== 'USD') throw new Error('Unsupported Demo currency. Use CNY or USD.');
28
+ return { industry: industryId, experimentType: experimentTypeId, sample, preset, currency: resolvedCurrency };
26
29
  }
@@ -2,38 +2,50 @@ import { randomUUID } from 'node:crypto';
2
2
  import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
 
5
- const endpoint = process.argv[2];
5
+ const action = process.argv[2];
6
6
  const cwd = process.cwd();
7
7
  const choices = {
8
8
  'choose-sample': { step: 'choose_sample', options: [{ value: 'star_island' }, { value: 'season_pass' }, { value: 'keep_sample' }] },
9
- 'after-follow-up': { step: 'follow_up_ready', options: [{ value: 'experiment_plan' }, { value: 'change_sample' }] },
9
+ 'after-follow-up': { step: 'follow_up_ready', options: [{ value: 'experiment_plan' }] },
10
+ 'after-experiment': { step: 'experiment_verified', options: [{ value: 'change_sample' }, { value: 'finish_demo' }] },
10
11
  };
11
- if (!(['done', 'stopped'].includes(endpoint) || Object.hasOwn(choices, endpoint))) {
12
- throw new Error('Expected done, stopped, choose-sample, or after-follow-up.');
12
+ if (!(['active', 'done', 'stopped'].includes(action) || Object.hasOwn(choices, action))) {
13
+ throw new Error('Expected active, done, stopped, choose-sample, after-follow-up, or after-experiment.');
13
14
  }
14
- if (Object.hasOwn(choices, endpoint)) {
15
- process.stdout.write(JSON.stringify({ ok: true, data: { interaction: choices[endpoint] } }) + '\n');
16
- process.exit(0);
15
+ if (action === 'after-experiment') await recordEndpoint('active');
16
+ if (Object.hasOwn(choices, action)) {
17
+ process.stdout.write(JSON.stringify({ ok: true, data: { interaction: choices[action] } }) + '\n');
18
+ } else {
19
+ await recordEndpoint(action);
17
20
  }
18
21
 
19
- const directory = path.join(cwd, '.ae-onboarding');
20
- await fs.mkdir(directory, { recursive: true, mode: 0o700 });
21
- if (!(await fs.lstat(directory)).isDirectory()) throw new Error('Unsafe onboarding state directory.');
22
- const target = path.join(directory, 'plg-journey.json');
23
- const schema = 'ae-onboarding.state.v5';
24
- const previous = await fs.lstat(target).catch(error => {
25
- if (error.code !== 'ENOENT') throw error;
26
- return null;
27
- });
28
- if (previous && (!previous.isFile() || previous.size > 8192)) throw new Error('Unsafe onboarding journey state.');
29
- if (previous) {
30
- const state = JSON.parse(await fs.readFile(target, 'utf8'));
31
- if (state.schema === schema && state.endpoint === endpoint) process.exit(0);
32
- }
33
- const temp = path.join(directory, `.${randomUUID()}.tmp`);
34
- try {
35
- await fs.writeFile(temp, `${JSON.stringify({ schema, revision: Date.now(), endpoint })}\n`, { mode: 0o600, flag: 'wx' });
36
- await fs.rename(temp, target);
37
- } finally {
38
- await fs.rm(temp, { force: true });
22
+ async function recordEndpoint(endpoint) {
23
+ const directory = path.join(cwd, '.ae-onboarding');
24
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
25
+ if (!(await fs.lstat(directory)).isDirectory()) throw new Error('Unsafe onboarding state directory.');
26
+ const target = path.join(directory, 'plg-journey.json');
27
+ const schema = 'ae-onboarding.state.v5';
28
+ const previous = await fs.lstat(target).catch(error => {
29
+ if (error.code !== 'ENOENT') throw error;
30
+ return null;
31
+ });
32
+ if (previous && (!previous.isFile() || previous.size > 8192)) throw new Error('Unsafe onboarding journey state.');
33
+ if (previous) {
34
+ const state = JSON.parse(await fs.readFile(target, 'utf8'));
35
+ if (endpoint === 'active' || (state.schema === schema && state.endpoint === endpoint)) return;
36
+ }
37
+ const temp = path.join(directory, `.${randomUUID()}.tmp`);
38
+ try {
39
+ await fs.writeFile(temp, `${JSON.stringify({ schema, revision: Date.now(), endpoint })}\n`, { mode: 0o600, flag: 'wx' });
40
+ if (endpoint === 'active') {
41
+ // Initialization must not replace a concurrent completion receipt.
42
+ await fs.link(temp, target).catch(error => {
43
+ if (error.code !== 'EEXIST') throw error;
44
+ });
45
+ } else {
46
+ await fs.rename(temp, target);
47
+ }
48
+ } finally {
49
+ await fs.rm(temp, { force: true });
50
+ }
39
51
  }
@@ -1,60 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import {
3
- getLocalCliPackageInfo
4
- } from "./chunk-PUSFEC6B.js";
5
- import {
6
- getAeSandboxDetectionReason
7
- } from "./chunk-IGU3R2JD.js";
8
- import {
9
- logger
10
- } from "./chunk-MTK4ZE7W.js";
11
-
12
- // src/core/source-logged-fetch.ts
13
- import { randomUUID } from "crypto";
14
- var CLI_REQUEST_ID_HEADER = "X-TA-CLI-Request-Id";
15
- var localPackage = getLocalCliPackageInfo();
16
- var MAX_LOG_VALUE_LENGTH = 256;
17
- function bounded(value) {
18
- return value.length > MAX_LOG_VALUE_LENGTH ? `${value.slice(0, MAX_LOG_VALUE_LENGTH)}...[truncated]` : value;
19
- }
20
- function sourceLoggedFetch(url, init) {
21
- const requestId = randomUUID();
22
- let headers;
23
- if (init.headers instanceof Headers) {
24
- headers = new Headers(init.headers);
25
- headers.set(CLI_REQUEST_ID_HEADER, requestId);
26
- } else if (Array.isArray(init.headers)) {
27
- headers = [
28
- ...init.headers.filter(([name]) => name.toLowerCase() !== CLI_REQUEST_ID_HEADER.toLowerCase()),
29
- [CLI_REQUEST_ID_HEADER, requestId]
30
- ];
31
- } else {
32
- headers = Object.fromEntries(Object.entries(init.headers ?? {}).filter(([name]) => name.toLowerCase() !== CLI_REQUEST_ID_HEADER.toLowerCase()));
33
- headers[CLI_REQUEST_ID_HEADER] = requestId;
34
- }
35
- const request = { ...init, headers };
36
- try {
37
- const target = new URL(url);
38
- const actualHeaders = new Headers(headers);
39
- const source = actualHeaders.get("X-Source");
40
- const sandboxDetection = getAeSandboxDetectionReason();
41
- logger.info(`CLI_SOURCE_SEND ${JSON.stringify({
42
- request_id: requestId,
43
- method: init.method ?? "GET",
44
- host: bounded(target.host),
45
- path: bounded(target.pathname),
46
- source: source === null ? null : bounded(source),
47
- source_state: source === null ? "missing" : source === "" ? "empty" : source.includes(",") ? "multiple" : "present",
48
- cli_package: localPackage.name,
49
- cli_version: localPackage.version,
50
- sandbox_detected: sandboxDetection !== "not_detected",
51
- sandbox_detection: sandboxDetection
52
- })}`);
53
- } catch {
54
- }
55
- return fetch(url, request);
56
- }
57
-
58
- export {
59
- sourceLoggedFetch
60
- };
@@ -1,29 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
-
3
- // src/core/package-info.ts
4
- import fs from "fs";
5
- import path from "path";
6
- import { fileURLToPath } from "url";
7
- function getLocalCliPackageInfo() {
8
- let dir = path.dirname(fileURLToPath(import.meta.url));
9
- for (let i = 0; i < 8; i += 1) {
10
- const candidate = path.join(dir, "package.json");
11
- try {
12
- if (fs.existsSync(candidate)) {
13
- const pkg = JSON.parse(fs.readFileSync(candidate, "utf8"));
14
- if (pkg.name && pkg.version && String(pkg.name).includes("ae-cli")) {
15
- return { name: pkg.name, version: pkg.version, root: dir };
16
- }
17
- }
18
- } catch {
19
- }
20
- const parent = path.dirname(dir);
21
- if (parent === dir) break;
22
- dir = parent;
23
- }
24
- return { name: "@tant/ae-cli", version: "0.0.0", root: "" };
25
- }
26
-
27
- export {
28
- getLocalCliPackageInfo
29
- };
@@ -1,55 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
-
3
- // src/core/resource-url.ts
4
- var LOCAL_BACKEND_PORTS = /* @__PURE__ */ new Set(["8992", "8996"]);
5
- function normalizeResourceUrlFields(node, host, sourceHost = host) {
6
- if (!node || typeof node !== "object") return;
7
- const obj = node;
8
- for (const [key, value] of Object.entries(obj)) {
9
- if (typeof value === "string") {
10
- if (/url|link/i.test(key) || value.includes("/#/")) {
11
- obj[key] = normalizeResourceUrls(value, host, sourceHost);
12
- }
13
- } else if (value && typeof value === "object") {
14
- normalizeResourceUrlFields(value, host, sourceHost);
15
- }
16
- }
17
- }
18
- function absolutizeRelativeUrls(s, host) {
19
- return normalizeResourceUrls(s, host);
20
- }
21
- function normalizeResourceUrls(s, host, sourceHost = host) {
22
- const base = host.replace(/\/+$/, "");
23
- const sourceBase = sourceHost.replace(/\/+$/, "");
24
- if (sourceBase && sourceBase !== base) {
25
- s = s.replace(new RegExp(`${escapeRegExp(sourceBase)}/#`, "g"), `${base}/#`);
26
- }
27
- s = s.replace(/\]\((\/(?!\/)[^)]*)\)/g, `](${base}$1)`);
28
- if (/^\/(?!\/)/.test(s)) s = base + s;
29
- return s;
30
- }
31
- function resolvePublicWebHost(host) {
32
- const override = process.env.AE_CLI_PUBLIC_WEB_URL || process.env.AE_CLI_WEB_HOST;
33
- if (override?.trim()) {
34
- return override.trim().replace(/\/+$/, "");
35
- }
36
- try {
37
- const url = new URL(host);
38
- if ((url.hostname === "127.0.0.1" || url.hostname === "localhost") && LOCAL_BACKEND_PORTS.has(url.port)) {
39
- url.port = "10010";
40
- return url.toString().replace(/\/+$/, "");
41
- }
42
- } catch {
43
- }
44
- return host.replace(/\/+$/, "");
45
- }
46
- function escapeRegExp(value) {
47
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48
- }
49
-
50
- export {
51
- normalizeResourceUrlFields,
52
- absolutizeRelativeUrls,
53
- normalizeResourceUrls,
54
- resolvePublicWebHost
55
- };