@thinkingai/ae-cli 6.1.40 → 6.1.42

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 +18 -10
  4. package/dist/{ai-monitor-DST4NDOK.js → ai-monitor-E62FT3TT.js} +5 -7
  5. package/dist/ai-monitor.js +6 -8
  6. package/dist/{auth-BD3NIY3T.js → auth-SDK5OAGP.js} +4 -4
  7. package/dist/{capability-3NJOQHZQ.js → capability-F6YWGPZZ.js} +8 -10
  8. package/dist/{chunk-FRJUB66C.js → chunk-CDBW5RE6.js} +2 -2
  9. package/dist/{chunk-VXKKTUU2.js → chunk-DIYDOOBL.js} +2 -2
  10. package/dist/{chunk-WRYXVIJP.js → chunk-DZRQGI2Z.js} +1 -1
  11. package/dist/{chunk-SQEK6S4X.js → chunk-GTENC5CO.js} +1209 -183
  12. package/dist/{chunk-IY5G42YY.js → chunk-KAZ5FWPB.js} +2 -2
  13. package/dist/{chunk-KBJHBVO7.js → chunk-N2QILIGH.js} +1 -1
  14. package/dist/{chunk-STHIGWWC.js → chunk-WG27BD67.js} +75 -4
  15. package/dist/{chunk-RW6Z2NN3.js → chunk-ZK6KEGUR.js} +6 -6
  16. package/dist/{chunk-24DCOJBJ.js → chunk-ZSKLELL7.js} +2 -2
  17. package/dist/{compat-check-7VBBE7KO.js → compat-check-J5K3NO5G.js} +2 -2
  18. package/dist/{config-LFRZBPH5.js → config-O3W6XLHO.js} +4 -4
  19. package/dist/index.js +29 -31
  20. package/dist/{metadata-AR64J76Z.js → metadata-3GA2N27I.js} +5 -7
  21. package/dist/{personal-semantic-preference-BCOSI4DO.js → personal-semantic-preference-T2HFF2V4.js} +4 -6
  22. package/dist/{project-semantic-DJLXAXLD.js → project-semantic-WJOP2HGJ.js} +4 -6
  23. package/dist/{sync-4TUIQ2PZ.js → sync-K65X7ODO.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-7E2GVKOR.js} +29 -14
  26. package/dist/{te-community-JSUSZEYH.js → te-community-NQNSLNON.js} +5 -8
  27. package/dist/{te-dataops-I264BUTI.js → te-dataops-PMI7UX36.js} +3 -4
  28. package/dist/{te-engage-XNMQYO5N.js → te-engage-EZBV5IPQ.js} +4 -6
  29. package/dist/{te-experiment-5SCHMYVO.js → te-experiment-RDB3TYBG.js} +4 -6
  30. package/dist/{te-kb-QQ53TNRZ.js → te-kb-OWPJB243.js} +4 -6
  31. package/dist/{te-team-V6BBI52R.js → te-team-NCMN34IL.js} +4 -6
  32. package/dist/{things-THHGDSEC.js → things-UBMLTY3S.js} +1 -3
  33. package/dist/{update-53ZUXWV5.js → update-LYVYF3KJ.js} +3 -3
  34. package/dist/{web-runtime-HIXOSNJ6.js → web-runtime-XJWDFVP3.js} +343 -664
  35. package/package.json +1 -1
  36. package/skills/ae-onboarding/SKILL.md +42 -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 +20 -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
@@ -1,15 +1,7 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import {
3
- absolutizeRelativeUrls
4
- } from "./chunk-QOJXLXDJ.js";
5
2
  import {
6
3
  fetchSigned
7
4
  } from "./chunk-KE5WGBXS.js";
8
- import {
9
- CapabilityGatewayError,
10
- executeCapability
11
- } from "./chunk-STHIGWWC.js";
12
- import "./chunk-6E6HCTP2.js";
13
5
  import {
14
6
  assembleSyncJsonBody,
15
7
  localDataUpload,
@@ -29,24 +21,49 @@ import {
29
21
  DEMO_SAMPLE_IDS,
30
22
  DEMO_STATUS,
31
23
  NETWORK_BUDGET_MS,
24
+ OVERSEAS_TEST_MARKETS,
25
+ OVERSEAS_TEST_PRODUCT_HOSTNAME,
26
+ OVERSEAS_TEST_WEBSITE_ORIGIN,
32
27
  RUN_BUDGET_MS,
33
28
  UUID_PATTERN,
34
29
  WEBSITE_MARKETS,
30
+ bootstrapOrigin,
31
+ claimBootstrapDevice,
35
32
  cliEntrySource,
36
- environmentForWebsiteOrigin,
33
+ createBootstrap,
37
34
  fetchCliConfig,
35
+ isOnboardingProgressHost,
38
36
  isProductionWebsiteOrigin,
37
+ isWebsiteMarket,
38
+ localRegistrationLanguage,
39
39
  normalizeRegistrationLanguage,
40
+ onboardingDemoCurrency,
41
+ onboardingDemoOverview,
42
+ onboardingDeviceMarket,
43
+ onboardingDraftReviewInteraction,
44
+ onboardingEvidenceLinks,
45
+ onboardingExperimentUrl,
40
46
  onboardingGrowthScenario,
47
+ onboardingInteraction,
48
+ readBootstrap,
49
+ readCheckoutRecoveryCohort,
50
+ readProgress,
41
51
  registrationLanguage,
42
52
  registrationMarket,
53
+ replayReportDates,
54
+ runOnboardingGrowth,
55
+ trustedProductHost,
56
+ verifyAndCompleteProgress,
57
+ waitForExperimentSampleSize,
43
58
  websiteEnvironment,
44
59
  websiteOrigin,
45
- withCliEntryContext
46
- } from "./chunk-SQEK6S4X.js";
60
+ writeProgress
61
+ } from "./chunk-GTENC5CO.js";
47
62
  import {
63
+ CapabilityGatewayError,
64
+ executeCapability,
48
65
  getLocalCliPackageInfo
49
- } from "./chunk-PUSFEC6B.js";
66
+ } from "./chunk-WG27BD67.js";
50
67
  import {
51
68
  SecureStoreAuthError,
52
69
  assertCredentialsReadable,
@@ -74,126 +91,11 @@ import {
74
91
 
75
92
  // src/core/onboarding/web-runtime.ts
76
93
  import { createHash as createHash2 } from "crypto";
77
- import path8 from "path";
78
-
79
- // src/core/onboarding/runtime.ts
80
- import crypto3 from "crypto";
81
94
  import path7 from "path";
82
95
 
83
- // src/core/onboarding/bootstrap-client.ts
84
- var PATH = "/backend/demo/v1/experience/cli/bootstrap-intents";
85
- var BootstrapRequestError = class extends Error {
86
- constructor(websiteStatus) {
87
- super(`The onboarding website request failed (HTTP ${websiteStatus}).`);
88
- this.websiteStatus = websiteStatus;
89
- }
90
- websiteStatus;
91
- };
92
- function loginMode(value) {
93
- if (value === void 0 || value === null) return void 0;
94
- if (value === "website_login" || value === "device_confirmation") return value;
95
- throw new Error("The website returned an invalid login mode.");
96
- }
97
- function authorizationStatus(value) {
98
- if (value === void 0 || value === null) return void 0;
99
- if (["pending", "authorizing", "approved", "claimed", "expired"].includes(String(value))) return value;
100
- throw new Error("The website returned an invalid authorization status.");
101
- }
102
- function bootstrapOrigin(market, environment = websiteEnvironment()) {
103
- return websiteOrigin(market, environment);
104
- }
105
- function trustedProductHost(value) {
106
- const url = new URL(value);
107
- if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || !["", "/"].includes(url.pathname)) {
108
- throw new Error("Onboarding requires a trusted HTTPS product origin.");
109
- }
110
- return url.origin;
111
- }
112
- function websiteUrl(value, origin) {
113
- const url = new URL(value);
114
- if (url.origin !== origin || url.username || url.password) throw new Error("The website returned an untrusted continuation URL.");
115
- return url.toString();
116
- }
117
- async function request(origin, endpoint, init, signal) {
118
- environmentForWebsiteOrigin(origin);
119
- const response = await fetch(`${origin}${endpoint}`, {
120
- ...init,
121
- redirect: "error",
122
- signal,
123
- headers: { Accept: "application/json", "Content-Type": "application/json", ...init.headers }
124
- });
125
- const body = safeJsonParse(await response.text());
126
- if (!response.ok || body?.return_code !== 0 || !body.data || typeof body.data !== "object") {
127
- throw new BootstrapRequestError(response.status);
128
- }
129
- return body.data;
130
- }
131
- async function createBootstrap(market, source, host, signal, toolReference, environment, language) {
132
- const origin = bootstrapOrigin(market, environment);
133
- const tool = cliEntrySource(source);
134
- if (toolReference && (tool !== "codex" || !UUID_PATTERN.test(toolReference))) throw new Error("Invalid AI tool continuation reference.");
135
- const data = await request(origin, PATH, { method: "POST", headers: {
136
- "X-AE-CLI-Login-Mode": "website_login",
137
- ...language ? { "Accept-Language": language } : {}
138
- }, body: JSON.stringify({
139
- market,
140
- source,
141
- ...host ? { requested_host: trustedProductHost(host) } : {},
142
- ...toolReference ? { tool_reference: toolReference } : {}
143
- }) }, signal);
144
- if (typeof data.intent_id !== "string" || !UUID_PATTERN.test(data.intent_id) || typeof data.poll_token !== "string" || data.poll_token.length < 16 || !Number.isFinite(Date.parse(data.expires_at))) {
145
- throw new Error("The website returned an invalid bootstrap session.");
146
- }
147
- return { ...data, login_mode: loginMode(data.login_mode), login_url: withCliEntryContext(websiteUrl(data.login_url, origin), tool, market, toolReference) };
148
- }
149
- async function readBootstrap(origin, intentId, pollToken, signal, source, market) {
150
- if (!UUID_PATTERN.test(intentId)) throw new Error("Invalid bootstrap continuation.");
151
- const data = await request(origin, `${PATH}/${encodeURIComponent(intentId)}`, {
152
- method: "GET",
153
- headers: { "X-CLI-Bootstrap-Token": pollToken }
154
- }, signal);
155
- if (data.intent_id !== intentId || !["pending", "account_ready", "browser_ready", "expired"].includes(data.status)) throw new Error("Invalid bootstrap state.");
156
- return {
157
- ...data,
158
- login_mode: loginMode(data.login_mode),
159
- authorization_status: authorizationStatus(data.authorization_status),
160
- host: data.host ? trustedProductHost(data.host) : null,
161
- ready_url: data.ready_url ? source ? withCliEntryContext(websiteUrl(data.ready_url, origin), cliEntrySource(source), market) : websiteUrl(data.ready_url, origin) : null
162
- };
163
- }
164
- async function claimBootstrapDevice(origin, intentId, pollToken, signal) {
165
- if (!UUID_PATTERN.test(intentId)) throw new Error("Invalid bootstrap continuation.");
166
- const data = await request(origin, `${PATH}/${encodeURIComponent(intentId)}/device`, {
167
- method: "POST",
168
- body: "{}",
169
- headers: { "X-CLI-Bootstrap-Token": pollToken }
170
- }, signal).catch((error) => {
171
- if (error instanceof BootstrapRequestError && error.websiteStatus === 410) {
172
- return { login_mode: "website_login", authorization_status: "expired" };
173
- }
174
- throw error;
175
- });
176
- if (loginMode(data.login_mode) !== "website_login") throw new Error("The website did not confirm this login mode.");
177
- const status = authorizationStatus(data.authorization_status);
178
- if (!status) throw new Error("The website returned an invalid authorization status.");
179
- if (status !== "approved" && status !== "claimed") return {
180
- login_mode: "website_login",
181
- authorization_status: status,
182
- ...Number.isFinite(data.poll_after_ms) ? { poll_after_ms: data.poll_after_ms } : {}
183
- };
184
- if (typeof data.device_code !== "string" || !/^uba_[A-Za-z0-9_-]{43}$/.test(data.device_code) || typeof data.user_code !== "string" || !/^[A-HJ-NP-Z2-9]{8}$/.test(data.user_code) || !Number.isFinite(Date.parse(data.expires_at)) || !Number.isFinite(data.interval) || data.interval < 1 || data.interval > 60 || typeof data.expected_login_name !== "string" || !data.expected_login_name.trim() || data.expected_login_name.length > 256 || !/^[1-9][0-9]*$/.test(String(data.expected_company_id)) || !Number.isSafeInteger(Number(data.expected_company_id))) throw new Error("The website returned an invalid device connection.");
185
- return {
186
- login_mode: "website_login",
187
- authorization_status: status,
188
- host: trustedProductHost(data.host),
189
- device_code: data.device_code,
190
- user_code: data.user_code,
191
- expires_at: data.expires_at,
192
- interval: data.interval,
193
- expected_login_name: data.expected_login_name,
194
- expected_company_id: String(data.expected_company_id)
195
- };
196
- }
96
+ // src/core/onboarding/runtime.ts
97
+ import crypto2 from "crypto";
98
+ import path6 from "path";
197
99
 
198
100
  // src/core/onboarding/website-login-identity.ts
199
101
  async function verifyWebsiteLoginIdentity(host, accessToken, expected, signal) {
@@ -331,419 +233,9 @@ var OnboardingStore = class {
331
233
  }
332
234
  };
333
235
 
334
- // src/core/onboarding/growth.ts
335
- import crypto2 from "crypto";
336
- import path2 from "path";
337
-
338
- // src/core/onboarding/interaction.ts
339
- var interactions = {
340
- complete_website_login: [
341
- { value: "login_done", label: "I finished signing in" },
342
- { value: "login_help", label: "I need help signing in" }
343
- ],
344
- approve_device: [
345
- { value: "authorization_done", label: "I approved CLI access" },
346
- { value: "authorization_help", label: "I need help authorizing the CLI" }
347
- ],
348
- restart_website_login: [
349
- { value: "retry_login", label: "Start a new sign-in" },
350
- { value: "not_now", label: "Not now" }
351
- ],
352
- choose_experience: [
353
- { value: "demo", label: "Start the demo" },
354
- { value: "business", label: "Connect my business data" }
355
- ],
356
- confirm_business_project: [
357
- { value: "confirm_project", label: "Use this AE project" },
358
- { value: "not_now", label: "Not now" }
359
- ],
360
- offer_growth_questions: [
361
- { value: "growth", label: "Find a growth opportunity" },
362
- { value: "checkout_recovery", label: "Win back players who started checkout but did not pay" },
363
- { value: "change_sample", label: "Change sample" }
364
- ],
365
- growth_ready: [
366
- { value: "follow_up", label: "How should we follow up with these users?" },
367
- { value: "change_sample", label: "Change sample" }
368
- ],
369
- confirm_experiment: [
370
- { value: "launch", label: "Confirm and start the A/B experiment" },
371
- { value: "start_later", label: "Start later" }
372
- ],
373
- reauthorize_cli: [
374
- { value: "reauthorize", label: "Reconnect the CLI" },
375
- { value: "not_now", label: "Not now" }
376
- ]
377
- };
378
- function onboardingInteraction(step, web = false) {
379
- if (!Object.hasOwn(interactions, step)) return void 0;
380
- const options = web && step === "choose_experience" ? [interactions.choose_experience[0], { value: "not_now", label: "Not now" }] : interactions[step];
381
- return { step, options };
382
- }
383
- function onboardingEvidenceLinks(evidence, projectId, host) {
384
- if (!evidence || typeof evidence !== "object" || typeof projectId !== "number" || !Number.isSafeInteger(projectId) || projectId < 1) return void 0;
385
- const paths = evidence;
386
- const links = {};
387
- const evidenceRoutes = {
388
- dashboard_url: "panel/panel",
389
- purchase_rate_report_url: "tga/ide",
390
- funnel_report_url: "tga/funnel"
391
- };
392
- for (const [key, route] of Object.entries(evidenceRoutes)) {
393
- const value = paths[key];
394
- if (typeof value === "string" && new RegExp(`^/#/${route}/${projectId}_[1-9][0-9]*$`).test(value)) {
395
- links[key] = host ? absolutizeRelativeUrls(value, host) : value;
396
- }
397
- }
398
- return Object.keys(links).length ? links : void 0;
399
- }
400
- function onboardingExperimentUrl(projectId, experimentId, host) {
401
- const params = new URLSearchParams({ expId: experimentId, currentProjectId: String(projectId) });
402
- const route = `/#/atlas/experiment/detail?${params}`;
403
- return host ? absolutizeRelativeUrls(route, host) : route;
404
- }
405
-
406
- // src/core/onboarding/growth.ts
407
- var GROWTH_VERSION = 2;
408
- var CACHE_TTL_MS = 10 * 6e4;
409
- var DAY_MS = 864e5;
410
- var VIEW = "item_detail_view";
411
- var CHECKOUT = "checkout_start";
412
- var PAYMENT = "payment_success";
413
- var fields = [
414
- "single_viewers",
415
- "single_buyers",
416
- "multi_viewers",
417
- "multi_buyers",
418
- "funnel_viewers",
419
- "funnel_checkout",
420
- "funnel_buyers",
421
- "account_ids_json",
422
- "checkout_unpaid",
423
- "checkout_account_ids_json",
424
- "unmapped_accounts"
425
- ];
426
- function date(value) {
427
- return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
428
- }
429
- function shiftDate(value, days) {
430
- return new Date(Date.parse(value) + days * DAY_MS).toISOString().slice(0, 10);
431
- }
432
- function growthScope(session, demo) {
433
- const { project_id, sample_id, item_id, start_date, end_date, zone_offset } = demo;
434
- if (!session.host || !sample_id || sample_id !== session.sample_id || typeof project_id !== "number" || !Number.isSafeInteger(project_id) || project_id <= 0 || project_id === session.project_id || typeof item_id !== "string" || !item_id.trim() || item_id.length > 128 || !date(start_date) || !date(end_date) || Date.parse(end_date) - Date.parse(start_date) !== 6 * DAY_MS || typeof zone_offset !== "number" || !Number.isFinite(zone_offset) || Math.abs(zone_offset) > 14) return void 0;
435
- return {
436
- sessionId: session.id,
437
- host: trustedProductHost(session.host),
438
- projectId: project_id,
439
- sampleId: sample_id,
440
- itemId: item_id,
441
- startDate: start_date,
442
- endDate: end_date,
443
- zoneOffset: zone_offset
444
- };
445
- }
446
- function evidenceFile(scope, credentialKey) {
447
- const digest = crypto2.createHash("sha256").update(JSON.stringify([GROWTH_VERSION, credentialKey, scope])).digest("hex");
448
- return `growth-${digest}.json`;
449
- }
450
- function readGrowthEvidence(store, file, scope) {
451
- const evidence = store.read(file);
452
- if (evidence?.analysisVersion === GROWTH_VERSION && evidence.schemaVersion === 1 && Object.entries(scope).every(([key, value]) => evidence[key] === value) && Array.isArray(evidence.accountIds) && Array.isArray(evidence.checkoutAccountIds) && evidence.single_day && evidence.multi_day && evidence.funnel) return evidence;
453
- }
454
- function readCheckoutRecoveryCohort(store, session, demo) {
455
- const scope = growthScope(session, demo);
456
- if (!scope || !session.credential_key) return void 0;
457
- const evidence = readGrowthEvidence(store, evidenceFile(scope, session.credential_key), scope);
458
- if (!evidence) return void 0;
459
- return { start_date: scope.startDate, end_date: scope.endDate, zone_offset: scope.zoneOffset, account_ids: evidence.checkoutAccountIds };
460
- }
461
- function sqlString(value) {
462
- return `'${value.replaceAll("'", "''")}'`;
463
- }
464
- function verifiedTables(result, type) {
465
- return result.items.filter((item) => item?.table_type === type && typeof item.sql_reference === "string" && /^(?:"(?:[^"\u0000-\u001f]|"")+"\.){2}"(?:[^"\u0000-\u001f]|"")+"$/.test(item.sql_reference)).map((item) => item.sql_reference);
466
- }
467
- async function resolveEventSource(call, projectId) {
468
- let offset = 0;
469
- const events = /* @__PURE__ */ new Set();
470
- const users = /* @__PURE__ */ new Set();
471
- const scope = { project_id: projectId, usage: "analysis" };
472
- while (true) {
473
- const page = await call("analysis.sql_table.list", { ...scope, limit: 200, offset });
474
- if (!Array.isArray(page?.items) || typeof page.has_more !== "boolean") throw new Error("AE did not return the authorized SQL tables.");
475
- verifiedTables(page, "eventView").forEach((name) => events.add(name));
476
- verifiedTables(page, "userView").forEach((name) => users.add(name));
477
- if (!page.has_more) break;
478
- if (!Number.isSafeInteger(page.next_offset) || page.next_offset <= offset) throw new Error("AE returned an invalid SQL table continuation.");
479
- offset = page.next_offset;
480
- }
481
- if (events.size !== 1) throw new Error("AE did not return exactly one authorized Demo event view.");
482
- const event = [...events][0];
483
- const readColumns = async (table_ref) => {
484
- const result = await call("analysis.sql_table.columns", { ...scope, table_ref });
485
- if (!Array.isArray(result?.columns)) throw new Error("AE did not return the authorized Demo columns.");
486
- return new Set(result.columns.map((entry) => entry.column));
487
- };
488
- const columns = await readColumns(event);
489
- if (!["#event_time", "$part_date", "$part_event", "plg_sample_id", "item_id", "plg_seed_event_id"].every((name) => columns.has(name))) {
490
- throw new Error("The authorized Demo view is missing the fields required for growth analysis.");
491
- }
492
- if (columns.has("#account_id")) return { from: `${event} e`, account: 'e."#account_id"' };
493
- if (!columns.has("#user_id") || users.size !== 1) throw new Error("AE did not expose a verified Demo account-ID mapping.");
494
- const user = [...users][0];
495
- const userColumns = await readColumns(user);
496
- if (!userColumns.has("#user_id") || !userColumns.has("#account_id")) throw new Error("AE did not expose a verified Demo account-ID mapping.");
497
- return { from: `${event} e LEFT JOIN ${user} u ON e."#user_id" = u."#user_id"`, account: 'u."#account_id"' };
498
- }
499
- function growthSql(scope, source) {
500
- return `WITH sample_events AS (
501
- SELECT NULLIF(CAST(${source.account} AS varchar), '') AS account_id,
502
- e."$part_event" AS event_name, e."#event_time" AS event_time
503
- FROM ${source.from}
504
- WHERE e."$part_date" BETWEEN '${shiftDate(scope.startDate, -1)}' AND '${shiftDate(scope.endDate, 1)}'
505
- AND e."#event_time" >= TIMESTAMP '${scope.startDate} 00:00:00'
506
- AND e."#event_time" < TIMESTAMP '${shiftDate(scope.endDate, 1)} 00:00:00'
507
- AND e.plg_sample_id = ${sqlString(scope.sampleId)} AND e.item_id = ${sqlString(scope.itemId)}
508
- AND e.plg_seed_event_id IS NOT NULL
509
- AND e."$part_event" IN ('${VIEW}', '${CHECKOUT}', '${PAYMENT}')
510
- ), views AS (
511
- SELECT *, min(CASE WHEN event_name = '${VIEW}' THEN event_time END) OVER (PARTITION BY account_id) AS first_view
512
- FROM sample_events
513
- ), checkouts AS (
514
- SELECT *, min(CASE WHEN event_name = '${CHECKOUT}' AND event_time > first_view THEN event_time END)
515
- OVER (PARTITION BY account_id) AS first_checkout
516
- FROM views
517
- ), accounts AS (
518
- SELECT account_id, count(DISTINCT CAST(event_time AS date)) FILTER (WHERE event_name = '${VIEW}') AS view_days,
519
- count_if(event_name = '${PAYMENT}') > 0 AS bought,
520
- count_if(first_checkout IS NOT NULL) > 0 AS checked_out,
521
- count_if(event_name = '${PAYMENT}' AND event_time > first_checkout) > 0 AS paid_after_checkout
522
- FROM checkouts GROUP BY account_id
523
- )
524
- SELECT count_if(view_days = 1) AS single_viewers, count_if(view_days = 1 AND bought) AS single_buyers,
525
- count_if(view_days >= 2) AS multi_viewers, count_if(view_days >= 2 AND bought) AS multi_buyers,
526
- count_if(view_days > 0) AS funnel_viewers, count_if(checked_out) AS funnel_checkout,
527
- count_if(paid_after_checkout) AS funnel_buyers,
528
- COALESCE(json_format(CAST(array_sort(array_agg(account_id) FILTER (WHERE view_days >= 2 AND NOT bought)) AS JSON)), '[]') AS account_ids_json,
529
- count_if(checked_out AND NOT bought) AS checkout_unpaid,
530
- COALESCE(json_format(CAST(array_sort(array_agg(account_id) FILTER (WHERE checked_out AND NOT bought)) AS JSON)), '[]') AS checkout_account_ids_json,
531
- count_if(account_id IS NULL) AS unmapped_accounts
532
- FROM accounts`;
533
- }
534
- function accountIds(value, expected) {
535
- let ids;
536
- try {
537
- ids = typeof value === "string" ? JSON.parse(value) : void 0;
538
- } catch {
539
- }
540
- if (!Array.isArray(ids) || ids.length !== expected || new Set(ids).size !== ids.length || !ids.every((id) => typeof id === "string" && id.length > 0 && id.length <= 256 && id === id.trim())) {
541
- throw new Error("AE returned incomplete or inconsistent Demo growth evidence.");
542
- }
543
- return ids;
544
- }
545
- function parseGrowth(result, scope, verifiedAt) {
546
- if (result?.has_more !== false || result.returned_rows !== 1 || result.rows?.length !== 1 || !Array.isArray(result.title) || !Array.isArray(result.rows[0])) {
547
- throw new Error("AE did not return a complete Demo growth result.");
548
- }
549
- const row = Object.fromEntries(result.title.map((name, index) => [name, result.rows[0][index]]));
550
- if (!fields.every((field) => Object.hasOwn(row, field))) throw new Error("AE did not return the expected Demo growth fields.");
551
- const count = (field) => {
552
- const raw = row[field];
553
- const value = typeof raw === "string" && /^\d+$/.test(raw) ? Number(raw) : raw;
554
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error("AE returned an invalid Demo growth count.");
555
- return value;
556
- };
557
- const single_day = { viewers: count("single_viewers"), buyers: count("single_buyers") };
558
- const multi_day = { viewers: count("multi_viewers"), buyers: count("multi_buyers") };
559
- const funnel = { viewers: count("funnel_viewers"), checkout: count("funnel_checkout"), buyers: count("funnel_buyers") };
560
- const checkoutUnpaid = count("checkout_unpaid");
561
- if (single_day.buyers > single_day.viewers || multi_day.buyers > multi_day.viewers || funnel.checkout > funnel.viewers || funnel.buyers + checkoutUnpaid > funnel.checkout || funnel.viewers !== single_day.viewers + multi_day.viewers || count("unmapped_accounts") !== 0 || funnel.viewers === 0) {
562
- throw new Error("AE returned incomplete or inconsistent Demo growth evidence.");
563
- }
564
- return {
565
- ...scope,
566
- schemaVersion: 1,
567
- analysisVersion: GROWTH_VERSION,
568
- verifiedAt,
569
- single_day,
570
- multi_day,
571
- funnel,
572
- accountIds: accountIds(row.account_ids_json, multi_day.viewers - multi_day.buyers),
573
- checkoutAccountIds: accountIds(row.checkout_account_ids_json, checkoutUnpaid)
574
- };
575
- }
576
- async function runOnboardingGrowth(store, deps, input, preview) {
577
- const scenario = onboardingGrowthScenario(input.scenario);
578
- const sessionId = input.session_id;
579
- if (!sessionId || !UUID_PATTERN.test(sessionId)) throw new Error("A valid onboarding --session-id is required.");
580
- const explicitHost = input.host ? trustedProductHost(input.host) : void 0;
581
- const readSession = () => store.session(sessionId, explicitHost);
582
- if (preview) {
583
- const session = readSession();
584
- return {
585
- dry_run: true,
586
- session_id: sessionId,
587
- host: session.host ?? null,
588
- sample_id: session.sample_id ?? null,
589
- scenario,
590
- capabilities: [DEMO_STATUS, "analysis.sql_table.list", "analysis.sql_table.columns", "analysis.adhoc.run"]
591
- };
592
- }
593
- const started = deps.now();
594
- const signal = AbortSignal.timeout(RUN_BUDGET_MS);
595
- return store.locked(`session:${sessionId}`, async () => {
596
- const session = readSession();
597
- const base = { session_id: sessionId, host: session.host ?? null, sample_id: session.sample_id ?? null, scenario };
598
- if (!session.host || !session.credential_key || session.requires_auth || deps.credentialKey(session.host) !== session.credential_key) {
599
- return {
600
- ...base,
601
- phase: "action_required",
602
- next_action: "resume_onboarding",
603
- poll_after_ms: 0,
604
- message: "Resume onboarding with the signed-in account for this session."
605
- };
606
- }
607
- const host = trustedProductHost(session.host);
608
- if (session.choice !== "demo" || !session.sample_id || !DEMO_SAMPLE_IDS.some((sample) => sample === session.sample_id)) {
609
- return {
610
- ...base,
611
- phase: "action_required",
612
- next_action: "choose_demo",
613
- poll_after_ms: 0,
614
- message: "Select a supported Demo in this onboarding session."
615
- };
616
- }
617
- const call = async (id, body) => {
618
- signal.throwIfAborted();
619
- const request2 = new AbortController();
620
- const abort = () => request2.abort();
621
- const timer = setTimeout(abort, NETWORK_BUDGET_MS);
622
- timer.unref();
623
- signal.addEventListener("abort", abort, { once: true });
624
- try {
625
- const result = await deps.capability(host, id, body, request2.signal);
626
- request2.signal.throwIfAborted();
627
- return result;
628
- } finally {
629
- signal.removeEventListener("abort", abort);
630
- clearTimeout(timer);
631
- }
632
- };
633
- try {
634
- const demo = await call(DEMO_STATUS, { sample_id: session.sample_id });
635
- if (typeof demo?.status !== "string" || demo.sample_id !== session.sample_id) {
636
- throw new Error("AE did not confirm the selected Demo sample.");
637
- }
638
- if (demo.status !== "ready") {
639
- return demo.status === "action_required" ? {
640
- ...base,
641
- phase: "action_required",
642
- next_action: "inspect_demo_preparation",
643
- poll_after_ms: 0,
644
- message: "Demo preparation needs attention before analysis can run."
645
- } : { ...base, phase: "pending", next_action: "poll_demo", poll_after_ms: 2e3 };
646
- }
647
- const scope = growthScope(session, demo);
648
- if (!scope) throw new Error("AE did not confirm the active Demo project and its seven-day sample scope.");
649
- const file = evidenceFile(scope, session.credential_key);
650
- let evidence = readGrowthEvidence(store, file, scope);
651
- const cached = evidence !== void 0 && deps.now() - evidence.verifiedAt >= 0 && deps.now() - evidence.verifiedAt < CACHE_TTL_MS;
652
- let queryMs = 0;
653
- if (!evidence || !cached) {
654
- const source = await resolveEventSource(call, scope.projectId);
655
- const queryStarted = deps.now();
656
- const rows = await call("analysis.adhoc.run", {
657
- project_id: scope.projectId,
658
- model_type: "sql",
659
- definition: { sql: growthSql(scope, source) },
660
- use_cache: false
661
- });
662
- queryMs = Math.max(0, deps.now() - queryStarted);
663
- evidence = parseGrowth(rows, scope, deps.now());
664
- }
665
- if (deps.credentialKey(host) !== session.credential_key) throw new Error("The active CLI account changed during Demo growth analysis.");
666
- if (!cached) store.write(file, evidence);
667
- const readyDemo = {
668
- sample_id: scope.sampleId,
669
- item_id: scope.itemId,
670
- project_id: scope.projectId,
671
- start_date: scope.startDate,
672
- end_date: scope.endDate,
673
- zone_offset: scope.zoneOffset
674
- };
675
- if (!Object.entries(readyDemo).every(([key, value]) => session.ready_demo?.[key] === value)) {
676
- session.ready_demo = readyDemo;
677
- store.save(session);
678
- }
679
- const singleRate = evidence.single_day.viewers ? evidence.single_day.buyers / evidence.single_day.viewers : null;
680
- const multiRate = evidence.multi_day.viewers ? evidence.multi_day.buyers / evidence.multi_day.viewers : null;
681
- const checkoutUnpaid = evidence.checkoutAccountIds.length;
682
- const followUpData = scenario === CHECKOUT_RECOVERY ? [
683
- { label: "Started checkout", value: evidence.funnel.checkout },
684
- { label: "Paid after checkout", value: evidence.funnel.buyers },
685
- { label: "Checkout without payment", value: checkoutUnpaid }
686
- ] : [
687
- { label: "Multi-day viewers, unpaid", value: evidence.accountIds.length },
688
- { label: "Single-day viewers, unpaid", value: evidence.single_day.viewers - evidence.single_day.buyers },
689
- { label: "Paid viewers", value: evidence.single_day.buyers + evidence.multi_day.buyers }
690
- ];
691
- const maxCount = Math.max(1, ...followUpData.map((row) => row.value));
692
- const followUpMarkdown = followUpData.map(({ label, value }) => {
693
- const width = value === 0 ? 0 : Math.max(1, Math.round(value * 10 / maxCount));
694
- return `- ${label} \xB7 ${width ? "\u2588".repeat(width) + " " : ""}**${value}**`;
695
- }).join("\n");
696
- return {
697
- ...base,
698
- phase: "ready",
699
- demo_project_id: scope.projectId,
700
- item_id: scope.itemId,
701
- start_date: scope.startDate,
702
- end_date: scope.endDate,
703
- zone_offset: scope.zoneOffset,
704
- analysis_version: GROWTH_VERSION,
705
- single_day: evidence.single_day,
706
- multi_day: evidence.multi_day,
707
- funnel: evidence.funnel,
708
- purchase_rates: {
709
- single_day: singleRate,
710
- multi_day: multiRate,
711
- difference_pp: singleRate === null || multiRate === null ? null : (multiRate - singleRate) * 100
712
- },
713
- charts: {
714
- purchase_rate: { type: "bar", data: [
715
- ...singleRate === null ? [] : [{ label: "Single-day viewers", value: Math.round(singleRate * 1e3) / 10 }],
716
- ...multiRate === null ? [] : [{ label: "Multi-day viewers", value: Math.round(multiRate * 1e3) / 10 }]
717
- ] },
718
- funnel: { type: "bar", data: [
719
- { label: "Viewed", value: evidence.funnel.viewers },
720
- { label: "Started checkout", value: evidence.funnel.checkout },
721
- { label: "Paid", value: evidence.funnel.buyers }
722
- ] }
723
- },
724
- follow_up_chart: { type: "bar", data: followUpData, markdown: followUpMarkdown },
725
- follow_up_count: scenario === CHECKOUT_RECOVERY ? checkoutUnpaid : evidence.accountIds.length,
726
- checkout_recovery: { unpaid_count: checkoutUnpaid, unpaid_rate: evidence.funnel.checkout ? checkoutUnpaid / evidence.funnel.checkout : null },
727
- cohort_path: path2.resolve(store.directory, file),
728
- evidence: onboardingEvidenceLinks(demo.evidence, scope.projectId, deps.webConversation ? void 0 : host),
729
- interaction: onboardingInteraction(scenario === CHECKOUT_RECOVERY && checkoutUnpaid < 2 ? "offer_growth_questions" : "growth_ready"),
730
- cached,
731
- query_ms: queryMs,
732
- elapsed_ms: Math.max(0, deps.now() - started),
733
- poll_after_ms: 0
734
- };
735
- } catch (error) {
736
- if (signal.aborted || error instanceof Error && ["AbortError", "TimeoutError"].includes(error.name)) {
737
- return { ...base, phase: "pending", next_action: "retry_growth", poll_after_ms: 2e3 };
738
- }
739
- throw error;
740
- }
741
- });
742
- }
743
-
744
236
  // src/core/onboarding/experiment-launch.ts
745
237
  import { createHash } from "crypto";
746
- import path5 from "path";
238
+ import path4 from "path";
747
239
  import { isDeepStrictEqual } from "util";
748
240
 
749
241
  // skills/ae-onboarding/scripts/experiment-preset.json
@@ -1002,9 +494,49 @@ var experiment_preset_default = {
1002
494
 
1003
495
  // src/core/onboarding/experiment-plan.ts
1004
496
  import { randomUUID } from "crypto";
1005
- import path3 from "path";
497
+ import path2 from "path";
1006
498
  var PROJECT_INFO = "project.info.get";
1007
499
  var APPROVER_ADD = "experiment.approver.add";
500
+ function readActivePlan(store, deps, input) {
501
+ const { session_id: sessionId, run_id: runId } = input;
502
+ if (!sessionId || !UUID_PATTERN.test(sessionId) || !runId || !/^[0-9a-f]{32}$/.test(runId)) {
503
+ throw new Error("Pass the onboarding session ID and the run ID returned by experiment-plan.");
504
+ }
505
+ const session = store.session(sessionId, input.host ? trustedProductHost(input.host) : void 0);
506
+ const file = `experiment-plan-${runId}.json`;
507
+ const plan = store.read(file);
508
+ const scope = session.ready_demo;
509
+ if (!plan || plan.phase !== "ready" || plan.session_id !== session.id || plan.run_id !== runId || !session.host || plan.host !== session.host || session.choice !== "demo" || !scope || plan.sample_id !== session.sample_id || plan.sample_id !== scope.sample_id || plan.item_id !== scope.item_id || plan.demo_project_id !== scope.project_id || !session.credential_key || session.requires_auth || plan.credential_key !== session.credential_key || deps.credentialKey(session.host) !== session.credential_key) {
510
+ throw new Error("The saved experiment plan does not match the active Demo session and account.");
511
+ }
512
+ return { file, plan };
513
+ }
514
+ function publicPlan(plan) {
515
+ const { checkout_cohort: _cohort, credential_key: _key, ...review } = plan;
516
+ return plan.approver?.status === "deferred" ? { ...review, interaction: onboardingDraftReviewInteraction(plan.answered_questions) } : review;
517
+ }
518
+ function readOnboardingExperimentPlan(store, deps, input) {
519
+ return publicPlan(readActivePlan(store, deps, input).plan);
520
+ }
521
+ function recordAnsweredQuestion(store, deps, input, preview) {
522
+ const { session_id: sessionId, answered_question: question } = input;
523
+ if (!sessionId || !UUID_PATTERN.test(sessionId) || !input.run_id || !question || input.scenario || input.draft_only || input.upload_metric_event || input.prepare_approver) {
524
+ throw new Error("Use --session-id, --run-id, and --answered-question together for draft review.");
525
+ }
526
+ if (!onboardingDraftReviewInteraction().options.some((option) => option.value === question && option.value !== "launch")) {
527
+ throw new Error("Use --answered-question review_audience, review_pilot, or review_no_reward.");
528
+ }
529
+ const update = () => {
530
+ const { file, plan } = readActivePlan(store, deps, input);
531
+ if (plan.approver?.status !== "deferred") throw new Error("Only a plan saved with --draft-only supports review questions.");
532
+ const answered = plan.answered_questions ?? [];
533
+ const updated = answered.includes(question) ? plan : { ...plan, answered_questions: [...answered, question] };
534
+ if (!preview && updated !== plan) store.write(file, updated);
535
+ const result = publicPlan(updated);
536
+ return preview ? { ...result, dry_run: true } : result;
537
+ };
538
+ return preview ? update() : store.locked(`session:${sessionId}`, async () => update());
539
+ }
1008
540
  function readyDemoScope(demo, session) {
1009
541
  if (demo?.status !== "ready" || !demo.sample_id || demo.sample_id !== session.sample_id || typeof demo.item_id !== "string" || !demo.item_id || typeof demo.project_id !== "number" || !Number.isSafeInteger(demo.project_id) || demo.project_id <= 0 || demo.project_id === session.project_id) return void 0;
1010
542
  return {
@@ -1017,10 +549,16 @@ function readyDemoScope(demo, session) {
1017
549
  };
1018
550
  }
1019
551
  async function runOnboardingExperimentPlan(store, deps, input, preview) {
552
+ if (input.run_id !== void 0 || input.answered_question !== void 0) {
553
+ return recordAnsweredQuestion(store, deps, input, preview);
554
+ }
1020
555
  const scenario = onboardingGrowthScenario(input.scenario);
1021
556
  if (scenario === CHECKOUT_RECOVERY && input.upload_metric_event) {
1022
557
  throw new Error("Checkout recovery prepares the plan locally. Use experiment-launch after the user confirms it.");
1023
558
  }
559
+ if (input.draft_only && (input.upload_metric_event || input.prepare_approver)) {
560
+ throw new Error("Use --draft-only by itself to prepare a plan for review.");
561
+ }
1024
562
  const sessionId = input.session_id;
1025
563
  if (!sessionId) throw new Error("A valid onboarding --session-id is required.");
1026
564
  const explicitHost = input.host ? trustedProductHost(input.host) : void 0;
@@ -1031,11 +569,12 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
1031
569
  session_id: sessionId,
1032
570
  host: session.host ?? null,
1033
571
  sample_id: session.sample_id ?? null,
572
+ currency: deps.demoCurrency(session.host, session.region),
1034
573
  ...input.scenario ? { scenario } : {},
1035
574
  capabilities: [
1036
575
  ...session.ready_demo ? [] : [DEMO_STATUS],
1037
576
  ...input.upload_metric_event ? [PROJECT_INFO] : [],
1038
- APPROVER_ADD
577
+ ...input.draft_only ? [] : [APPROVER_ADD]
1039
578
  ],
1040
579
  ...input.upload_metric_event ? { metric_event: { event_name: "payment_success", record_count: 1 } } : {}
1041
580
  };
@@ -1073,6 +612,7 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
1073
612
  throw new Error("The active Demo sample and item have no supported experiment preset.");
1074
613
  }
1075
614
  const preset = experiment_preset_default.experimentTypes[scenario];
615
+ const currency = deps.demoCurrency(host, session.region);
1076
616
  const checkoutCohort = scenario === CHECKOUT_RECOVERY ? readCheckoutRecoveryCohort(store, session, scope) : void 0;
1077
617
  if (scenario === CHECKOUT_RECOVERY && !checkoutCohort) {
1078
618
  return {
@@ -1093,6 +633,7 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
1093
633
  }
1094
634
  const eventId = randomUUID();
1095
635
  const runId = eventId.replaceAll("-", "");
636
+ const audienceCount = checkoutCohort?.account_ids.length ?? selection.sample.followUpAccountIds.length;
1096
637
  const result = {
1097
638
  ...base,
1098
639
  phase: "ready",
@@ -1102,11 +643,12 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
1102
643
  industry: selection.industry,
1103
644
  experiment_type: scenario,
1104
645
  run_id: runId,
1105
- interaction: onboardingInteraction("confirm_experiment"),
646
+ interaction: input.draft_only ? onboardingDraftReviewInteraction() : onboardingInteraction("confirm_experiment"),
647
+ ...input.draft_only ? { answered_questions: [], review: { pilot_accounts_per_arm: Math.min(4, Math.floor(audienceCount / 2)) } } : {},
1106
648
  plan: {
1107
649
  synthetic: true,
1108
650
  hypothesis: preset.experiment.hypothesis,
1109
- audience_count: checkoutCohort?.account_ids.length ?? selection.sample.followUpAccountIds.length,
651
+ audience_count: audienceCount,
1110
652
  audience: {
1111
653
  minimum_view_days: preset.audience.minimumViewDays,
1112
654
  view_event: preset.audience.viewEvent,
@@ -1122,7 +664,7 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
1122
664
  bucket_id: preset.audience.bucketId,
1123
665
  arms: Object.entries(preset.arms).map(([role, arm]) => ({ role, name: arm.name, allocation: arm.allocation, price: arm.price })),
1124
666
  metrics: preset.metrics,
1125
- currency: preset.currency,
667
+ currency,
1126
668
  cost_per_paid_order: preset.costPerPaidOrder,
1127
669
  other_costs: preset.otherCosts
1128
670
  }
@@ -1132,14 +674,24 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
1132
674
  "| A \xB7 Control | B \xB7 Treatment |",
1133
675
  "| --- | --- |",
1134
676
  `| ${control.name} | ${treatment.name} |`,
1135
- `| ${control.price} ${preset.currency} \xB7 ${control.allocation}% | ${treatment.price} ${preset.currency} \xB7 ${treatment.allocation}% |`
677
+ `| ${control.price} ${currency} \xB7 ${control.allocation}% | ${treatment.price} ${currency} \xB7 ${treatment.allocation}% |`
1136
678
  ].join("\n");
1137
679
  const file = `experiment-plan-${runId}.json`;
1138
- const planPath = path3.resolve(store.directory, file);
680
+ const planPath = path2.resolve(store.directory, file);
681
+ const savePlan = (plan) => store.write(file, {
682
+ ...plan,
683
+ ...input.draft_only ? { plan_preview_markdown: planPreviewMarkdown } : {},
684
+ ...input.draft_only || checkoutCohort ? { credential_key: session.credential_key } : {},
685
+ ...checkoutCohort ? { checkout_cohort: checkoutCohort } : {}
686
+ });
687
+ if (input.draft_only) {
688
+ const draft = { ...result, approver: { status: "deferred" } };
689
+ savePlan(draft);
690
+ return { ...draft, plan_path: planPath, plan_preview_markdown: planPreviewMarkdown };
691
+ }
1139
692
  const metricEvent = input.upload_metric_event ? { event_name: preset.events.payment, event_id: eventId, persistence_verified: false } : void 0;
1140
- store.write(file, {
693
+ savePlan({
1141
694
  ...result,
1142
- ...checkoutCohort ? { checkout_cohort: checkoutCohort, credential_key: session.credential_key } : {},
1143
695
  ...metricEvent ? { metric_event: { ...metricEvent, status: "pending" } } : {},
1144
696
  approver: { status: "pending" }
1145
697
  });
@@ -1156,7 +708,7 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
1156
708
  plg_sample_id: sampleId,
1157
709
  item_id: scope.item_id,
1158
710
  amount: preset.arms.control.price,
1159
- currency: preset.currency,
711
+ currency,
1160
712
  order_id: eventId
1161
713
  }
1162
714
  }) : void 0
@@ -1166,10 +718,7 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
1166
718
  approver,
1167
719
  ...delivery ? { metric_event: { ...metricEvent, ...delivery } } : {}
1168
720
  };
1169
- store.write(file, {
1170
- ...preparedPlan,
1171
- ...checkoutCohort ? { checkout_cohort: checkoutCohort, credential_key: session.credential_key } : {}
1172
- });
721
+ savePlan(preparedPlan);
1173
722
  return { ...preparedPlan, plan_path: planPath, plan_preview_markdown: planPreviewMarkdown };
1174
723
  });
1175
724
  }
@@ -1222,7 +771,7 @@ async function uploadPlanPayment(deps, host, credentialKey, scope, event) {
1222
771
  // src/core/onboarding/experiment-replay.ts
1223
772
  import { execFile } from "child_process";
1224
773
  import { mkdtemp, readFile, rm, writeFile } from "fs/promises";
1225
- import path4 from "path";
774
+ import path3 from "path";
1226
775
  import { promisify } from "util";
1227
776
  var exec = promisify(execFile);
1228
777
  var OUTCOME_DELAY_MS = 5e3;
@@ -1231,7 +780,7 @@ async function runExperimentScript(script, args) {
1231
780
  if (!root) throw new Error("The PLG preset scripts could not be located in this CLI package.");
1232
781
  const { stdout } = await exec(
1233
782
  process.execPath,
1234
- [path4.join(root, "skills", "ae-onboarding", "scripts", script), ...args],
783
+ [path3.join(root, "skills", "ae-onboarding", "scripts", script), ...args],
1235
784
  { timeout: 15e3 }
1236
785
  );
1237
786
  return stdout;
@@ -1248,12 +797,12 @@ async function prepareExperimentReplay(options) {
1248
797
  const midnight = Math.floor((now + offsetMs) / 864e5) * 864e5 - offsetMs;
1249
798
  const experimentStart = Date.parse(options.startTime);
1250
799
  if (!Number.isFinite(experimentStart) || experimentStart > now) throw new Error("The running experiment has no elapsed start time.");
1251
- const start = Math.max(experimentStart, midnight, now - OUTCOME_DELAY_MS);
1252
- const end = start + OUTCOME_DELAY_MS;
1253
- const directory = await mkdtemp(path4.join(options.directory, "experiment-replay-"));
800
+ const start = options.savedTiming ? Date.parse(options.savedTiming.start) : Math.max(experimentStart, midnight, now - OUTCOME_DELAY_MS);
801
+ const end = options.savedTiming ? Date.parse(options.savedTiming.end) : start + OUTCOME_DELAY_MS;
802
+ const directory = await mkdtemp(path3.join(options.directory, "experiment-replay-"));
1254
803
  try {
1255
- const cohort = path4.join(directory, "cohort.json");
1256
- const replay = path4.join(directory, "replay");
804
+ const cohort = path3.join(directory, "cohort.json");
805
+ const replay = path3.join(directory, "replay");
1257
806
  await writeFile(cohort, JSON.stringify(options.accountIds), { mode: 384 });
1258
807
  await runExperimentScript("generate.mjs", [
1259
808
  "--phase=plg-experiment-today",
@@ -1262,6 +811,7 @@ async function prepareExperimentReplay(options) {
1262
811
  `--experiment-type=${options.experimentType}`,
1263
812
  `--sample-id=${options.sampleId}`,
1264
813
  `--item-id=${options.itemId}`,
814
+ `--currency=${options.currency}`,
1265
815
  `--cohort-file=${cohort}`,
1266
816
  `--experiment-id=${options.experimentId}`,
1267
817
  `--control-id=${options.controlId}`,
@@ -1271,16 +821,16 @@ async function prepareExperimentReplay(options) {
1271
821
  `--timezone=${timezone}`,
1272
822
  `--output-dir=${replay}`
1273
823
  ]);
1274
- const receipt = JSON.parse(await readFile(path4.join(replay, "plg-experiment-receipt.json"), "utf8"));
1275
- const mapping = JSON.parse(await readFile(path4.join(replay, "replay.mapping.json"), "utf8"));
824
+ const receipt = JSON.parse(await readFile(path3.join(replay, "plg-experiment-receipt.json"), "utf8"));
825
+ const mapping = JSON.parse(await readFile(path3.join(replay, "replay.mapping.json"), "utf8"));
1276
826
  const { convertLocalData } = await import("./conversion-4FR3RA45.js");
1277
827
  const converted = await convertLocalData({
1278
- inputFile: path4.join(replay, "replay.jsonl"),
828
+ inputFile: path3.join(replay, "replay.jsonl"),
1279
829
  mapping,
1280
- outputDir: path4.join(directory, "converted"),
830
+ outputDir: path3.join(directory, "converted"),
1281
831
  now: new Date(options.now())
1282
832
  });
1283
- const rows = (await readFile(path4.join(converted.output_dir, converted.manifest.output.valid_file), "utf8")).trim().split("\n");
833
+ const rows = (await readFile(path3.join(converted.output_dir, converted.manifest.output.valid_file), "utf8")).trim().split("\n");
1284
834
  const count = receipt.event_uuids.exposure.length + receipt.event_uuids.outcomes.length;
1285
835
  if (converted.status !== "ready" || count === 0 || converted.manifest.output.invalid_records !== 0 || rows.length !== count || converted.manifest.output.valid_records !== count) {
1286
836
  throw new Error("The complete Demo replay did not pass data conversion.");
@@ -1291,59 +841,6 @@ async function prepareExperimentReplay(options) {
1291
841
  }
1292
842
  }
1293
843
 
1294
- // src/core/onboarding/experiment-report-wait.ts
1295
- function replayReportDates(receipt) {
1296
- const zone = /^([+-])(\d{2}):(\d{2})$/.exec(receipt.timezone);
1297
- if (!zone || Number(zone[2]) > 14 || Number(zone[3]) > 59 || Number(zone[2]) === 14 && Number(zone[3]) !== 0) throw new Error("The replay reporting timezone is invalid.");
1298
- const offset = (Number(zone[2]) * 60 + Number(zone[3])) * 6e4 * (zone[1] === "-" ? -1 : 1);
1299
- const start = Date.parse(receipt.start);
1300
- const end = Date.parse(receipt.end);
1301
- if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) throw new Error("The replay interval is invalid.");
1302
- return {
1303
- start_time: new Date(start + offset).toISOString().slice(0, 10),
1304
- end_time: new Date(end + offset).toISOString().slice(0, 10)
1305
- };
1306
- }
1307
- function isReportPending(error, projectId) {
1308
- if (!(error instanceof CapabilityGatewayError) || error.type === "validation" || error.httpStatus === 401 || error.httpStatus === 403) return false;
1309
- const view = `hive.hermes.v_atlas_experiment_exposure_${projectId}`.replaceAll(".", "\\.");
1310
- return new RegExp("\\bTable\\s+['\"`]?" + view + "['\"`]?\\s+does not exist\\b", "i").test(error.message) || /^(atlas\.service\.error\.report\.data_unavailable|Report data is temporarily unavailable\.|报告数据暂不可用|レポートデータを一時的に利用できません|리포트 데이터를 일시적으로 사용할 수 없습니다)/.test(error.message);
1311
- }
1312
- async function waitForExperimentSampleSize(query, input, budgetMs = 25e3, delayMs = 5e3) {
1313
- const deadline = Date.now() + budgetMs;
1314
- let attempts = 0;
1315
- do {
1316
- attempts++;
1317
- try {
1318
- const response = await query(
1319
- { ...input, force_refresh: true },
1320
- AbortSignal.timeout(Math.max(1, Math.min(NETWORK_BUDGET_MS, deadline - Date.now())))
1321
- );
1322
- if (!response || typeof response.report !== "object" || response.report === null) {
1323
- throw new Error("The sample-size query returned no report.");
1324
- }
1325
- if (response.report.has_data !== false) {
1326
- return { phase: "complete", next_action: "verify_experiment_results", report_dates: {
1327
- start_time: input.start_time,
1328
- end_time: input.end_time
1329
- }, sample_size_report: response.report, report_query_attempts: attempts };
1330
- }
1331
- } catch (error) {
1332
- if (!isReportPending(error, input.project_id) && !(error instanceof DOMException && ["TimeoutError", "AbortError"].includes(error.name))) throw error;
1333
- }
1334
- const remaining = deadline - Date.now();
1335
- if (remaining <= 0) break;
1336
- await new Promise((resolve) => setTimeout(resolve, Math.min(delayMs, remaining)));
1337
- } while (Date.now() < deadline);
1338
- return {
1339
- phase: "pending",
1340
- next_action: "wait_experiment_report",
1341
- poll_after_ms: delayMs,
1342
- report_dates: { start_time: input.start_time, end_time: input.end_time },
1343
- report_query_attempts: attempts
1344
- };
1345
- }
1346
-
1347
844
  // src/core/onboarding/experiment-launch.ts
1348
845
  function isApprovalBlocker(error) {
1349
846
  return error instanceof SecureStoreAuthError || error instanceof PermissionError || error instanceof CapabilityGatewayError && (error.httpStatus === 401 || error.httpStatus === 403 || error.type === "validation");
@@ -1362,11 +859,13 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1362
859
  const execute = async (session) => {
1363
860
  const plan = store.read(`experiment-plan-${runId}.json`);
1364
861
  const scope = session.ready_demo;
1365
- if (!plan || plan.phase !== "ready" || plan.run_id !== runId || plan.session_id !== sessionId || !session.host || plan.host !== session.host || session.choice !== "demo" || plan.sample_id !== session.sample_id || !scope || scope.sample_id !== plan.sample_id || scope.item_id !== plan.item_id || scope.project_id !== plan.demo_project_id || !Number.isSafeInteger(scope.project_id) || scope.project_id <= 0 || scope.project_id === session.project_id) {
862
+ if (!plan || plan.phase !== "ready" || plan.run_id !== runId || plan.session_id !== sessionId || !session.host || plan.host !== session.host || session.choice !== "demo" || plan.sample_id !== session.sample_id || plan.credential_key && plan.credential_key !== session.credential_key || !scope || scope.sample_id !== plan.sample_id || scope.item_id !== plan.item_id || scope.project_id !== plan.demo_project_id || !Number.isSafeInteger(scope.project_id) || scope.project_id <= 0 || scope.project_id === session.project_id) {
1366
863
  throw new Error("The saved experiment plan does not match the active Demo session and sample.");
1367
864
  }
1368
865
  const host = trustedProductHost(session.host);
1369
866
  const project = { project_id: scope.project_id };
867
+ const currency = plan.plan?.currency ?? "CNY";
868
+ if (currency !== "CNY" && currency !== "USD") throw new Error("The saved Demo plan has an unsupported currency.");
1370
869
  const checkoutCohort = plan.experiment_type === CHECKOUT_RECOVERY ? plan.checkout_cohort : void 0;
1371
870
  if (plan.experiment_type === CHECKOUT_RECOVERY && (!checkoutCohort || plan.credential_key !== session.credential_key || !Array.isArray(checkoutCohort.account_ids) || checkoutCohort.account_ids.length < 2)) {
1372
871
  throw new Error("The checkout recovery plan no longer matches the verified Demo scope.");
@@ -1378,10 +877,12 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1378
877
  demo_project_id: scope.project_id,
1379
878
  sample_id: scope.sample_id,
1380
879
  item_id: scope.item_id,
880
+ currency,
1381
881
  ...checkoutCohort ? { experiment_type: plan.experiment_type } : {}
1382
882
  };
1383
883
  if (preview) return { ...summary, dry_run: true, steps: [
1384
884
  ...checkoutCohort ? ["check_other_demo_experiment", "verify_demo_scope"] : [],
885
+ ...plan.approver?.status === "deferred" ? ["prepare_signed_in_approver"] : [],
1385
886
  "save_metrics_and_feature",
1386
887
  "save_draft",
1387
888
  "check_readiness",
@@ -1397,7 +898,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1397
898
  throw new Error("Resume onboarding with the signed-in account that generated the Demo plan.");
1398
899
  }
1399
900
  };
1400
- const request2 = async (id, params, waitSignal) => {
901
+ const request = async (id, params, waitSignal) => {
1401
902
  checkAccount();
1402
903
  const signal = waitSignal ?? AbortSignal.timeout(NETWORK_BUDGET_MS);
1403
904
  const response = await deps.capability(host, id, params, signal);
@@ -1405,6 +906,19 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1405
906
  return response;
1406
907
  };
1407
908
  checkAccount();
909
+ let progressRun;
910
+ const checkpoint = async (experimentId, receipt) => {
911
+ if (!progressRun) return;
912
+ checkAccount();
913
+ const result2 = await writeProgress(deps, host, "checkpoint", {
914
+ ...progressRun,
915
+ experiment_id: experimentId,
916
+ ...receipt ? { receipt } : {}
917
+ });
918
+ if (result2.state !== "in_progress" || result2.experiment_id !== experimentId) {
919
+ throw new Error("The Demo experiment checkpoint could not be saved. Resume the same run.");
920
+ }
921
+ };
1408
922
  const stateFile = `experiment-launch-${runId}.json`;
1409
923
  const progress = store.read(stateFile) ?? { timings_ms: {} };
1410
924
  const persist = () => store.write(stateFile, progress);
@@ -1415,7 +929,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1415
929
  ...progress.experiment_id && (progress.experiment_status === "running" || progress.replay) ? {
1416
930
  experiment_url: onboardingExperimentUrl(scope.project_id, progress.experiment_id, deps.webConversation ? void 0 : host)
1417
931
  } : {},
1418
- replay_receipt_path: progress.replay ? path5.resolve(store.directory, `experiment-replay-${runId}.json`) : void 0
932
+ replay_receipt_path: progress.replay ? path4.resolve(store.directory, `experiment-replay-${runId}.json`) : void 0
1419
933
  });
1420
934
  const completed = () => ({
1421
935
  ...result("complete"),
@@ -1430,12 +944,12 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1430
944
  if (!input.wait_report) return accepted;
1431
945
  try {
1432
946
  const receipt = store.read(`experiment-replay-${runId}.json`);
1433
- if (!receipt || receipt.run_id !== runId || receipt.experiment_id !== progress.experiment_id || receipt.sample_id !== scope.sample_id || receipt.item_id !== scope.item_id) {
947
+ if (!receipt || receipt.run_id !== runId || receipt.experiment_id !== progress.experiment_id || receipt.sample_id !== scope.sample_id || receipt.item_id !== scope.item_id || (receipt.currency ?? "CNY") !== currency) {
1434
948
  throw new Error("The replay receipt does not match this Demo experiment.");
1435
949
  }
1436
950
  const dates = replayReportDates(receipt);
1437
951
  const report = await waitForExperimentSampleSize(
1438
- (params, signal) => request2("experiment.report.sample-size", params, signal),
952
+ (params, signal) => request("experiment.report.sample-size", params, signal),
1439
953
  { project_id: scope.project_id, exp_id: progress.experiment_id, ...dates }
1440
954
  );
1441
955
  return { ...accepted, ...report };
@@ -1455,7 +969,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1455
969
  if (progress.replay?.status === "receiver_accepted") return finishReplay();
1456
970
  if (progress.replay) return { ...result("action_required"), next_action: "reconcile_replay_delivery" };
1457
971
  let stage = "prepare_requests";
1458
- const call = (id, params = {}) => request2(id, { ...project, ...params });
972
+ const call = (id, params = {}) => request(id, { ...project, ...params });
1459
973
  const measure = async (name, action) => {
1460
974
  const start = deps.now();
1461
975
  try {
@@ -1486,7 +1000,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1486
1000
  if (!checkoutCohort && error instanceof CapabilityGatewayError && error.code === "CAPABILITY_NOT_FOUND") return { items: [] };
1487
1001
  throw error;
1488
1002
  }),
1489
- checkoutCohort && !progress.experiment_status ? request2(DEMO_STATUS, { sample_id: scope.sample_id }) : void 0
1003
+ checkoutCohort && !progress.experiment_status ? request(DEMO_STATUS, { sample_id: scope.sample_id }) : void 0
1490
1004
  ]);
1491
1005
  if (!progress.experiment_status && !Array.isArray(otherExperiments?.items)) {
1492
1006
  throw new Error("AE did not return the Demo experiment list.");
@@ -1511,6 +1025,43 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1511
1025
  };
1512
1026
  }
1513
1027
  }
1028
+ stage = "claim_onboarding_run";
1029
+ if (session.journey_id) {
1030
+ const current = await readProgress(deps, host);
1031
+ if (current.state !== "completed" && current.state !== "disabled") {
1032
+ checkAccount();
1033
+ const run = {
1034
+ journey_id: session.journey_id,
1035
+ run_id: runId,
1036
+ launch_session_id: session.id,
1037
+ demo_project_id: scope.project_id
1038
+ };
1039
+ const claim = await writeProgress(deps, host, "claim", run);
1040
+ if (claim.state !== "disabled" && !claim.claim_granted) {
1041
+ return {
1042
+ ...summary,
1043
+ phase: "action_required",
1044
+ next_action: "resume_onboarding_progress",
1045
+ existing_run_id: claim.run_id,
1046
+ experiment_id: claim.experiment_id
1047
+ };
1048
+ }
1049
+ if (claim.claim_granted) progressRun = run;
1050
+ }
1051
+ }
1052
+ if (plan.approver?.status === "deferred" && !progress.approver_prepared) {
1053
+ stage = "prepare_approver";
1054
+ checkAccount();
1055
+ const prepared = await prepareDemoApprover(deps, host, key, scope.project_id);
1056
+ if (prepared.status !== "ready") return {
1057
+ ...result("action_required"),
1058
+ failed_stage: stage,
1059
+ next_action: "resume_experiment_launch",
1060
+ error: { message: prepared.message, code: prepared.code }
1061
+ };
1062
+ progress.approver_prepared = true;
1063
+ persist();
1064
+ }
1514
1065
  stage = "prepare_requests";
1515
1066
  const requestsFile = `experiment-requests-${runId}.json`;
1516
1067
  let requests = store.read(requestsFile);
@@ -1522,9 +1073,10 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1522
1073
  sampleId: plan.sample_id,
1523
1074
  itemId: plan.item_id,
1524
1075
  runId,
1076
+ currency,
1525
1077
  ...checkoutCohort ? { accountIds: checkoutCohort.account_ids } : {}
1526
1078
  });
1527
- const generated = JSON.parse(await runExperimentScript("experiment-requests.mjs", [path5.join(store.directory, inputFile)]));
1079
+ const generated = JSON.parse(await runExperimentScript("experiment-requests.mjs", [path4.join(store.directory, inputFile)]));
1528
1080
  store.write(requestsFile, generated);
1529
1081
  requests = generated;
1530
1082
  }
@@ -1574,6 +1126,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1574
1126
  progress.experiment_id = draft.result;
1575
1127
  });
1576
1128
  const exp = { exp_id: progress.experiment_id };
1129
+ await checkpoint(exp.exp_id);
1577
1130
  const approval = async () => (await call("experiment.approval.get", exp)).item;
1578
1131
  const verifyRound = (round) => {
1579
1132
  if (!Number.isSafeInteger(round?.approval_id) || round.approval_id <= 0 || progress.approval_id && round.approval_id !== progress.approval_id || round.configuration?.exp_id !== exp.exp_id || round.configuration.exp_name !== preset.experiment.expName || !round.configuration.feature_key_list?.includes(preset.feature.featureKey)) {
@@ -1682,6 +1235,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1682
1235
  experimentType: plan.experiment_type,
1683
1236
  sampleId: plan.sample_id,
1684
1237
  itemId: plan.item_id,
1238
+ currency,
1685
1239
  experimentId: exp.exp_id,
1686
1240
  controlId,
1687
1241
  treatmentId,
@@ -1690,10 +1244,24 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1690
1244
  zoneOffset,
1691
1245
  appid: info.appid.trim(),
1692
1246
  receiver: info.public_receiver_address,
1693
- now: deps.now
1247
+ now: deps.now,
1248
+ savedTiming: progressRun ? store.read(`experiment-replay-${runId}.json`) : void 0
1694
1249
  });
1695
1250
  checkAccount();
1696
1251
  store.write(`experiment-replay-${runId}.json`, replay.receipt);
1252
+ if (progressRun) {
1253
+ const { sample_id, item_id, currency: currency2, start, end, timezone, arms } = replay.receipt;
1254
+ const publicArm = ({ group_id, exposed_account_ids, coupon_claim_account_ids, paid_account_ids }) => ({ group_id, exposed_account_ids, coupon_claim_account_ids, paid_account_ids });
1255
+ await checkpoint(exp.exp_id, {
1256
+ sample_id,
1257
+ item_id,
1258
+ currency: currency2,
1259
+ start,
1260
+ end,
1261
+ timezone,
1262
+ arms: { control: publicArm(arms.control), treatment: publicArm(arms.treatment) }
1263
+ });
1264
+ }
1697
1265
  progress.replay = { status: "unknown", record_count: replay.count };
1698
1266
  persist();
1699
1267
  try {
@@ -1725,7 +1293,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1725
1293
 
1726
1294
  // src/core/onboarding/workspace-projects.ts
1727
1295
  import fs2 from "fs";
1728
- import path6 from "path";
1296
+ import path5 from "path";
1729
1297
  var ignored = /* @__PURE__ */ new Set(["node_modules", "vendor", "dist", "build", "Library", "Packages", "Temp", "obj", "Assets"]);
1730
1298
  function identifyWorkspaceProjects(root = process.cwd()) {
1731
1299
  const projects = [];
@@ -1740,11 +1308,11 @@ function identifyWorkspaceProjects(root = process.cwd()) {
1740
1308
  continue;
1741
1309
  }
1742
1310
  const files = new Set(entries.filter((entry) => entry.isFile()).map((entry) => entry.name));
1743
- const relative = path6.relative(root, directory) || ".";
1311
+ const relative = path5.relative(root, directory) || ".";
1744
1312
  if (entries.some((entry) => entry.name === "Assets" && entry.isDirectory()) && entries.some((entry) => entry.name === "ProjectSettings" && entry.isDirectory())) {
1745
1313
  projects.push({ directory: relative, platform: "unity", evidence: "Assets/, ProjectSettings/" });
1746
1314
  }
1747
- const packageManifest = files.has("package.json") ? readManifest(path6.join(directory, "package.json")) : void 0;
1315
+ const packageManifest = files.has("package.json") ? readManifest(path5.join(directory, "package.json")) : void 0;
1748
1316
  const dependencies = { ...packageManifest?.dependencies, ...packageManifest?.devDependencies };
1749
1317
  const hasBrowser = files.has("index.html") || Object.keys(dependencies).some((name) => ["vite", "next", "react-dom", "vue", "@angular/core", "phaser", "pixi.js"].includes(name));
1750
1318
  const hasServer = Object.keys(dependencies).some((name) => ["express", "fastify", "@nestjs/core", "koa", "@hapi/hapi", "socket.io"].includes(name)) || ["server.js", "server.mjs", "server.ts"].some((file) => files.has(file));
@@ -1753,7 +1321,7 @@ function identifyWorkspaceProjects(root = process.cwd()) {
1753
1321
  if (depth < 4) {
1754
1322
  for (const entry of entries) {
1755
1323
  if (entry.isDirectory() && !entry.name.startsWith(".") && !ignored.has(entry.name)) {
1756
- pending.push({ directory: path6.join(directory, entry.name), depth: depth + 1 });
1324
+ pending.push({ directory: path5.join(directory, entry.name), depth: depth + 1 });
1757
1325
  }
1758
1326
  }
1759
1327
  }
@@ -1832,6 +1400,8 @@ function clearAccountScope(session) {
1832
1400
  delete session.choice;
1833
1401
  delete session.sample_id;
1834
1402
  delete session.ready_demo;
1403
+ delete session.journey_id;
1404
+ delete session.demo_visits;
1835
1405
  delete session.confirmed_business_project_id;
1836
1406
  }
1837
1407
  var defaults = {
@@ -1844,9 +1414,10 @@ var defaults = {
1844
1414
  },
1845
1415
  credentialKey(host) {
1846
1416
  const token = readExternalCliToken(host)?.token ?? (process.env.TE_AGENT_CLI_CONFIG_DIR !== void 0 ? peekCliToken(host) : loadCliToken(host));
1847
- return token ? crypto3.createHash("sha256").update(token).digest("hex") : void 0;
1417
+ return token ? crypto2.createHash("sha256").update(token).digest("hex") : void 0;
1848
1418
  },
1849
1419
  machineLoginAllowed: (host) => !readExternalCliToken(host),
1420
+ demoCurrency: onboardingDemoCurrency,
1850
1421
  createBootstrap,
1851
1422
  readBootstrap,
1852
1423
  claimBootstrapDevice,
@@ -1854,7 +1425,7 @@ var defaults = {
1854
1425
  authorize: authorizeLoginDevice,
1855
1426
  poll: (issuer, code, signal) => pollDeviceToken(issuer, code, code.startsWith("uba_") ? "uba" : "legacy", signal),
1856
1427
  async persist(host, tokens, signal) {
1857
- const { persistDeviceTokens, activateHostAfterLogin } = await import("./auth-BD3NIY3T.js");
1428
+ const { persistDeviceTokens, activateHostAfterLogin } = await import("./auth-SDK5OAGP.js");
1858
1429
  await persistDeviceTokens(host, tokens, { signal, checkCompatibility: false });
1859
1430
  activateHostAfterLogin(host, host);
1860
1431
  },
@@ -1883,6 +1454,23 @@ var OnboardingRuntime = class {
1883
1454
  store;
1884
1455
  dependencies;
1885
1456
  async invoke(action, input) {
1457
+ if (action === "progress" || action === "progress-preview") {
1458
+ const active = input.host ?? this.dependencies.activeHost();
1459
+ const host2 = active ? trustedProductHost(active) : void 0;
1460
+ if (action === "progress-preview") return { dry_run: true, action: input.run_id ? "complete" : "status", host: host2 };
1461
+ if (!host2 || !this.dependencies.webConversation && !isOnboardingProgressHost(host2) || !this.dependencies.authenticated(host2)) return { state: "disabled" };
1462
+ if (!input.run_id) {
1463
+ const { receipt: _receipt2, ...progress2 } = await readProgress(this.dependencies, host2);
1464
+ return progress2;
1465
+ }
1466
+ if (!/^[0-9a-f]{32}$/.test(input.run_id)) throw new Error("Pass the run ID returned by experiment-plan.");
1467
+ const { receipt: _receipt, ...progress } = await verifyAndCompleteProgress(this.dependencies, host2, input.run_id);
1468
+ return progress;
1469
+ }
1470
+ if ((action === "status" || action === "plan") && input.run_id) {
1471
+ const draft = readOnboardingExperimentPlan(this.store, this.dependencies, input);
1472
+ return action === "plan" ? { ...draft, dry_run: true } : draft;
1473
+ }
1886
1474
  if (action === "growth" || action === "growth-plan") {
1887
1475
  return runOnboardingGrowth(this.store, this.dependencies, input, action === "growth-plan");
1888
1476
  }
@@ -1899,34 +1487,47 @@ var OnboardingRuntime = class {
1899
1487
  if (input.choice === "business" && input.sample) throw new Error("A sample requires the demo choice.");
1900
1488
  if (input.language && !normalizeRegistrationLanguage(input.language)) throw new Error("Unsupported onboarding language. Use zh-CN, en-US, ja-JP, or ko-KR.");
1901
1489
  if (input.source && !["codex", "claude-code", "cursor", "other"].includes(input.source)) throw new Error("Unsupported local AI tool source.");
1902
- const selectedWebsiteEnv = websiteEnvironment(input.website_env, webConversation ? {} : process.env);
1903
1490
  const explicitHost = input.host ? trustedProductHost(input.host) : void 0;
1904
- let session = this.store.session(input.session_id, explicitHost);
1905
- let host = explicitHost ?? session?.host;
1491
+ const pinnedSession = input.session_id ? this.store.session(input.session_id, explicitHost) : void 0;
1492
+ const websiteEnvOverride = input.website_env ?? (webConversation ? void 0 : process.env.AE_CLI_WEBSITE_ENV);
1493
+ const selectedWebsiteEnv = websiteEnvironment(websiteEnvOverride ?? pinnedSession?.website_env, {});
1494
+ const testHost = selectedWebsiteEnv === "test" ? `https://${OVERSEAS_TEST_PRODUCT_HOSTNAME}` : void 0;
1495
+ if (testHost && explicitHost && explicitHost !== testHost) throw new Error("Use the overseas test product host for test website onboarding.");
1496
+ let session = pinnedSession ?? this.store.session(void 0, explicitHost ?? testHost);
1497
+ let host = explicitHost ?? session?.host ?? testHost;
1906
1498
  if (!host) {
1907
1499
  const active = this.dependencies.activeHost();
1908
1500
  const activeCandidate = active ? trustedProductHost(active) : void 0;
1909
1501
  host = activeCandidate && (action === "plan" || this.dependencies.authenticated(activeCandidate)) ? activeCandidate : void 0;
1910
1502
  }
1911
1503
  if (!session) session = this.store.session(void 0, host);
1912
- if (session?.website_env === "test" || session?.bootstrap && !isProductionWebsiteOrigin(session.bootstrap.origin)) {
1913
- if (input.session_id || session.host || session.project_id || session.device || session.credential_key) {
1914
- throw new Error("This onboarding session is bound to a previous website environment. To use an existing account, sign in with ae-cli auth login --host <url>.");
1504
+ if (session) {
1505
+ const origin = session.bootstrap?.origin;
1506
+ const matchesOrigin = !origin || (testHost ? origin === OVERSEAS_TEST_WEBSITE_ORIGIN : isProductionWebsiteOrigin(origin));
1507
+ if ((session.website_env ?? "production") !== selectedWebsiteEnv || testHost && session.host !== testHost || !matchesOrigin) {
1508
+ if (pinnedSession) throw new Error("This onboarding session is bound to a previous website environment. Start a separate continuation.");
1509
+ session = void 0;
1915
1510
  }
1916
- session = void 0;
1917
1511
  }
1918
1512
  const source = cliEntrySource(input.source ?? session?.source);
1919
- const language = registrationLanguage(input.language ?? session?.language);
1920
- const defaultMarket = registrationMarket(language);
1513
+ const inspectLocalLanguage = !webConversation && !testHost && (action === "plan" || action === "run" && !host && !session);
1514
+ const localLanguage = inspectLocalLanguage ? localRegistrationLanguage() : void 0;
1515
+ const language = registrationLanguage(input.language ?? session?.language ?? localLanguage);
1516
+ const markets = testHost ? OVERSEAS_TEST_MARKETS : WEBSITE_MARKETS;
1517
+ const languageMarket = registrationMarket(language);
1518
+ const defaultMarket = testHost && languageMarket === "cn" ? "us" : languageMarket;
1519
+ const useDefaultMarket = testHost !== void 0 || !host;
1921
1520
  const registrationOrigin = webConversation ? null : websiteOrigin(input.region ?? session?.region ?? defaultMarket, selectedWebsiteEnv);
1922
1521
  if (action === "plan") return {
1923
1522
  dry_run: true,
1924
1523
  host: host ?? null,
1925
- market: input.region ?? session?.region ?? (!host ? defaultMarket : null),
1524
+ market: input.region ?? session?.region ?? (useDefaultMarket ? defaultMarket : null),
1926
1525
  language,
1927
1526
  default_market: defaultMarket,
1928
- markets: WEBSITE_MARKETS,
1929
- selection_source: input.region ? "explicit" : session?.region_source ?? (session?.region ? "saved" : !host ? "language_default" : "existing_host"),
1527
+ ...localLanguage ? { local_language: localLanguage } : {},
1528
+ device_market: testHost ? "us" : onboardingDeviceMarket(webConversation ? registrationLanguage() : localLanguage),
1529
+ markets,
1530
+ selection_source: input.region ? "explicit" : session?.region_source ?? (session?.region ? "saved" : useDefaultMarket ? "language_default" : "existing_host"),
1930
1531
  website_env: selectedWebsiteEnv,
1931
1532
  website_origin: registrationOrigin,
1932
1533
  actions: webConversation ? ["read_project_state", "choose_demo", "prepare_demo"] : ["resolve_trusted_host", "resolve_account_host", "authorize_cli", "read_project_state", "choose_demo_or_business", "prepare_demo_or_connect_sdk"],
@@ -1937,15 +1538,16 @@ var OnboardingRuntime = class {
1937
1538
  if (!session && action === "status" && (!host || !this.dependencies.authenticated(host))) return { host: host ?? null, project_id: null, phase: "not_started", next_action: "run_onboarding", poll_after_ms: 0 };
1938
1539
  const newSession = (market) => ({
1939
1540
  schema_version: 1,
1940
- id: crypto3.randomUUID(),
1541
+ id: crypto2.randomUUID(),
1941
1542
  host,
1942
1543
  browser: browserMode,
1943
1544
  source,
1944
- region: market ?? (!host ? defaultMarket : void 0),
1545
+ region: market ?? (useDefaultMarket ? defaultMarket : void 0),
1945
1546
  language,
1946
1547
  language_source: input.language ? "explicit" : "system",
1947
1548
  website_env: selectedWebsiteEnv,
1948
- region_source: market ? "explicit" : !host ? "language_default" : void 0,
1549
+ region_source: market ? "explicit" : useDefaultMarket ? "language_default" : void 0,
1550
+ ...testHost ? { requires_auth: true } : {},
1949
1551
  updated_at: new Date(this.dependencies.now()).toISOString()
1950
1552
  });
1951
1553
  if (!session) session = newSession(input.region);
@@ -1956,7 +1558,7 @@ var OnboardingRuntime = class {
1956
1558
  if (credentialKey) session.credential_key = credentialKey;
1957
1559
  session.host ??= host;
1958
1560
  if (!session.region) {
1959
- session.region = input.region ?? (!session.host && action === "run" ? defaultMarket : void 0);
1561
+ session.region = input.region ?? (useDefaultMarket && action === "run" ? defaultMarket : void 0);
1960
1562
  if (session.region) session.region_source = input.region ? "explicit" : "language_default";
1961
1563
  }
1962
1564
  session.language = language;
@@ -1996,10 +1598,10 @@ var OnboardingRuntime = class {
1996
1598
  market: current.region ?? null,
1997
1599
  default_market: defaultMarket,
1998
1600
  website_env: current.website_env,
1999
- markets: WEBSITE_MARKETS,
1601
+ markets,
2000
1602
  selection_source: current.region_source ?? (current.region ? "saved" : "existing_host"),
2001
1603
  ...extra,
2002
- skill_path: path7.join(getLocalCliPackageInfo().root, "skills", "ae-onboarding", "SKILL.md"),
1604
+ skill_path: path6.join(getLocalCliPackageInfo().root, "skills", "ae-onboarding", "SKILL.md"),
2003
1605
  ...interaction ? { interaction } : {},
2004
1606
  ...target ? { browser: opening?.receipt ?? extra.browser ?? onboardingBrowserPolicy({ target: target.name, new_page: false }) } : {},
2005
1607
  session_id: current.id,
@@ -2022,7 +1624,7 @@ var OnboardingRuntime = class {
2022
1624
  const execute = async () => {
2023
1625
  const marketChanged = input.region && current.region && input.region !== current.region;
2024
1626
  if (marketChanged) {
2025
- if (action !== "run" || input.session_id || current.host || current.project_id || current.credential_key || current.device) {
1627
+ if (action !== "run" || input.session_id || current.host && !(testHost && current.requires_auth) || current.project_id || current.credential_key || current.device) {
2026
1628
  throw new Error("The continuation is bound to another market. Keep the existing account environment and resume its original continuation.");
2027
1629
  }
2028
1630
  if (current.bootstrap) {
@@ -2064,6 +1666,25 @@ var OnboardingRuntime = class {
2064
1666
  this.store.save(current);
2065
1667
  }
2066
1668
  const compatibility = action === "run" ? await network((signal) => this.dependencies.compatibility(current.host, signal)) : void 0;
1669
+ const versioned = webConversation || isOnboardingProgressHost(current.host);
1670
+ let progress = versioned && action === "run" ? await readProgress(this.dependencies, current.host) : void 0;
1671
+ if (progress?.state === "not_started" && input.choice === "demo" && !loginChangedCredential) {
1672
+ progress = await writeProgress(this.dependencies, current.host, "start", { version: progress.version });
1673
+ }
1674
+ if (progress?.state === "in_progress" && progress.journey_id !== current.journey_id) {
1675
+ current = {
1676
+ ...current,
1677
+ id: crypto2.randomUUID(),
1678
+ journey_id: progress.journey_id,
1679
+ choice: void 0,
1680
+ sample_id: void 0,
1681
+ ready_demo: void 0,
1682
+ demo_visits: void 0
1683
+ };
1684
+ this.store.save(current);
1685
+ } else if (progress?.state === "not_started" && !input.choice && (current.choice || current.journey_id)) {
1686
+ current = { ...current, id: crypto2.randomUUID(), journey_id: void 0, choice: void 0, sample_id: void 0, ready_demo: void 0, demo_visits: void 0 };
1687
+ }
2067
1688
  const context = await network((signal) => this.dependencies.capability(current.host, DEMO_CONTEXT, {}, signal));
2068
1689
  const projectId = context?.business_project?.project_id;
2069
1690
  const availableProject = Number.isSafeInteger(projectId) && projectId > 0;
@@ -2084,7 +1705,21 @@ var OnboardingRuntime = class {
2084
1705
  if (current.choice !== "demo" || current.ready_demo?.sample_id !== current.sample_id || current.ready_demo?.project_id === projectId) delete current.ready_demo;
2085
1706
  this.store.save(current);
2086
1707
  }
2087
- const account = { ...completedLogin, business_project: availableProject ? context.business_project : null, compatibility };
1708
+ const account = {
1709
+ ...completedLogin,
1710
+ ...progress ? { onboarding_progress: {
1711
+ state: progress.state,
1712
+ run_id: progress.run_id,
1713
+ experiment_id: progress.experiment_id,
1714
+ demo_project_id: progress.demo_project_id
1715
+ } } : {},
1716
+ business_project: availableProject ? context.business_project : null,
1717
+ compatibility,
1718
+ ...!webConversation ? { business_data: {
1719
+ interaction: onboardingInteraction("choose_data_source"),
1720
+ tools: onboardingInteraction("choose_data_tool")
1721
+ } } : {}
1722
+ };
2088
1723
  if (current.choice === "demo" && current.sample_id) {
2089
1724
  const prepareDemo = () => network((signal) => this.dependencies.capability(
2090
1725
  current.host,
@@ -2103,15 +1738,42 @@ var OnboardingRuntime = class {
2103
1738
  }
2104
1739
  if (action === "run") {
2105
1740
  const scope = readyDemoScope(demo, current);
2106
- if (scope) current.ready_demo = scope;
2107
- else delete current.ready_demo;
1741
+ if (scope) {
1742
+ const sample2 = DEMO_SAMPLE_IDS.find((id) => id === scope.sample_id);
1743
+ if (sample2 && (!current.ready_demo || input.sample)) {
1744
+ current.demo_visits ??= {};
1745
+ current.demo_visits[sample2] = (current.demo_visits[sample2] ?? 0) + 1;
1746
+ }
1747
+ current.ready_demo = scope;
1748
+ } else delete current.ready_demo;
2108
1749
  this.store.save(current);
2109
1750
  }
1751
+ if (action === "run" && progress?.state === "in_progress" && current.ready_demo) {
1752
+ try {
1753
+ await writeProgress(this.dependencies, current.host, "check_demo", {
1754
+ demo_project_id: current.ready_demo.project_id
1755
+ });
1756
+ } catch (error) {
1757
+ if (error?.code !== "PLG_DEMO_LICENSE_REQUIRED") throw error;
1758
+ return summary({
1759
+ ...account,
1760
+ demo,
1761
+ demo_project_id: current.ready_demo.project_id,
1762
+ phase: "action_required",
1763
+ next_action: "check_demo_license",
1764
+ code: error.code,
1765
+ message: error.message,
1766
+ poll_after_ms: 0
1767
+ });
1768
+ }
1769
+ }
1770
+ const sample = DEMO_SAMPLE_IDS.find((id) => id === current.sample_id);
2110
1771
  return summary({
2111
1772
  ...account,
2112
1773
  demo,
2113
1774
  samples: context.samples,
2114
1775
  demo_project_id: demo?.project_id ?? null,
1776
+ ...demo?.status === "ready" && sample ? { demo_overview: onboardingDemoOverview(sample, current.demo_visits?.[sample] ?? 1) } : {},
2115
1777
  evidence: onboardingEvidenceLinks(demo?.evidence, demo?.project_id, webConversation ? void 0 : current.host),
2116
1778
  phase: demo?.status === "ready" ? "ready" : demo?.status === "action_required" ? "action_required" : "pending",
2117
1779
  next_action: demo?.status === "ready" ? "offer_growth_questions" : demo?.status === "action_required" ? "inspect_demo_preparation" : "poll_demo",
@@ -2142,7 +1804,8 @@ var OnboardingRuntime = class {
2142
1804
  phase: "waiting_user",
2143
1805
  next_action: "choose_experience",
2144
1806
  poll_after_ms: 0,
2145
- choices
1807
+ choices,
1808
+ ...!webConversation ? { demo_entry: onboardingInteraction("demo_entry") } : {}
2146
1809
  });
2147
1810
  };
2148
1811
  return action === "run" ? await this.store.locked(`session:${current.id}`, execute) : await execute();
@@ -2219,7 +1882,7 @@ var OnboardingRuntime = class {
2219
1882
  }
2220
1883
  return summary({ phase: "waiting_user", next_action: "run_onboarding", poll_after_ms: 0 });
2221
1884
  }
2222
- if (!session.region) return summary({ phase: "action_required", next_action: "choose_market", markets: WEBSITE_MARKETS, poll_after_ms: 0 });
1885
+ if (!session.region) return summary({ phase: "action_required", next_action: "choose_market", poll_after_ms: 0 });
2223
1886
  const language = session.language_source === "explicit" ? registrationLanguage(session.language) : void 0;
2224
1887
  if (!session.bootstrap || Date.parse(session.bootstrap.expires_at) <= this.dependencies.now()) {
2225
1888
  const thread = session.source === "codex" && UUID_PATTERN.test(process.env.CODEX_THREAD_ID ?? "") ? process.env.CODEX_THREAD_ID : void 0;
@@ -2321,7 +1984,7 @@ var OnboardingRuntime = class {
2321
1984
  if (grant.authorization_status === "expired") return restart("WEBSITE_AUTHORIZATION_EXPIRED");
2322
1985
  if (grant.authorization_status !== "approved" && grant.authorization_status !== "claimed") return waiting(grant.authorization_status, grant.poll_after_ms ?? ready.poll_after_ms);
2323
1986
  if (grant.host !== issuer || !grant.device_code || !grant.expected_login_name || !grant.expected_company_id || !grant.expires_at || !Number.isFinite(Date.parse(grant.expires_at)) || Date.parse(grant.expires_at) <= this.dependencies.now()) throw new Error("The website device connection does not match this continuation.");
2324
- const fingerprint = crypto3.createHash("sha256").update(grant.device_code).digest("hex");
1987
+ const fingerprint = crypto2.createHash("sha256").update(grant.device_code).digest("hex");
2325
1988
  const previous = session.website_device;
2326
1989
  if (previous && (previous.fingerprint !== fingerprint || previous.issuer !== issuer || previous.expires_at !== grant.expires_at || previous.expected_login_name !== grant.expected_login_name || previous.expected_company_id !== String(grant.expected_company_id))) {
2327
1990
  throw new Error("The website device connection changed. Start a separate connection.");
@@ -2367,10 +2030,10 @@ var GUIDE_AGENT_ID = "system-agent-onboarding-guide";
2367
2030
  var SESSION_HOST = "https://onboarding-sandbox.invalid";
2368
2031
  function webSessionDirectory(env, cwd) {
2369
2032
  const conversationId = env.TE_AGENT_CONVERSATION_ID;
2370
- if (!conversationId || !/^[\w-]+$/.test(conversationId) || path8.basename(cwd) !== conversationId) {
2033
+ if (!conversationId || !/^[\w-]+$/.test(conversationId) || path7.basename(cwd) !== conversationId) {
2371
2034
  throw new Error("Web onboarding must run in the current AE conversation directory.");
2372
2035
  }
2373
- return path8.join(cwd, ".ae-onboarding", "cli");
2036
+ return path7.join(cwd, ".ae-onboarding", "cli");
2374
2037
  }
2375
2038
  async function readTaskActor(host, token, conversationId, signal) {
2376
2039
  const legacy = token.startsWith("cli_task_");
@@ -2391,7 +2054,12 @@ async function readTaskActor(host, token, conversationId, signal) {
2391
2054
  if (legacy && (payload.return_code !== 0 || payload.data?.task_cli_compat_enabled !== true)) return void 0;
2392
2055
  const actor = legacy ? payload.data?.plg_onboarding_actor : payload.actor;
2393
2056
  if (typeof actor?.account_id === "string" && actor.account_id && typeof actor.company_id === "string" && actor.company_id && actor.conversation_id === conversationId) {
2394
- return { openId: actor.account_id, issuer: actor.company_id };
2057
+ return {
2058
+ openId: actor.account_id,
2059
+ issuer: actor.company_id,
2060
+ platformRegion: actor.platform_region === "cn" || actor.platform_region === "overseas" ? actor.platform_region : void 0,
2061
+ market: typeof actor.market === "string" && isWebsiteMarket(actor.market) ? actor.market : void 0
2062
+ };
2395
2063
  }
2396
2064
  }
2397
2065
  async function invokeOnboarding(action, input) {
@@ -2413,7 +2081,12 @@ async function invokeOnboarding(action, input) {
2413
2081
  if (external && !token.startsWith("cli_task_") && !external.taskContext) {
2414
2082
  throw new Error("Web onboarding requires the current AE task context.");
2415
2083
  }
2416
- const actor = token.startsWith("cli_task_") || external?.taskContext ? await readTaskActor(host, token, process.env.TE_AGENT_CONVERSATION_ID, signal) : { openId: (await validateCliTokenOnServer(host, token, signal)).account?.openId, issuer: host };
2084
+ const actor = token.startsWith("cli_task_") || external?.taskContext ? await readTaskActor(host, token, process.env.TE_AGENT_CONVERSATION_ID, signal) : {
2085
+ openId: (await validateCliTokenOnServer(host, token, signal)).account?.openId,
2086
+ issuer: host,
2087
+ platformRegion: void 0,
2088
+ market: void 0
2089
+ };
2417
2090
  if (!actor?.openId || external?.taskContext && actor.issuer !== external.taskContext.companyId) {
2418
2091
  throw new Error("AE could not verify the current onboarding account.");
2419
2092
  }
@@ -2425,6 +2098,7 @@ async function invokeOnboarding(action, input) {
2425
2098
  }
2426
2099
  const runtime = new OnboardingRuntime(store, {
2427
2100
  webConversation: true,
2101
+ demoCurrency: () => onboardingDemoCurrency(host),
2428
2102
  activeHost: () => SESSION_HOST,
2429
2103
  authenticated: (scope) => scope === SESSION_HOST,
2430
2104
  credentialKey: (scope) => scope === SESSION_HOST ? key : void 0,
@@ -2439,6 +2113,11 @@ async function invokeOnboarding(action, input) {
2439
2113
  });
2440
2114
  const output = await runtime.invoke(action, input);
2441
2115
  if (output.host === SESSION_HOST) output.host = null;
2116
+ if (typeof output.language === "string") {
2117
+ const languageMarket = registrationMarket(registrationLanguage(output.language));
2118
+ const overseasMarket = languageMarket === "cn" ? "us" : languageMarket;
2119
+ output.product_resource_market = actor.market ?? (actor.platformRegion === "overseas" ? overseasMarket : actor.platformRegion ?? null);
2120
+ }
2442
2121
  return output;
2443
2122
  }
2444
2123
  export {