@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,7 +1,8 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
2
  import {
3
+ CapabilityGatewayError,
3
4
  getLocalCliPackageInfo
4
- } from "./chunk-PUSFEC6B.js";
5
+ } from "./chunk-WG27BD67.js";
5
6
  import {
6
7
  internalCallSourceHeaders,
7
8
  peekCliToken
@@ -10,7 +11,8 @@ import {
10
11
  getActiveHost,
11
12
  getConfigDir,
12
13
  isAeSandboxRuntime,
13
- readSandboxCliTokenEntry
14
+ readSandboxCliTokenEntry,
15
+ safeJsonParse
14
16
  } from "./chunk-IGU3R2JD.js";
15
17
  import {
16
18
  externalCliTokenRequestOptions,
@@ -23,7 +25,7 @@ import {
23
25
 
24
26
  // src/core/compat-check.ts
25
27
  import fs10 from "fs";
26
- import path10 from "path";
28
+ import path12 from "path";
27
29
  import { createHash as createHash3 } from "crypto";
28
30
  import { Agent } from "undici";
29
31
 
@@ -314,24 +316,1050 @@ function formatCompatNotice(verdict) {
314
316
 
315
317
  // src/core/version-sync.ts
316
318
  import fs8 from "fs";
317
- import path8 from "path";
319
+ import path10 from "path";
320
+
321
+ // src/core/onboarding/contracts.ts
322
+ var DEMO_CONTEXT = "project.plg_demo.context";
323
+ var DEMO_ENSURE = "project.plg_demo.ensure";
324
+ var DEMO_STATUS = "project.plg_demo.status";
325
+ var RUN_BUDGET_MS = 45e3;
326
+ var NETWORK_BUDGET_MS = 35e3;
327
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
328
+ var DEMO_SAMPLE_IDS = ["star-island", "season-pass"];
329
+ var CHECKOUT_RECOVERY = "checkout-recovery";
330
+ var OVERSEAS_TEST_PRODUCT_HOSTNAME = "plg-test-overseas-web.thinkingai.io";
331
+ function onboardingDemoCurrency(host, region) {
332
+ const hostname = host ? new URL(host).hostname : void 0;
333
+ if (hostname === "ae-web-global.thinkingai.io" || hostname === OVERSEAS_TEST_PRODUCT_HOSTNAME) return "USD";
334
+ if (hostname?.endsWith(".thinkingai.cn") || hostname?.endsWith(".thinkingdata.cn")) return "CNY";
335
+ return region === "us" ? "USD" : "CNY";
336
+ }
337
+ function onboardingGrowthScenario(value) {
338
+ if (value === void 0 || value === "item-coupon") return "item-coupon";
339
+ if (value === CHECKOUT_RECOVERY) return CHECKOUT_RECOVERY;
340
+ throw new Error("Use --scenario item-coupon or checkout-recovery.");
341
+ }
342
+
343
+ // src/core/onboarding/experiment-report-wait.ts
344
+ function replayReportDates(receipt) {
345
+ const zone = /^([+-])(\d{2}):(\d{2})$/.exec(receipt.timezone);
346
+ 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.");
347
+ const offset = (Number(zone[2]) * 60 + Number(zone[3])) * 6e4 * (zone[1] === "-" ? -1 : 1);
348
+ const start = Date.parse(receipt.start);
349
+ const end = Date.parse(receipt.end);
350
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) throw new Error("The replay interval is invalid.");
351
+ return {
352
+ start_time: new Date(start + offset).toISOString().slice(0, 10),
353
+ end_time: new Date(end + offset).toISOString().slice(0, 10)
354
+ };
355
+ }
356
+ function isReportPending(error, projectId) {
357
+ if (!(error instanceof CapabilityGatewayError) || error.type === "validation" || error.httpStatus === 401 || error.httpStatus === 403) return false;
358
+ const view = `hive.hermes.v_atlas_experiment_exposure_${projectId}`.replaceAll(".", "\\.");
359
+ 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);
360
+ }
361
+ async function waitForExperimentSampleSize(query, input, budgetMs = 25e3, delayMs = 5e3) {
362
+ const deadline = Date.now() + budgetMs;
363
+ let attempts = 0;
364
+ do {
365
+ attempts++;
366
+ try {
367
+ const response = await query(
368
+ { ...input, force_refresh: true },
369
+ AbortSignal.timeout(Math.max(1, Math.min(NETWORK_BUDGET_MS, deadline - Date.now())))
370
+ );
371
+ if (!response || typeof response.report !== "object" || response.report === null) {
372
+ throw new Error("The sample-size query returned no report.");
373
+ }
374
+ if (response.report.has_data !== false) {
375
+ return { phase: "complete", next_action: "verify_experiment_results", report_dates: {
376
+ start_time: input.start_time,
377
+ end_time: input.end_time
378
+ }, sample_size_report: response.report, report_query_attempts: attempts };
379
+ }
380
+ } catch (error) {
381
+ if (!isReportPending(error, input.project_id) && !(error instanceof DOMException && ["TimeoutError", "AbortError"].includes(error.name))) throw error;
382
+ }
383
+ const remaining = deadline - Date.now();
384
+ if (remaining <= 0) break;
385
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delayMs, remaining)));
386
+ } while (Date.now() < deadline);
387
+ return {
388
+ phase: "pending",
389
+ next_action: "wait_experiment_report",
390
+ poll_after_ms: delayMs,
391
+ report_dates: { start_time: input.start_time, end_time: input.end_time },
392
+ report_query_attempts: attempts
393
+ };
394
+ }
395
+
396
+ // src/core/onboarding/growth.ts
397
+ import crypto from "crypto";
398
+ import path2 from "path";
399
+
400
+ // src/core/website-entry.ts
401
+ var LOGIN_PATHS = { jp: "/jp/experience-login/", kr: "/kr/experience-login/", us: "/en/experience-login/", cn: "/experience-login/" };
402
+ var WEBSITE_MARKETS = Object.keys(LOGIN_PATHS);
403
+ var OVERSEAS_TEST_MARKETS = WEBSITE_MARKETS.filter((market) => market !== "cn");
404
+ var OVERSEAS_TEST_WEBSITE_ORIGIN = "https://test.thinkingai.io";
405
+ var PRODUCTION_ISSUER = "https://thinkingai.io";
406
+ var PRODUCTION_BROWSER_ORIGIN = "https://www.thinkingai.io";
407
+ var CHINA_PRODUCTION_ORIGIN = "https://www.thinkingai.cn";
408
+ var UNSUPPORTED_MARKET = "Website onboarding is available in China, Japan, South Korea, and the United States. Use --region cn, jp, kr, or us.";
409
+ function isWebsiteMarket(market) {
410
+ return Object.hasOwn(LOGIN_PATHS, market);
411
+ }
412
+ function websiteEnvironment(value, env = process.env) {
413
+ const selected = value ?? env.AE_CLI_WEBSITE_ENV ?? "production";
414
+ if (selected !== "production" && selected !== "test") throw new Error("Choose website environment test or production.");
415
+ return selected;
416
+ }
417
+ function websiteOrigin(market, environment) {
418
+ websiteEnvironment(environment, {});
419
+ if (!isWebsiteMarket(market)) throw new Error(UNSUPPORTED_MARKET);
420
+ if (environment === "test") {
421
+ if (market === "cn") throw new Error("Overseas test website onboarding supports us, jp, and kr.");
422
+ return OVERSEAS_TEST_WEBSITE_ORIGIN;
423
+ }
424
+ return market === "cn" ? CHINA_PRODUCTION_ORIGIN : PRODUCTION_ISSUER;
425
+ }
426
+ function isProductionWebsiteOrigin(origin) {
427
+ return origin === PRODUCTION_ISSUER || origin === PRODUCTION_BROWSER_ORIGIN || origin === CHINA_PRODUCTION_ORIGIN;
428
+ }
429
+ function environmentForWebsiteOrigin(origin) {
430
+ if (origin === OVERSEAS_TEST_WEBSITE_ORIGIN) return "test";
431
+ if (isProductionWebsiteOrigin(origin)) return "production";
432
+ throw new Error("Untrusted onboarding website.");
433
+ }
434
+ function cliEntrySource(source, env = process.env) {
435
+ const selected = source ?? (UUID_PATTERN.test(env.CODEX_THREAD_ID ?? "") ? "codex" : "other");
436
+ if (!["codex", "cursor", "claude-code", "other"].includes(selected)) throw new Error("Unsupported local AI tool source.");
437
+ return selected;
438
+ }
439
+ function cliToolReference(source, env = process.env) {
440
+ return source === "codex" && UUID_PATTERN.test(env.CODEX_THREAD_ID ?? "") ? env.CODEX_THREAD_ID : void 0;
441
+ }
442
+ function withCliEntryContext(value, source, market, toolReference) {
443
+ const url = new URL(value);
444
+ if (url.protocol !== "https:" || url.username || url.password) throw new Error("Untrusted website continuation URL.");
445
+ if ([...url.searchParams.keys()].some((key) => /^(device_code|poll_token|access_token|refresh_token|cli[_-]token|token)$/i.test(key))) {
446
+ throw new Error("The website returned a private credential in its public continuation URL.");
447
+ }
448
+ const references = url.searchParams.getAll("tool_reference");
449
+ if (references.length > 1 || references.some((reference) => !UUID_PATTERN.test(reference))) throw new Error("Invalid AI tool continuation reference.");
450
+ url.searchParams.set("entry", "cli");
451
+ url.searchParams.set("source", cliEntrySource(source));
452
+ if (market && !url.searchParams.has("market")) url.searchParams.set("market", market);
453
+ if (toolReference) {
454
+ if (source !== "codex" || !UUID_PATTERN.test(toolReference)) throw new Error("Invalid AI tool continuation reference.");
455
+ if (references.length && references[0] !== toolReference) throw new Error("The website returned a mismatched AI tool continuation reference.");
456
+ if (!url.searchParams.has("tool_reference")) url.searchParams.set("tool_reference", toolReference);
457
+ }
458
+ return url.toString();
459
+ }
460
+ function websiteLoginUrl(market, environment, source, toolReference) {
461
+ if (!isWebsiteMarket(market)) throw new Error(UNSUPPORTED_MARKET);
462
+ const origin = websiteOrigin(market, environment);
463
+ const browserOrigin = origin === PRODUCTION_ISSUER ? PRODUCTION_BROWSER_ORIGIN : origin;
464
+ return withCliEntryContext(`${browserOrigin}${LOGIN_PATHS[market]}`, source, market, toolReference);
465
+ }
466
+
467
+ // src/core/onboarding/bootstrap-client.ts
468
+ var PATH = "/backend/demo/v1/experience/cli/bootstrap-intents";
469
+ var BootstrapRequestError = class extends Error {
470
+ constructor(websiteStatus) {
471
+ super(`The onboarding website request failed (HTTP ${websiteStatus}).`);
472
+ this.websiteStatus = websiteStatus;
473
+ }
474
+ websiteStatus;
475
+ };
476
+ function loginMode(value) {
477
+ if (value === void 0 || value === null) return void 0;
478
+ if (value === "website_login" || value === "device_confirmation") return value;
479
+ throw new Error("The website returned an invalid login mode.");
480
+ }
481
+ function authorizationStatus(value) {
482
+ if (value === void 0 || value === null) return void 0;
483
+ if (["pending", "authorizing", "approved", "claimed", "expired"].includes(String(value))) return value;
484
+ throw new Error("The website returned an invalid authorization status.");
485
+ }
486
+ function bootstrapOrigin(market, environment = websiteEnvironment()) {
487
+ return websiteOrigin(market, environment);
488
+ }
489
+ function trustedProductHost(value) {
490
+ const url = new URL(value);
491
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || !["", "/"].includes(url.pathname)) {
492
+ throw new Error("Onboarding requires a trusted HTTPS product origin.");
493
+ }
494
+ return url.origin;
495
+ }
496
+ function websiteUrl(value, origin) {
497
+ const url = new URL(value);
498
+ if (url.origin !== origin || url.username || url.password) throw new Error("The website returned an untrusted continuation URL.");
499
+ return url.toString();
500
+ }
501
+ async function request(origin, endpoint, init, signal) {
502
+ environmentForWebsiteOrigin(origin);
503
+ const response = await fetch(`${origin}${endpoint}`, {
504
+ ...init,
505
+ redirect: "error",
506
+ signal,
507
+ headers: { Accept: "application/json", "Content-Type": "application/json", ...init.headers }
508
+ });
509
+ const body = safeJsonParse(await response.text());
510
+ if (!response.ok || body?.return_code !== 0 || !body.data || typeof body.data !== "object") {
511
+ throw new BootstrapRequestError(response.status);
512
+ }
513
+ return body.data;
514
+ }
515
+ async function createBootstrap(market, source, host, signal, toolReference, environment, language) {
516
+ const origin = bootstrapOrigin(market, environment);
517
+ const tool = cliEntrySource(source);
518
+ if (toolReference && (tool !== "codex" || !UUID_PATTERN.test(toolReference))) throw new Error("Invalid AI tool continuation reference.");
519
+ const data = await request(origin, PATH, { method: "POST", headers: {
520
+ "X-AE-CLI-Login-Mode": "website_login",
521
+ ...language ? { "Accept-Language": language } : {}
522
+ }, body: JSON.stringify({
523
+ market,
524
+ source,
525
+ ...host ? { requested_host: trustedProductHost(host) } : {},
526
+ ...toolReference ? { tool_reference: toolReference } : {}
527
+ }) }, signal);
528
+ 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))) {
529
+ throw new Error("The website returned an invalid bootstrap session.");
530
+ }
531
+ return { ...data, login_mode: loginMode(data.login_mode), login_url: withCliEntryContext(websiteUrl(data.login_url, origin), tool, market, toolReference) };
532
+ }
533
+ async function readBootstrap(origin, intentId, pollToken, signal, source, market) {
534
+ if (!UUID_PATTERN.test(intentId)) throw new Error("Invalid bootstrap continuation.");
535
+ const data = await request(origin, `${PATH}/${encodeURIComponent(intentId)}`, {
536
+ method: "GET",
537
+ headers: { "X-CLI-Bootstrap-Token": pollToken }
538
+ }, signal);
539
+ if (data.intent_id !== intentId || !["pending", "account_ready", "browser_ready", "expired"].includes(data.status)) throw new Error("Invalid bootstrap state.");
540
+ return {
541
+ ...data,
542
+ login_mode: loginMode(data.login_mode),
543
+ authorization_status: authorizationStatus(data.authorization_status),
544
+ host: data.host ? trustedProductHost(data.host) : null,
545
+ ready_url: data.ready_url ? source ? withCliEntryContext(websiteUrl(data.ready_url, origin), cliEntrySource(source), market) : websiteUrl(data.ready_url, origin) : null
546
+ };
547
+ }
548
+ async function claimBootstrapDevice(origin, intentId, pollToken, signal) {
549
+ if (!UUID_PATTERN.test(intentId)) throw new Error("Invalid bootstrap continuation.");
550
+ const data = await request(origin, `${PATH}/${encodeURIComponent(intentId)}/device`, {
551
+ method: "POST",
552
+ body: "{}",
553
+ headers: { "X-CLI-Bootstrap-Token": pollToken }
554
+ }, signal).catch((error) => {
555
+ if (error instanceof BootstrapRequestError && error.websiteStatus === 410) {
556
+ return { login_mode: "website_login", authorization_status: "expired" };
557
+ }
558
+ throw error;
559
+ });
560
+ if (loginMode(data.login_mode) !== "website_login") throw new Error("The website did not confirm this login mode.");
561
+ const status = authorizationStatus(data.authorization_status);
562
+ if (!status) throw new Error("The website returned an invalid authorization status.");
563
+ if (status !== "approved" && status !== "claimed") return {
564
+ login_mode: "website_login",
565
+ authorization_status: status,
566
+ ...Number.isFinite(data.poll_after_ms) ? { poll_after_ms: data.poll_after_ms } : {}
567
+ };
568
+ 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.");
569
+ return {
570
+ login_mode: "website_login",
571
+ authorization_status: status,
572
+ host: trustedProductHost(data.host),
573
+ device_code: data.device_code,
574
+ user_code: data.user_code,
575
+ expires_at: data.expires_at,
576
+ interval: data.interval,
577
+ expected_login_name: data.expected_login_name,
578
+ expected_company_id: String(data.expected_company_id)
579
+ };
580
+ }
581
+
582
+ // src/core/resource-url.ts
583
+ var LOCAL_BACKEND_PORTS = /* @__PURE__ */ new Set(["8992", "8996"]);
584
+ function normalizeResourceUrlFields(node, host, sourceHost = host) {
585
+ if (!node || typeof node !== "object") return;
586
+ const obj = node;
587
+ for (const [key, value] of Object.entries(obj)) {
588
+ if (typeof value === "string") {
589
+ if (/url|link/i.test(key) || value.includes("/#/")) {
590
+ obj[key] = normalizeResourceUrls(value, host, sourceHost);
591
+ }
592
+ } else if (value && typeof value === "object") {
593
+ normalizeResourceUrlFields(value, host, sourceHost);
594
+ }
595
+ }
596
+ }
597
+ function absolutizeRelativeUrls(s, host) {
598
+ return normalizeResourceUrls(s, host);
599
+ }
600
+ function normalizeResourceUrls(s, host, sourceHost = host) {
601
+ const base = host.replace(/\/+$/, "");
602
+ const sourceBase = sourceHost.replace(/\/+$/, "");
603
+ if (sourceBase && sourceBase !== base) {
604
+ s = s.replace(new RegExp(`${escapeRegExp(sourceBase)}/#`, "g"), `${base}/#`);
605
+ }
606
+ s = s.replace(/\]\((\/(?!\/)[^)]*)\)/g, `](${base}$1)`);
607
+ if (/^\/(?!\/)/.test(s)) s = base + s;
608
+ return s;
609
+ }
610
+ function resolvePublicWebHost(host) {
611
+ const override = process.env.AE_CLI_PUBLIC_WEB_URL || process.env.AE_CLI_WEB_HOST;
612
+ if (override?.trim()) {
613
+ return override.trim().replace(/\/+$/, "");
614
+ }
615
+ try {
616
+ const url = new URL(host);
617
+ if ((url.hostname === "127.0.0.1" || url.hostname === "localhost") && LOCAL_BACKEND_PORTS.has(url.port)) {
618
+ url.port = "10010";
619
+ return url.toString().replace(/\/+$/, "");
620
+ }
621
+ } catch {
622
+ }
623
+ return host.replace(/\/+$/, "");
624
+ }
625
+ function escapeRegExp(value) {
626
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
627
+ }
628
+
629
+ // src/core/onboarding/interaction.ts
630
+ var interactions = {
631
+ complete_website_login: [
632
+ { value: "login_done", label: "I finished signing in" },
633
+ { value: "login_help", label: "Help me sign in" }
634
+ ],
635
+ approve_device: [
636
+ { value: "authorization_done", label: "CLI access approved" },
637
+ { value: "authorization_help", label: "Help me approve CLI access" }
638
+ ],
639
+ restart_website_login: [
640
+ { value: "retry_login", label: "Reopen the sign-in page" },
641
+ { value: "not_now", label: "Not now" }
642
+ ],
643
+ choose_experience: [
644
+ { value: "demo", label: "Start the demo" },
645
+ { value: "business", label: "Connect my business data" }
646
+ ],
647
+ demo_entry: [
648
+ { value: "demo", label: "Try the sample data" },
649
+ { value: "learn", label: "See what ThinkingAI can do" }
650
+ ],
651
+ choose_data_source: [
652
+ { value: "import_data", label: "Import a file or Feishu table" },
653
+ { value: "sdk", label: "Connect an app SDK" },
654
+ { value: "more_data_tools", label: "More integration tools" }
655
+ ],
656
+ choose_data_tool: [
657
+ { value: "datax", label: "Connect with DataX" },
658
+ { value: "logbus2", label: "Configure LogBus2" },
659
+ { value: "tracking_plan", label: "Create a tracking plan" },
660
+ { value: "migrate_tracking", label: "Migrate existing tracking" },
661
+ { value: "dimension_table", label: "Import a dimension table" },
662
+ { value: "check_ingestion", label: "Check existing ingestion" }
663
+ ],
664
+ confirm_business_project: [
665
+ { value: "confirm_project", label: "Use this AE project" },
666
+ { value: "not_now", label: "Not now" }
667
+ ],
668
+ offer_growth_questions: [
669
+ { value: "growth", label: "Find players worth following up with" },
670
+ { value: "checkout_recovery", label: "Find players who left checkout" }
671
+ ],
672
+ growth_ready: [
673
+ { value: "follow_up", label: "See how to follow up" }
674
+ ],
675
+ confirm_experiment: [
676
+ { value: "launch", label: "Confirm and start the A/B experiment" }
677
+ ],
678
+ review_experiment: [
679
+ { value: "launch", label: "Approve and start the Demo test" },
680
+ { value: "review_audience", label: "Why this audience?" },
681
+ { value: "review_pilot", label: "How would a small pilot work?" },
682
+ { value: "review_no_reward", label: "What can we test without rewards?" }
683
+ ],
684
+ demo_overview: [
685
+ { value: "growth", label: "Find players worth following up with" },
686
+ { value: "diagnosis", label: "Investigate a business question" }
687
+ ],
688
+ diagnosis_topics: [
689
+ { value: "product_revisits", label: "Product revisits" },
690
+ { value: "checkout_recovery", label: "Checkout without payment" },
691
+ { value: "purchase_conversion", label: "Purchase conversion" }
692
+ ],
693
+ reauthorize_cli: [
694
+ { value: "reauthorize", label: "Reconnect the CLI" },
695
+ { value: "not_now", label: "Not now" }
696
+ ]
697
+ };
698
+ function onboardingDraftReviewInteraction(answered = []) {
699
+ return { step: "review_experiment", options: interactions.review_experiment.filter((option) => option.value === "launch" || !answered.includes(option.value)) };
700
+ }
701
+ function onboardingDemoOverview(sampleId, visit) {
702
+ const seasonPass = sampleId === "season-pass";
703
+ const themes = interactions.diagnosis_topics;
704
+ const questions = seasonPass ? [
705
+ "Which pass players could we win back?",
706
+ "Where did players leave the purchase funnel?",
707
+ "Which pass viewers came back without buying?"
708
+ ] : [
709
+ "Which returning bundle viewers should we follow up with?",
710
+ "Which bundle players started checkout without buying?",
711
+ "Where did players leave the purchase funnel?"
712
+ ];
713
+ const first = seasonPass ? 1 : 0;
714
+ const round = Math.max(0, visit - 1) % themes.length;
715
+ const index = (first + round) % themes.length;
716
+ const topicLabels = seasonPass ? ["Pass revisits", "Pass checkout drop-off", "Pass purchase funnel"] : ["Bundle revisits", "Bundle checkout drop-off", "Bundle purchase funnel"];
717
+ const sampleTopics = themes.map((topic, i) => ({ ...topic, label: topicLabels[i] }));
718
+ const topics = [...sampleTopics.slice(index), ...sampleTopics.slice(0, index)];
719
+ const growthLabels = seasonPass ? ["Find unpaid pass checkouts", "Find where pass buyers drop off", "Find returning pass viewers"] : ["Find repeat bundle viewers", "Find unpaid bundle checkouts", "Find where bundle buyers drop off"];
720
+ const [growth, diagnosis] = interactions.demo_overview;
721
+ return {
722
+ primary_metric: seasonPass ? "checkout_unpaid_rate" : "purchase_rate_by_viewing_days",
723
+ featured_topic: topics[0].value,
724
+ featured_question: questions[round],
725
+ interaction: { step: "demo_overview", options: [
726
+ { ...growth, label: growthLabels[round] },
727
+ { ...diagnosis, label: seasonPass ? "Investigate pass conversion" : "Investigate bundle purchases" }
728
+ ] },
729
+ diagnosis: { step: "diagnosis_topics", options: topics }
730
+ };
731
+ }
732
+ function onboardingInteraction(step, web = false) {
733
+ if (!Object.hasOwn(interactions, step)) return void 0;
734
+ const options = web && step === "choose_experience" ? [interactions.choose_experience[0], interactions.demo_entry[1], { value: "not_now", label: "Not now" }] : interactions[step];
735
+ return { step, options };
736
+ }
737
+ function onboardingEvidenceLinks(evidence, projectId, host) {
738
+ if (!evidence || typeof evidence !== "object" || typeof projectId !== "number" || !Number.isSafeInteger(projectId) || projectId < 1) return void 0;
739
+ const paths = evidence;
740
+ const links = {};
741
+ const evidenceRoutes = {
742
+ dashboard_url: "panel/panel",
743
+ purchase_rate_report_url: "tga/ide",
744
+ funnel_report_url: "tga/funnel"
745
+ };
746
+ for (const [key, route] of Object.entries(evidenceRoutes)) {
747
+ const value = paths[key];
748
+ if (typeof value === "string" && new RegExp(`^/#/${route}/${projectId}_[1-9][0-9]*$`).test(value)) {
749
+ links[key] = host ? absolutizeRelativeUrls(value, host) : value;
750
+ }
751
+ }
752
+ return Object.keys(links).length ? links : void 0;
753
+ }
754
+ function onboardingExperimentUrl(projectId, experimentId, host) {
755
+ const params = new URLSearchParams({ expId: experimentId, currentProjectId: String(projectId) });
756
+ const route = `/#/atlas/experiment/detail?${params}`;
757
+ return host ? absolutizeRelativeUrls(route, host) : route;
758
+ }
759
+
760
+ // src/core/onboarding/markdown-charts.ts
761
+ var barWidth = 12;
762
+ var ringMarks = ["\u2588", "\u2592"];
763
+ var stackedMarks = ["\u{1F7E6}", "\u{1F7EA}", "\u2B1C"];
764
+ function share(value, total) {
765
+ return total ? `${(value * 100 / total).toFixed(1)}%` : "\u2014";
766
+ }
767
+ function comparisonMarkdown(points, maximum, percent = false) {
768
+ const rows = points.map(({ label, value }) => {
769
+ const width = value === null || !maximum ? 0 : Math.round(value * barWidth / maximum);
770
+ const exact = value === null ? "\u2014" : percent ? `${value.toFixed(1)}%` : String(value);
771
+ return `| ${label} | ${exact} | ${"\u{1F7E6}".repeat(width)} |`;
772
+ });
773
+ return ["| Group | Value | Scale |", "| --- | ---: | --- |", ...rows].join("\n");
774
+ }
775
+ function compositionTable(points, total, marks) {
776
+ return ["| Group | Players | Share |", "| --- | ---: | ---: |", ...points.map(({ label, value }, index) => `| ${marks[index]} ${label} | ${value} | ${share(value, total)} |`)].join("\n");
777
+ }
778
+ function checkoutRingMarkdown(points) {
779
+ const total = points[0].value + points[1].value;
780
+ if (!total) return null;
781
+ const firstShare = points[0].value / total;
782
+ const rows = [];
783
+ for (let y = -4; y <= 4; y += 1) {
784
+ let row = "";
785
+ for (let x = -9; x <= 9; x += 1) {
786
+ const radius = Math.hypot(x / 2, y);
787
+ const angle = (Math.atan2(x / 2, -y) + 2 * Math.PI) % (2 * Math.PI);
788
+ row += radius < 2.7 || radius > 4.5 ? " " : ringMarks[angle / (2 * Math.PI) < firstShare ? 0 : 1];
789
+ }
790
+ rows.push(row.trimEnd());
791
+ }
792
+ return ["```text", ...rows, "```", "", compositionTable(points, total, ringMarks)].join("\n");
793
+ }
794
+ function audienceShareMarkdown(points) {
795
+ const total = points.reduce((sum, point) => sum + point.value, 0);
796
+ if (!total) return null;
797
+ const width = 20;
798
+ let cumulative = 0;
799
+ let previousBoundary = 0;
800
+ const marks = points.map(({ value }, index) => {
801
+ cumulative += value;
802
+ const boundary = Math.round(cumulative * width / total);
803
+ const segment = stackedMarks[index].repeat(boundary - previousBoundary);
804
+ previousBoundary = boundary;
805
+ return segment;
806
+ }).join("");
807
+ return `${marks}
808
+
809
+ ${compositionTable(points, total, stackedMarks)}`;
810
+ }
811
+ function dailyTrendMarkdown(points) {
812
+ const levels = 6;
813
+ const counts = points.map((point) => point.value);
814
+ const minimum = Math.min(...counts);
815
+ const maximum = Math.max(...counts);
816
+ const step = Math.max(1, Math.ceil((maximum - minimum) / levels));
817
+ const baseline = Math.max(0, maximum - step * levels);
818
+ const spacing = 6;
819
+ const grid = Array.from({ length: levels + 1 }, () => Array((points.length - 1) * spacing + 1).fill(" "));
820
+ const heights = counts.map((value) => Math.round((value - baseline) / step));
821
+ for (let index = 1; index < heights.length; index += 1) {
822
+ const rise = heights[index] - heights[index - 1];
823
+ for (let offset = 1; offset < spacing; offset += 1) {
824
+ const height = Math.round(heights[index - 1] + rise * offset / spacing);
825
+ const before = Math.round(heights[index - 1] + rise * (offset - 1) / spacing);
826
+ const after = Math.round(heights[index - 1] + rise * (offset + 1) / spacing);
827
+ const stroke = before === after ? "\u2500" : rise > 0 ? "\u2571" : "\u2572";
828
+ grid[levels - height][(index - 1) * spacing + offset] = stroke;
829
+ }
830
+ }
831
+ heights.forEach((height, index) => {
832
+ grid[levels - height][index * spacing] = "\u25CF";
833
+ });
834
+ const labelWidth = String(baseline + step * levels).length;
835
+ const dates = points.map((point) => point.label.slice(5).replace("-", "/"));
836
+ const axis = grid.map((row, index) => `${String(baseline + (levels - index) * step).padStart(labelWidth)} \u2502 ${row.join("")}`.trimEnd());
837
+ const table = [
838
+ `| Date | ${dates.join(" | ")} |`,
839
+ `| --- | ${dates.map(() => "---:").join(" | ")} |`,
840
+ `| Viewers | ${points.map((point) => point.value).join(" | ")} |`
841
+ ];
842
+ return [
843
+ "```text",
844
+ ...axis,
845
+ `${" ".repeat(labelWidth + 1)} \u2514${"\u2500".repeat(grid[0].length + 2)}`,
846
+ `${" ".repeat(labelWidth + 1)}${dates.join(" ")}`,
847
+ "```",
848
+ "",
849
+ ...table
850
+ ].join("\n");
851
+ }
852
+ function funnelMarkdown(points, transitions) {
853
+ const peak = points[0].value;
854
+ const rows = points.map(({ label, value }, index) => {
855
+ const width = peak ? Math.round(value * barWidth / peak) : 0;
856
+ const transition = transitions[index - 1];
857
+ const rate = transition?.conversion_rate;
858
+ return `| ${label} | ${value} | ${"\u2501".repeat(width)} | ${transition?.dropoff_accounts ?? "\u2014"} | ${rate == null ? "\u2014" : share(rate, 1)} |`;
859
+ });
860
+ return ["| Step | Players | Scale | Drop-off | Conversion |", "| --- | ---: | :---: | ---: | ---: |", ...rows].join("\n");
861
+ }
862
+
863
+ // src/core/onboarding/growth.ts
864
+ var GROWTH_VERSION = 2;
865
+ var CACHE_TTL_MS = 10 * 6e4;
866
+ var DAY_MS = 864e5;
867
+ var SAMPLE_DAYS = 7;
868
+ var VIEW = "item_detail_view";
869
+ var CHECKOUT = "checkout_start";
870
+ var PAYMENT = "payment_success";
871
+ var fields = [
872
+ "single_viewers",
873
+ "single_buyers",
874
+ "multi_viewers",
875
+ "multi_buyers",
876
+ "funnel_viewers",
877
+ "funnel_checkout",
878
+ "funnel_buyers",
879
+ "account_ids_json",
880
+ "checkout_unpaid",
881
+ "checkout_account_ids_json",
882
+ "unmapped_accounts"
883
+ ];
884
+ function date(value) {
885
+ 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;
886
+ }
887
+ function shiftDate(value, days) {
888
+ return new Date(Date.parse(value) + days * DAY_MS).toISOString().slice(0, 10);
889
+ }
890
+ function sampleDates(startDate) {
891
+ return Array.from({ length: SAMPLE_DAYS }, (_, index) => shiftDate(startDate, index));
892
+ }
893
+ function growthScope(session, demo) {
894
+ const { project_id, sample_id, item_id, start_date, end_date, zone_offset } = demo;
895
+ 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) !== (SAMPLE_DAYS - 1) * DAY_MS || typeof zone_offset !== "number" || !Number.isFinite(zone_offset) || Math.abs(zone_offset) > 14) return void 0;
896
+ return {
897
+ sessionId: session.id,
898
+ host: trustedProductHost(session.host),
899
+ projectId: project_id,
900
+ sampleId: sample_id,
901
+ itemId: item_id,
902
+ startDate: start_date,
903
+ endDate: end_date,
904
+ zoneOffset: zone_offset
905
+ };
906
+ }
907
+ function evidenceFile(scope, credentialKey) {
908
+ const digest = crypto.createHash("sha256").update(JSON.stringify([GROWTH_VERSION, credentialKey, scope])).digest("hex");
909
+ return `growth-${digest}.json`;
910
+ }
911
+ function readGrowthEvidence(store, file, scope) {
912
+ const evidence = store.read(file);
913
+ 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;
914
+ }
915
+ function readCheckoutRecoveryCohort(store, session, demo) {
916
+ const scope = growthScope(session, demo);
917
+ if (!scope || !session.credential_key) return void 0;
918
+ const evidence = readGrowthEvidence(store, evidenceFile(scope, session.credential_key), scope);
919
+ if (!evidence) return void 0;
920
+ return { start_date: scope.startDate, end_date: scope.endDate, zone_offset: scope.zoneOffset, account_ids: evidence.checkoutAccountIds };
921
+ }
922
+ function sqlString(value) {
923
+ return `'${value.replaceAll("'", "''")}'`;
924
+ }
925
+ function verifiedTables(result2, type) {
926
+ return result2.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);
927
+ }
928
+ async function resolveEventSource(call, projectId) {
929
+ let offset = 0;
930
+ const events = /* @__PURE__ */ new Set();
931
+ const users = /* @__PURE__ */ new Set();
932
+ const scope = { project_id: projectId, usage: "analysis" };
933
+ while (true) {
934
+ const page = await call("analysis.sql_table.list", { ...scope, limit: 200, offset });
935
+ if (!Array.isArray(page?.items) || typeof page.has_more !== "boolean") throw new Error("AE did not return the authorized SQL tables.");
936
+ verifiedTables(page, "eventView").forEach((name) => events.add(name));
937
+ verifiedTables(page, "userView").forEach((name) => users.add(name));
938
+ if (!page.has_more) break;
939
+ if (!Number.isSafeInteger(page.next_offset) || page.next_offset <= offset) throw new Error("AE returned an invalid SQL table continuation.");
940
+ offset = page.next_offset;
941
+ }
942
+ if (events.size !== 1) throw new Error("AE did not return exactly one authorized Demo event view.");
943
+ const event = [...events][0];
944
+ const readColumns = async (table_ref) => {
945
+ const result2 = await call("analysis.sql_table.columns", { ...scope, table_ref });
946
+ if (!Array.isArray(result2?.columns)) throw new Error("AE did not return the authorized Demo columns.");
947
+ return new Set(result2.columns.map((entry) => entry.column));
948
+ };
949
+ const columns = await readColumns(event);
950
+ if (!["#event_time", "$part_date", "$part_event", "plg_sample_id", "item_id", "plg_seed_event_id"].every((name) => columns.has(name))) {
951
+ throw new Error("The authorized Demo view is missing the fields required for growth analysis.");
952
+ }
953
+ if (columns.has("#account_id")) return { from: `${event} e`, account: 'e."#account_id"' };
954
+ if (!columns.has("#user_id") || users.size !== 1) throw new Error("AE did not expose a verified Demo account-ID mapping.");
955
+ const user = [...users][0];
956
+ const userColumns = await readColumns(user);
957
+ if (!userColumns.has("#user_id") || !userColumns.has("#account_id")) throw new Error("AE did not expose a verified Demo account-ID mapping.");
958
+ return { from: `${event} e LEFT JOIN ${user} u ON e."#user_id" = u."#user_id"`, account: 'u."#account_id"' };
959
+ }
960
+ function growthSql(scope, source) {
961
+ const dailyCounts = sampleDates(scope.startDate).map((day) => `count_if(contains(view_dates, DATE '${day}'))`);
962
+ return `WITH sample_events AS (
963
+ SELECT NULLIF(CAST(${source.account} AS varchar), '') AS account_id,
964
+ e."$part_event" AS event_name, e."#event_time" AS event_time
965
+ FROM ${source.from}
966
+ WHERE e."$part_date" BETWEEN '${shiftDate(scope.startDate, -1)}' AND '${shiftDate(scope.endDate, 1)}'
967
+ AND e."#event_time" >= TIMESTAMP '${scope.startDate} 00:00:00'
968
+ AND e."#event_time" < TIMESTAMP '${shiftDate(scope.endDate, 1)} 00:00:00'
969
+ AND e.plg_sample_id = ${sqlString(scope.sampleId)} AND e.item_id = ${sqlString(scope.itemId)}
970
+ AND e.plg_seed_event_id IS NOT NULL
971
+ AND e."$part_event" IN ('${VIEW}', '${CHECKOUT}', '${PAYMENT}')
972
+ ), views AS (
973
+ SELECT *, min(CASE WHEN event_name = '${VIEW}' THEN event_time END) OVER (PARTITION BY account_id) AS first_view
974
+ FROM sample_events
975
+ ), checkouts AS (
976
+ SELECT *, min(CASE WHEN event_name = '${CHECKOUT}' AND event_time > first_view THEN event_time END)
977
+ OVER (PARTITION BY account_id) AS first_checkout
978
+ FROM views
979
+ ), activity AS (
980
+ SELECT account_id, array_agg(DISTINCT CAST(event_time AS date)) FILTER (WHERE event_name = '${VIEW}') AS view_dates,
981
+ count_if(event_name = '${PAYMENT}') > 0 AS bought,
982
+ count_if(first_checkout IS NOT NULL) > 0 AS checked_out,
983
+ count_if(event_name = '${PAYMENT}' AND event_time > first_checkout) > 0 AS paid_after_checkout
984
+ FROM checkouts GROUP BY account_id
985
+ ), accounts AS (
986
+ SELECT *, COALESCE(cardinality(view_dates), 0) AS view_days FROM activity
987
+ )
988
+ SELECT count_if(view_days = 1) AS single_viewers, count_if(view_days = 1 AND bought) AS single_buyers,
989
+ count_if(view_days >= 2) AS multi_viewers, count_if(view_days >= 2 AND bought) AS multi_buyers,
990
+ count_if(view_days > 0) AS funnel_viewers, count_if(checked_out) AS funnel_checkout,
991
+ count_if(paid_after_checkout) AS funnel_buyers,
992
+ COALESCE(json_format(CAST(array_sort(array_agg(account_id) FILTER (WHERE view_days >= 2 AND NOT bought)) AS JSON)), '[]') AS account_ids_json,
993
+ count_if(checked_out AND NOT bought) AS checkout_unpaid,
994
+ COALESCE(json_format(CAST(array_sort(array_agg(account_id) FILTER (WHERE checked_out AND NOT bought)) AS JSON)), '[]') AS checkout_account_ids_json,
995
+ count_if(account_id IS NULL) AS unmapped_accounts,
996
+ json_format(CAST(ARRAY[${dailyCounts.join(", ")}] AS JSON)) AS daily_viewers_json
997
+ FROM accounts`;
998
+ }
999
+ function accountIds(value, expected) {
1000
+ let ids;
1001
+ try {
1002
+ ids = typeof value === "string" ? JSON.parse(value) : void 0;
1003
+ } catch {
1004
+ }
1005
+ 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())) {
1006
+ throw new Error("AE returned incomplete or inconsistent Demo growth evidence.");
1007
+ }
1008
+ return ids;
1009
+ }
1010
+ function parseDailyViewers(value, viewers) {
1011
+ if (typeof value !== "string") return void 0;
1012
+ let counts;
1013
+ try {
1014
+ counts = JSON.parse(value);
1015
+ } catch {
1016
+ return void 0;
1017
+ }
1018
+ if (!Array.isArray(counts) || counts.length !== SAMPLE_DAYS || !counts.every((count) => Number.isSafeInteger(count) && count >= 0 && count <= viewers) || counts.reduce((sum, count) => sum + count, 0) < viewers) return void 0;
1019
+ return counts;
1020
+ }
1021
+ function parseGrowth(result2, scope, verifiedAt) {
1022
+ if (result2?.has_more !== false || result2.returned_rows !== 1 || result2.rows?.length !== 1 || !Array.isArray(result2.title) || !Array.isArray(result2.rows[0])) {
1023
+ throw new Error("AE did not return a complete Demo growth result.");
1024
+ }
1025
+ const row = Object.fromEntries(result2.title.map((name, index) => [name, result2.rows[0][index]]));
1026
+ if (!fields.every((field) => Object.hasOwn(row, field))) throw new Error("AE did not return the expected Demo growth fields.");
1027
+ const count = (field) => {
1028
+ const raw = row[field];
1029
+ const value = typeof raw === "string" && /^\d+$/.test(raw) ? Number(raw) : raw;
1030
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error("AE returned an invalid Demo growth count.");
1031
+ return value;
1032
+ };
1033
+ const single_day = { viewers: count("single_viewers"), buyers: count("single_buyers") };
1034
+ const multi_day = { viewers: count("multi_viewers"), buyers: count("multi_buyers") };
1035
+ const funnel = { viewers: count("funnel_viewers"), checkout: count("funnel_checkout"), buyers: count("funnel_buyers") };
1036
+ const checkoutUnpaid = count("checkout_unpaid");
1037
+ 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) {
1038
+ throw new Error("AE returned incomplete or inconsistent Demo growth evidence.");
1039
+ }
1040
+ return {
1041
+ ...scope,
1042
+ schemaVersion: 1,
1043
+ analysisVersion: GROWTH_VERSION,
1044
+ verifiedAt,
1045
+ single_day,
1046
+ multi_day,
1047
+ funnel,
1048
+ dailyViewers: parseDailyViewers(row.daily_viewers_json, funnel.viewers),
1049
+ accountIds: accountIds(row.account_ids_json, multi_day.viewers - multi_day.buyers),
1050
+ checkoutAccountIds: accountIds(row.checkout_account_ids_json, checkoutUnpaid)
1051
+ };
1052
+ }
1053
+ async function runOnboardingGrowth(store, deps, input, preview) {
1054
+ const scenario = onboardingGrowthScenario(input.scenario);
1055
+ const sessionId = input.session_id;
1056
+ if (!sessionId || !UUID_PATTERN.test(sessionId)) throw new Error("A valid onboarding --session-id is required.");
1057
+ const explicitHost = input.host ? trustedProductHost(input.host) : void 0;
1058
+ const readSession = () => store.session(sessionId, explicitHost);
1059
+ if (preview) {
1060
+ const session = readSession();
1061
+ return {
1062
+ dry_run: true,
1063
+ session_id: sessionId,
1064
+ host: session.host ?? null,
1065
+ sample_id: session.sample_id ?? null,
1066
+ scenario,
1067
+ capabilities: [DEMO_STATUS, "analysis.sql_table.list", "analysis.sql_table.columns", "analysis.adhoc.run"]
1068
+ };
1069
+ }
1070
+ const started = deps.now();
1071
+ const signal = AbortSignal.timeout(RUN_BUDGET_MS);
1072
+ return store.locked(`session:${sessionId}`, async () => {
1073
+ const session = readSession();
1074
+ const base = { session_id: sessionId, host: session.host ?? null, sample_id: session.sample_id ?? null, scenario };
1075
+ if (!session.host || !session.credential_key || session.requires_auth || deps.credentialKey(session.host) !== session.credential_key) {
1076
+ return {
1077
+ ...base,
1078
+ phase: "action_required",
1079
+ next_action: "resume_onboarding",
1080
+ poll_after_ms: 0,
1081
+ message: "Resume onboarding with the signed-in account for this session."
1082
+ };
1083
+ }
1084
+ const host = trustedProductHost(session.host);
1085
+ if (session.choice !== "demo" || !session.sample_id || !DEMO_SAMPLE_IDS.some((sample) => sample === session.sample_id)) {
1086
+ return {
1087
+ ...base,
1088
+ phase: "action_required",
1089
+ next_action: "choose_demo",
1090
+ poll_after_ms: 0,
1091
+ message: "Select a supported Demo in this onboarding session."
1092
+ };
1093
+ }
1094
+ const call = async (id, body) => {
1095
+ signal.throwIfAborted();
1096
+ const request2 = new AbortController();
1097
+ const abort = () => request2.abort();
1098
+ const timer = setTimeout(abort, NETWORK_BUDGET_MS);
1099
+ timer.unref();
1100
+ signal.addEventListener("abort", abort, { once: true });
1101
+ try {
1102
+ const result2 = await deps.capability(host, id, body, request2.signal);
1103
+ request2.signal.throwIfAborted();
1104
+ return result2;
1105
+ } finally {
1106
+ signal.removeEventListener("abort", abort);
1107
+ clearTimeout(timer);
1108
+ }
1109
+ };
1110
+ try {
1111
+ const demo = await call(DEMO_STATUS, { sample_id: session.sample_id });
1112
+ if (typeof demo?.status !== "string" || demo.sample_id !== session.sample_id) {
1113
+ throw new Error("AE did not confirm the selected Demo sample.");
1114
+ }
1115
+ if (demo.status !== "ready") {
1116
+ return demo.status === "action_required" ? {
1117
+ ...base,
1118
+ phase: "action_required",
1119
+ next_action: "inspect_demo_preparation",
1120
+ poll_after_ms: 0,
1121
+ message: "Demo preparation needs attention before analysis can run."
1122
+ } : { ...base, phase: "pending", next_action: "poll_demo", poll_after_ms: 2e3 };
1123
+ }
1124
+ const scope = growthScope(session, demo);
1125
+ if (!scope) throw new Error("AE did not confirm the active Demo project and its seven-day sample scope.");
1126
+ const file = evidenceFile(scope, session.credential_key);
1127
+ let evidence = readGrowthEvidence(store, file, scope);
1128
+ const cached = evidence !== void 0 && deps.now() - evidence.verifiedAt >= 0 && deps.now() - evidence.verifiedAt < CACHE_TTL_MS;
1129
+ let queryMs = 0;
1130
+ if (!evidence || !cached) {
1131
+ const source = await resolveEventSource(call, scope.projectId);
1132
+ const queryStarted = deps.now();
1133
+ const rows = await call("analysis.adhoc.run", {
1134
+ project_id: scope.projectId,
1135
+ model_type: "sql",
1136
+ definition: { sql: growthSql(scope, source) },
1137
+ use_cache: false
1138
+ });
1139
+ queryMs = Math.max(0, deps.now() - queryStarted);
1140
+ evidence = parseGrowth(rows, scope, deps.now());
1141
+ }
1142
+ if (deps.credentialKey(host) !== session.credential_key) throw new Error("The active CLI account changed during Demo growth analysis.");
1143
+ if (!cached) store.write(file, evidence);
1144
+ const readyDemo = {
1145
+ sample_id: scope.sampleId,
1146
+ item_id: scope.itemId,
1147
+ project_id: scope.projectId,
1148
+ start_date: scope.startDate,
1149
+ end_date: scope.endDate,
1150
+ zone_offset: scope.zoneOffset
1151
+ };
1152
+ if (!Object.entries(readyDemo).every(([key, value]) => session.ready_demo?.[key] === value)) {
1153
+ session.ready_demo = readyDemo;
1154
+ store.save(session);
1155
+ }
1156
+ const singleRate = evidence.single_day.viewers ? evidence.single_day.buyers / evidence.single_day.viewers : null;
1157
+ const multiRate = evidence.multi_day.viewers ? evidence.multi_day.buyers / evidence.multi_day.viewers : null;
1158
+ const checkoutUnpaid = evidence.checkoutAccountIds.length;
1159
+ const checkoutAccounts = new Set(evidence.checkoutAccountIds);
1160
+ const overlappingAccounts = evidence.accountIds.filter((id) => checkoutAccounts.has(id)).length;
1161
+ const funnelSteps = [
1162
+ { event: VIEW, accounts: evidence.funnel.viewers },
1163
+ { event: CHECKOUT, accounts: evidence.funnel.checkout },
1164
+ { event: PAYMENT, accounts: evidence.funnel.buyers }
1165
+ ];
1166
+ const funnelTransitions = funnelSteps.slice(1).map((step, index) => {
1167
+ const previous = funnelSteps[index];
1168
+ return {
1169
+ from_event: previous.event,
1170
+ to_event: step.event,
1171
+ from_accounts: previous.accounts,
1172
+ to_accounts: step.accounts,
1173
+ dropoff_accounts: previous.accounts - step.accounts,
1174
+ conversion_rate: previous.accounts ? step.accounts / previous.accounts : null
1175
+ };
1176
+ });
1177
+ const followUpData = scenario === CHECKOUT_RECOVERY ? [
1178
+ { label: "Started checkout", value: evidence.funnel.checkout },
1179
+ { label: "Paid after checkout", value: evidence.funnel.buyers },
1180
+ { label: "Checkout without payment", value: checkoutUnpaid }
1181
+ ] : [
1182
+ { label: "Multi-day viewers, unpaid", value: evidence.accountIds.length },
1183
+ { label: "Single-day viewers, unpaid", value: evidence.single_day.viewers - evidence.single_day.buyers },
1184
+ { label: "Paid viewers", value: evidence.single_day.buyers + evidence.multi_day.buyers }
1185
+ ];
1186
+ const maxCount = Math.max(1, ...followUpData.map((row) => row.value));
1187
+ const followUpMarkdown = followUpData.map(({ label, value }) => {
1188
+ const width = value === 0 ? 0 : Math.max(1, Math.round(value * 10 / maxCount));
1189
+ return `- ${label} \xB7 ${width ? "\u2588".repeat(width) + " " : ""}**${value}**`;
1190
+ }).join("\n");
1191
+ const checkoutTotal = evidence.funnel.checkout;
1192
+ const checkoutOther = checkoutTotal - checkoutUnpaid;
1193
+ const checkoutShare = [
1194
+ { label: "Started checkout without paying", value: checkoutUnpaid },
1195
+ { label: checkoutOther === evidence.funnel.buyers ? "Paid after checkout" : "Other checkout starters", value: checkoutOther }
1196
+ ];
1197
+ const audienceOverlap = [
1198
+ { label: "Both signals", value: overlappingAccounts },
1199
+ { label: "Started checkout only", value: checkoutUnpaid - overlappingAccounts },
1200
+ { label: "Viewed on multiple days only", value: evidence.accountIds.length - overlappingAccounts }
1201
+ ];
1202
+ const purchaseRateData = [
1203
+ ...singleRate === null ? [] : [{ label: "Single-day viewers", value: Math.round(singleRate * 1e3) / 10 }],
1204
+ ...multiRate === null ? [] : [{ label: "Multi-day viewers", value: Math.round(multiRate * 1e3) / 10 }]
1205
+ ];
1206
+ const funnelData = [
1207
+ { label: "Viewed", value: evidence.funnel.viewers },
1208
+ { label: "Started checkout", value: checkoutTotal },
1209
+ { label: "Paid", value: evidence.funnel.buyers }
1210
+ ];
1211
+ const dailyViewers = evidence.dailyViewers;
1212
+ const dailyData = dailyViewers && sampleDates(scope.startDate).map((label, index) => ({ label, value: dailyViewers[index] }));
1213
+ return {
1214
+ ...base,
1215
+ phase: "ready",
1216
+ demo_project_id: scope.projectId,
1217
+ item_id: scope.itemId,
1218
+ start_date: scope.startDate,
1219
+ end_date: scope.endDate,
1220
+ zone_offset: scope.zoneOffset,
1221
+ analysis_version: GROWTH_VERSION,
1222
+ single_day: evidence.single_day,
1223
+ multi_day: evidence.multi_day,
1224
+ funnel: evidence.funnel,
1225
+ purchase_rates: {
1226
+ single_day: singleRate,
1227
+ multi_day: multiRate,
1228
+ difference_pp: singleRate === null || multiRate === null ? null : (multiRate - singleRate) * 100
1229
+ },
1230
+ data_basis: { source: "demo_seed_events", counting_unit: "distinct_accounts", funnel_transitions: funnelTransitions },
1231
+ charts: {
1232
+ purchase_rate: { type: "bar", data: purchaseRateData },
1233
+ funnel: { type: "bar", data: funnelData },
1234
+ ...dailyData ? { daily_viewers: { type: "line", data: dailyData } } : {}
1235
+ },
1236
+ visuals: {
1237
+ overview: scope.sampleId === "season-pass" ? "checkout_share" : "purchase_rate",
1238
+ checkout_share: checkoutTotal > 0 ? { type: "pie", data: checkoutShare } : null,
1239
+ audience_overlap: { type: "pie", data: audienceOverlap }
1240
+ },
1241
+ markdown_charts: {
1242
+ purchase_rate: comparisonMarkdown([
1243
+ { label: "Single-day viewers", value: singleRate === null ? null : singleRate * 100 },
1244
+ { label: "Multi-day viewers", value: multiRate === null ? null : multiRate * 100 }
1245
+ ], 100, true),
1246
+ checkout_share: checkoutRingMarkdown(checkoutShare),
1247
+ audience_overlap: audienceShareMarkdown(audienceOverlap),
1248
+ purchase_funnel: funnelMarkdown(funnelData, funnelTransitions),
1249
+ follow_up: comparisonMarkdown(followUpData, maxCount),
1250
+ ...dailyData ? { daily_viewers: dailyTrendMarkdown(dailyData) } : {}
1251
+ },
1252
+ follow_up_chart: { type: "bar", data: followUpData, markdown: followUpMarkdown },
1253
+ follow_up_count: scenario === CHECKOUT_RECOVERY ? checkoutUnpaid : evidence.accountIds.length,
1254
+ checkout_recovery: { unpaid_count: checkoutUnpaid, unpaid_rate: evidence.funnel.checkout ? checkoutUnpaid / evidence.funnel.checkout : null },
1255
+ candidate_cohorts: {
1256
+ multi_day_unpaid: evidence.accountIds.length,
1257
+ checkout_unpaid: checkoutUnpaid,
1258
+ overlap: overlappingAccounts,
1259
+ total_distinct: evidence.accountIds.length + checkoutUnpaid - overlappingAccounts
1260
+ },
1261
+ cohort_path: path2.resolve(store.directory, file),
1262
+ evidence: onboardingEvidenceLinks(demo.evidence, scope.projectId, deps.webConversation ? void 0 : host),
1263
+ interaction: onboardingInteraction(scenario === CHECKOUT_RECOVERY && checkoutUnpaid < 2 ? "offer_growth_questions" : "growth_ready"),
1264
+ cached,
1265
+ query_ms: queryMs,
1266
+ elapsed_ms: Math.max(0, deps.now() - started),
1267
+ poll_after_ms: 0
1268
+ };
1269
+ } catch (error) {
1270
+ if (signal.aborted || error instanceof Error && ["AbortError", "TimeoutError"].includes(error.name)) {
1271
+ return { ...base, phase: "pending", next_action: "retry_growth", poll_after_ms: 2e3 };
1272
+ }
1273
+ throw error;
1274
+ }
1275
+ });
1276
+ }
1277
+
1278
+ // src/core/onboarding/progress.ts
1279
+ var PROGRESS = "analysis.plg_onboarding.progress";
1280
+ var progressOrigins = /* @__PURE__ */ new Set([
1281
+ "https://ae-web.thinkingai.cn",
1282
+ "https://ae-web-global.thinkingai.io",
1283
+ `https://${OVERSEAS_TEST_PRODUCT_HOSTNAME}`
1284
+ ]);
1285
+ function isOnboardingProgressHost(host) {
1286
+ if (!host) return false;
1287
+ try {
1288
+ return progressOrigins.has(new URL(host).origin);
1289
+ } catch {
1290
+ return false;
1291
+ }
1292
+ }
1293
+ function writeProgress(deps, host, action, input) {
1294
+ return deps.capability(host, PROGRESS, { action, ...input }, AbortSignal.timeout(5e3));
1295
+ }
1296
+ async function readProgress(deps, host) {
1297
+ try {
1298
+ const result2 = await writeProgress(deps, host, "status", {});
1299
+ if (["disabled", "unavailable", "not_started", "in_progress", "completed"].includes(result2?.state)) return result2;
1300
+ return { state: "unavailable" };
1301
+ } catch (error) {
1302
+ return { state: error?.httpStatus === 404 || error?.code === "CAPABILITY_NOT_FOUND" ? "disabled" : "unavailable" };
1303
+ }
1304
+ }
1305
+ async function verifyAndCompleteProgress(deps, host, runId) {
1306
+ const progress = await readProgress(deps, host);
1307
+ if (progress.state !== "in_progress") return progress;
1308
+ const { receipt, experiment_id, journey_id, demo_project_id } = progress;
1309
+ if (progress.run_id !== runId || !receipt || !experiment_id || !journey_id || !demo_project_id) {
1310
+ throw new Error("The current Demo replay checkpoint is not ready. Resume the experiment in the session that started it.");
1311
+ }
1312
+ const call = (id, input) => deps.capability(host, id, input, AbortSignal.timeout(1e4));
1313
+ const source = await resolveEventSource(call, demo_project_id);
1314
+ const dates = replayReportDates(receipt);
1315
+ const shiftDate2 = (date2, days) => new Date(Date.parse(date2) + days * 864e5).toISOString().slice(0, 10);
1316
+ const expected = /* @__PURE__ */ new Set();
1317
+ const key = (event, group, account) => JSON.stringify([event, group, account]);
1318
+ for (const arm of Object.values(receipt.arms)) {
1319
+ for (const account of arm.exposed_account_ids) expected.add(key("te_experiment_exposure", arm.group_id, account));
1320
+ for (const account of arm.coupon_claim_account_ids) expected.add(key("demo_coupon_claim", "", account));
1321
+ for (const account of arm.paid_account_ids) expected.add(key("payment_success", "", account));
1322
+ }
1323
+ if (!expected.size) throw new Error("The Demo replay checkpoint contains no events.");
1324
+ const sql = `SELECT DISTINCT e."$part_event", CAST(${source.account} AS varchar),
1325
+ CASE WHEN e."$part_event" = 'te_experiment_exposure' THEN CAST(e.experiment_group_id AS varchar) ELSE '' END
1326
+ FROM ${source.from}
1327
+ WHERE e."$part_date" BETWEEN ${sqlString(shiftDate2(dates.start_time, -1))} AND ${sqlString(shiftDate2(dates.end_time, 1))}
1328
+ AND ((e."$part_event" = 'te_experiment_exposure' AND CAST(e.experiment_id AS varchar) = ${sqlString(experiment_id)})
1329
+ OR (e.demo_run_id = ${sqlString(runId)} AND e.plg_sample_id = ${sqlString(receipt.sample_id)}
1330
+ AND e.item_id = ${sqlString(receipt.item_id)}
1331
+ AND (e."$part_event" = 'demo_coupon_claim'
1332
+ OR (e."$part_event" = 'payment_success' AND e.currency = ${sqlString(receipt.currency)}))))`;
1333
+ const rows = await call("analysis.adhoc.run", {
1334
+ project_id: demo_project_id,
1335
+ model_type: "sql",
1336
+ definition: { sql },
1337
+ use_cache: false
1338
+ });
1339
+ if (rows?.has_more !== false || !Array.isArray(rows.rows)) {
1340
+ throw new Error("The Demo event query did not return a complete result.");
1341
+ }
1342
+ const found = new Set(rows.rows.map(([event, account, group]) => key(event, group, account)));
1343
+ if (found.size !== expected.size || [...expected].some((event) => !found.has(event))) return progress;
1344
+ return writeProgress(deps, host, "complete", { journey_id, run_id: runId, demo_project_id, experiment_id });
1345
+ }
318
1346
 
319
1347
  // src/core/installation.ts
320
1348
  import fs7 from "fs";
321
- import path7 from "path";
322
- import crypto3 from "crypto";
1349
+ import path9 from "path";
1350
+ import crypto4 from "crypto";
323
1351
 
324
1352
  // src/core/skills-install.ts
325
1353
  import fs2 from "fs";
326
1354
  import os from "os";
327
- import path2 from "path";
1355
+ import path3 from "path";
328
1356
  import { parseDocument } from "yaml";
329
1357
  var ON_DEMAND_SKILLS = /* @__PURE__ */ new Set(["ae-onboarding"]);
330
1358
  function readInstallableSkills(directory, select) {
331
1359
  return readBundledSkills(directory, (name) => !ON_DEMAND_SKILLS.has(name) && (!select || select(name)));
332
1360
  }
333
1361
  function globalSkillsDirectory() {
334
- return path2.join(os.homedir(), ".agents", "skills");
1362
+ return path3.join(os.homedir(), ".agents", "skills");
335
1363
  }
336
1364
  function skillName(content) {
337
1365
  const frontmatter = content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
@@ -343,12 +1371,12 @@ function skillName(content) {
343
1371
  return data.name;
344
1372
  }
345
1373
  function readFiles(root, prefix = "", files = /* @__PURE__ */ new Map()) {
346
- for (const entry of fs2.readdirSync(path2.join(root, prefix), { withFileTypes: true })) {
1374
+ for (const entry of fs2.readdirSync(path3.join(root, prefix), { withFileTypes: true })) {
347
1375
  if (entry.name.startsWith(".") || ["metadata.json", "__pycache__", "__pypackages__"].includes(entry.name)) continue;
348
- const relative = path2.join(prefix, entry.name);
1376
+ const relative = path3.join(prefix, entry.name);
349
1377
  if (entry.isSymbolicLink()) throw new Error("Bundled Skills must contain regular files.");
350
1378
  if (entry.isDirectory()) readFiles(root, relative, files);
351
- else if (entry.isFile()) files.set(relative, fs2.readFileSync(path2.join(root, relative)));
1379
+ else if (entry.isFile()) files.set(relative, fs2.readFileSync(path3.join(root, relative)));
352
1380
  }
353
1381
  return files;
354
1382
  }
@@ -359,14 +1387,14 @@ function readBundledSkills(directory, select) {
359
1387
  try {
360
1388
  let selectedName;
361
1389
  if (select) {
362
- const header = path2.join(directory, entry.name, "SKILL.md");
1390
+ const header = path3.join(directory, entry.name, "SKILL.md");
363
1391
  if (!fs2.lstatSync(header).isFile()) throw new Error("Bundled Skill metadata must be a regular file.");
364
1392
  selectedName = skillName(fs2.readFileSync(header, "utf8"));
365
1393
  if (names.has(selectedName)) throw new Error("Duplicate bundled Skill name.");
366
1394
  names.add(selectedName);
367
1395
  if (!select(selectedName)) return [];
368
1396
  }
369
- const files = readFiles(path2.join(directory, entry.name));
1397
+ const files = readFiles(path3.join(directory, entry.name));
370
1398
  const name = skillName(files.get("SKILL.md").toString("utf8"));
371
1399
  if (selectedName !== void 0 && selectedName !== name) throw new Error("Bundled Skill metadata changed.");
372
1400
  return [{ name, files }];
@@ -384,12 +1412,12 @@ function verifyGlobalSkills(skills, directory) {
384
1412
  return skills.flatMap((skill) => {
385
1413
  let reason = "";
386
1414
  try {
387
- const target = path2.join(directory, skill.name);
388
- if (skillName(fs2.readFileSync(path2.join(target, "SKILL.md"), "utf8")) !== skill.name) {
1415
+ const target = path3.join(directory, skill.name);
1416
+ if (skillName(fs2.readFileSync(path3.join(target, "SKILL.md"), "utf8")) !== skill.name) {
389
1417
  reason = "Installed Skill name does not match the bundled Skill.";
390
1418
  } else {
391
1419
  for (const [file, expected] of skill.files) {
392
- if (!fs2.readFileSync(path2.join(target, file)).equals(expected)) {
1420
+ if (!fs2.readFileSync(path3.join(target, file)).equals(expected)) {
393
1421
  reason = "Installed files do not match the CLI package version.";
394
1422
  break;
395
1423
  }
@@ -402,82 +1430,8 @@ function verifyGlobalSkills(skills, directory) {
402
1430
  });
403
1431
  }
404
1432
 
405
- // src/core/onboarding/contracts.ts
406
- var DEMO_CONTEXT = "project.plg_demo.context";
407
- var DEMO_ENSURE = "project.plg_demo.ensure";
408
- var DEMO_STATUS = "project.plg_demo.status";
409
- var RUN_BUDGET_MS = 45e3;
410
- var NETWORK_BUDGET_MS = 35e3;
411
- var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
412
- var DEMO_SAMPLE_IDS = ["star-island", "season-pass"];
413
- var CHECKOUT_RECOVERY = "checkout-recovery";
414
- function onboardingGrowthScenario(value) {
415
- if (value === void 0 || value === "item-coupon") return "item-coupon";
416
- if (value === CHECKOUT_RECOVERY) return CHECKOUT_RECOVERY;
417
- throw new Error("Use --scenario item-coupon or checkout-recovery.");
418
- }
419
-
420
- // src/core/website-entry.ts
421
- var LOGIN_PATHS = { jp: "/jp/experience-login/", kr: "/kr/experience-login/", us: "/en/experience-login/", cn: "/experience-login/" };
422
- var WEBSITE_MARKETS = Object.keys(LOGIN_PATHS);
423
- var PRODUCTION_ISSUER = "https://thinkingai.io";
424
- var PRODUCTION_BROWSER_ORIGIN = "https://www.thinkingai.io";
425
- var CHINA_PRODUCTION_ORIGIN = "https://www.thinkingai.cn";
426
- var UNSUPPORTED_MARKET = "Website onboarding is available in China, Japan, South Korea, and the United States. Use --region cn, jp, kr, or us.";
427
- function isWebsiteMarket(market) {
428
- return Object.hasOwn(LOGIN_PATHS, market);
429
- }
430
- function websiteEnvironment(value, env = process.env) {
431
- const selected = value ?? env.AE_CLI_WEBSITE_ENV ?? "production";
432
- if (selected !== "production") throw new Error("Website onboarding supports only the production environment.");
433
- return "production";
434
- }
435
- function websiteOrigin(market, environment) {
436
- websiteEnvironment(environment, {});
437
- if (!isWebsiteMarket(market)) throw new Error(UNSUPPORTED_MARKET);
438
- return market === "cn" ? CHINA_PRODUCTION_ORIGIN : PRODUCTION_ISSUER;
439
- }
440
- function isProductionWebsiteOrigin(origin) {
441
- return origin === PRODUCTION_ISSUER || origin === PRODUCTION_BROWSER_ORIGIN || origin === CHINA_PRODUCTION_ORIGIN;
442
- }
443
- function environmentForWebsiteOrigin(origin) {
444
- if (isProductionWebsiteOrigin(origin)) return "production";
445
- throw new Error("Untrusted onboarding website.");
446
- }
447
- function cliEntrySource(source, env = process.env) {
448
- const selected = source ?? (UUID_PATTERN.test(env.CODEX_THREAD_ID ?? "") ? "codex" : "other");
449
- if (!["codex", "cursor", "claude-code", "other"].includes(selected)) throw new Error("Unsupported local AI tool source.");
450
- return selected;
451
- }
452
- function cliToolReference(source, env = process.env) {
453
- return source === "codex" && UUID_PATTERN.test(env.CODEX_THREAD_ID ?? "") ? env.CODEX_THREAD_ID : void 0;
454
- }
455
- function withCliEntryContext(value, source, market, toolReference) {
456
- const url = new URL(value);
457
- if (url.protocol !== "https:" || url.username || url.password) throw new Error("Untrusted website continuation URL.");
458
- if ([...url.searchParams.keys()].some((key) => /^(device_code|poll_token|access_token|refresh_token|cli[_-]token|token)$/i.test(key))) {
459
- throw new Error("The website returned a private credential in its public continuation URL.");
460
- }
461
- const references = url.searchParams.getAll("tool_reference");
462
- if (references.length > 1 || references.some((reference) => !UUID_PATTERN.test(reference))) throw new Error("Invalid AI tool continuation reference.");
463
- url.searchParams.set("entry", "cli");
464
- url.searchParams.set("source", cliEntrySource(source));
465
- if (market && !url.searchParams.has("market")) url.searchParams.set("market", market);
466
- if (toolReference) {
467
- if (source !== "codex" || !UUID_PATTERN.test(toolReference)) throw new Error("Invalid AI tool continuation reference.");
468
- if (references.length && references[0] !== toolReference) throw new Error("The website returned a mismatched AI tool continuation reference.");
469
- if (!url.searchParams.has("tool_reference")) url.searchParams.set("tool_reference", toolReference);
470
- }
471
- return url.toString();
472
- }
473
- function websiteLoginUrl(market, environment, source, toolReference) {
474
- websiteEnvironment(environment, {});
475
- if (!isWebsiteMarket(market)) throw new Error(UNSUPPORTED_MARKET);
476
- const origin = market === "cn" ? CHINA_PRODUCTION_ORIGIN : PRODUCTION_BROWSER_ORIGIN;
477
- return withCliEntryContext(`${origin}${LOGIN_PATHS[market]}`, source, market, toolReference);
478
- }
479
-
480
1433
  // src/core/host-guidance.ts
1434
+ import path4 from "path";
481
1435
  function normalizeRegistrationLanguage(value) {
482
1436
  const language = value.trim().toLowerCase().split(/[_.:@-]/)[0];
483
1437
  if (language === "zh" || language === "cn") return "zh-CN";
@@ -485,11 +1439,32 @@ function normalizeRegistrationLanguage(value) {
485
1439
  if (language === "ko" || language === "kr") return "ko-KR";
486
1440
  return language === "en" ? "en-US" : void 0;
487
1441
  }
488
- function localRegistrationLanguage(env = process.env) {
489
- return normalizeRegistrationLanguage(env.AE_LANG || env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE || "");
1442
+ function terminalRegistrationLanguage(env) {
1443
+ const locale = [env.LC_ALL, env.LC_MESSAGES, env.LANG, env.LANGUAGE].map((value) => value?.trim()).find((value) => value && !/^(?:C|POSIX)(?:[.@].*)?$/i.test(value));
1444
+ return normalizeRegistrationLanguage(locale ?? "");
1445
+ }
1446
+ function localRegistrationLanguage(env = process.env, platform = process.platform, runner = defaultInstallRunner) {
1447
+ const override = normalizeRegistrationLanguage(env.AE_LANG ?? "");
1448
+ if (override) return override;
1449
+ let systemLocale;
1450
+ if (platform === "darwin") {
1451
+ const result2 = runner("/usr/bin/defaults", ["read", "-g", "AppleLanguages"], 1e3);
1452
+ if (commandSucceeded(result2)) {
1453
+ systemLocale = result2.stdout.match(/^\s*\(\s*"?([\w-]+)"?\s*[,)]/u)?.[1];
1454
+ }
1455
+ } else if (platform === "win32") {
1456
+ const powershell = path4.win32.join(env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
1457
+ const result2 = runner(powershell, ["-NoProfile", "-NonInteractive", "-Command", "(Get-UICulture).Name"], 2e3);
1458
+ if (commandSucceeded(result2)) systemLocale = result2.stdout.trim();
1459
+ }
1460
+ return systemLocale ? normalizeRegistrationLanguage(systemLocale) : terminalRegistrationLanguage(env);
1461
+ }
1462
+ function onboardingDeviceMarket(language) {
1463
+ return language === "zh-CN" ? "cn" : "us";
490
1464
  }
491
1465
  function registrationLanguage(language, env = process.env) {
492
- return (language ? normalizeRegistrationLanguage(language) : localRegistrationLanguage(env)) ?? "en-US";
1466
+ const locale = language || env.AE_LANG || env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE || "";
1467
+ return normalizeRegistrationLanguage(locale) ?? "en-US";
493
1468
  }
494
1469
  function registrationMarket(language) {
495
1470
  return { "zh-CN": "cn", "en-US": "us", "ja-JP": "jp", "ko-KR": "kr" }[language];
@@ -522,9 +1497,9 @@ function missingAeHostGuidance() {
522
1497
  }
523
1498
 
524
1499
  // src/core/business-config.ts
525
- import crypto2 from "crypto";
1500
+ import crypto3 from "crypto";
526
1501
  import fs6 from "fs";
527
- import path6 from "path";
1502
+ import path8 from "path";
528
1503
 
529
1504
  // src/core/skill-businesses.json
530
1505
  var skill_businesses_default = {
@@ -709,20 +1684,20 @@ function canManageGlobalSkills() {
709
1684
  }
710
1685
 
711
1686
  // src/core/business-skill-refresh.ts
712
- import crypto from "crypto";
1687
+ import crypto2 from "crypto";
713
1688
  import fs5 from "fs";
714
- import path5 from "path";
1689
+ import path7 from "path";
715
1690
 
716
1691
  // src/core/business-skill-sync.ts
717
1692
  import fs4 from "fs";
718
1693
  import os3 from "os";
719
- import path4 from "path";
1694
+ import path6 from "path";
720
1695
  import { createHash as createHash2, randomUUID } from "crypto";
721
1696
 
722
1697
  // src/core/skills-tool.ts
723
1698
  import fs3 from "fs";
724
1699
  import os2 from "os";
725
- import path3 from "path";
1700
+ import path5 from "path";
726
1701
  import { createHash } from "crypto";
727
1702
  import { createRequire, isBuiltin } from "module";
728
1703
  import { pathToFileURL } from "url";
@@ -748,25 +1723,25 @@ function realSkillPath(file) {
748
1723
  return fs3.realpathSync(file);
749
1724
  } catch (error) {
750
1725
  if (error.code !== "ENOENT") throw error;
751
- const parent = path3.dirname(file);
1726
+ const parent = path5.dirname(file);
752
1727
  if (parent === file) throw error;
753
- return path3.join(realSkillPath(parent), path3.basename(file));
1728
+ return path5.join(realSkillPath(parent), path5.basename(file));
754
1729
  }
755
1730
  }
756
1731
  function skillPathProblem(targetDirectory, skill, sourceRoot) {
757
1732
  try {
758
- const target = realSkillPath(path3.resolve(targetDirectory, skill));
759
- const source = realSkillPath(path3.resolve(sourceRoot));
760
- const overlaps = (a, b) => a === b || a.startsWith(b + path3.sep);
1733
+ const target = realSkillPath(path5.resolve(targetDirectory, skill));
1734
+ const source = realSkillPath(path5.resolve(sourceRoot));
1735
+ const overlaps = (a, b) => a === b || a.startsWith(b + path5.sep);
761
1736
  if (overlaps(target, source) || overlaps(source, target)) return "package_source_overlap";
762
- let parent = path3.resolve(targetDirectory);
1737
+ let parent = path5.resolve(targetDirectory);
763
1738
  while (true) {
764
1739
  try {
765
1740
  if (fs3.lstatSync(parent).isSymbolicLink()) return "copy_parent_linked";
766
1741
  } catch (error) {
767
1742
  if (error.code !== "ENOENT") throw error;
768
1743
  }
769
- const next = path3.dirname(parent);
1744
+ const next = path5.dirname(parent);
770
1745
  if (next === parent) return null;
771
1746
  parent = next;
772
1747
  }
@@ -783,13 +1758,13 @@ function skillCopyHash(directory, source = false) {
783
1758
  }
784
1759
  const hash = createHash("sha256");
785
1760
  const visit = (relative) => {
786
- for (const name of fs3.readdirSync(path3.join(directory, relative)).sort()) {
1761
+ for (const name of fs3.readdirSync(path5.join(directory, relative)).sort()) {
787
1762
  if (name === ".DS_Store") continue;
788
- const child = path3.join(relative, name);
789
- const absolute = path3.join(directory, child);
1763
+ const child = path5.join(relative, name);
1764
+ const absolute = path5.join(directory, child);
790
1765
  const stat = fs3.lstatSync(absolute);
791
1766
  if (source && (name === "metadata.json" || stat.isDirectory() && [".git", "__pycache__", "__pypackages__"].includes(name))) continue;
792
- const normalized = child.split(path3.sep).join("/");
1767
+ const normalized = child.split(path5.sep).join("/");
793
1768
  if (stat.isSymbolicLink()) throw new Error("Symbolic links are not managed Skill copies.");
794
1769
  if (stat.isDirectory()) {
795
1770
  hash.update(`directory:${normalized}\0`);
@@ -853,7 +1828,7 @@ function adaptedToolSource(source, entry) {
853
1828
  );
854
1829
  source = replaceOnce(source, "main().finally(() => flushTelemetry().then(() => process.exit(0)));", "");
855
1830
  const require2 = createRequire(entry);
856
- const resolveImport = (specifier) => isBuiltin(specifier) ? specifier : pathToFileURL(specifier.startsWith(".") ? path3.resolve(path3.dirname(entry), specifier) : require2.resolve(specifier)).href;
1831
+ const resolveImport = (specifier) => isBuiltin(specifier) ? specifier : pathToFileURL(specifier.startsWith(".") ? path5.resolve(path5.dirname(entry), specifier) : require2.resolve(specifier)).href;
857
1832
  source = source.replace(
858
1833
  /\bfrom (['"])([^'"]+)\1/g,
859
1834
  (_match, quote, specifier) => `from ${quote}${resolveImport(specifier)}${quote}`
@@ -1063,21 +2038,21 @@ catch { process.stdout.write(JSON.stringify({ ok: false })); process.exitCode =
1063
2038
  `;
1064
2039
  function createPinnedSkillsTool(options = {}) {
1065
2040
  const require2 = createRequire(import.meta.url);
1066
- const packageFile = options.entry ? path3.join(path3.dirname(options.entry), "..", "package.json") : require2.resolve("skills/package.json");
1067
- const entry = options.entry ?? path3.join(path3.dirname(packageFile), "dist", "cli.mjs");
2041
+ const packageFile = options.entry ? path5.join(path5.dirname(options.entry), "..", "package.json") : require2.resolve("skills/package.json");
2042
+ const entry = options.entry ?? path5.join(path5.dirname(packageFile), "dist", "cli.mjs");
1068
2043
  const metadata = JSON.parse(fs3.readFileSync(packageFile, "utf8"));
1069
2044
  const source = fs3.readFileSync(entry, "utf8");
1070
2045
  if (metadata.version !== MANAGED_SKILLS_TOOL_VERSION || createHash("sha256").update(source).digest("hex") !== TOOL_SOURCE_SHA256) {
1071
2046
  throw new Error("Managed Skill synchronization requires the verified skills@1.5.12 package.");
1072
2047
  }
1073
2048
  const script = adaptedToolSource(source, entry);
1074
- const run = (request) => {
1075
- const directory = fs3.mkdtempSync(path3.join(os2.tmpdir(), "ae-cli-skills-tool-"));
1076
- const worker = path3.join(directory, "adapter.mjs");
2049
+ const run = (request2) => {
2050
+ const directory = fs3.mkdtempSync(path5.join(os2.tmpdir(), "ae-cli-skills-tool-"));
2051
+ const worker = path5.join(directory, "adapter.mjs");
1077
2052
  try {
1078
2053
  fs3.writeFileSync(worker, script, { mode: 384 });
1079
2054
  const result2 = spawn2.sync(process.execPath, [worker], {
1080
- input: JSON.stringify(request),
2055
+ input: JSON.stringify(request2),
1081
2056
  encoding: "utf8",
1082
2057
  maxBuffer: 8 * 1024 * 1024,
1083
2058
  timeout: options.timeoutMs ?? 12e4,
@@ -1109,17 +2084,17 @@ var POLICY_HASH = createHash2("sha256").update(JSON.stringify({ removal_policy:
1109
2084
  function historicalCliSkills(options) {
1110
2085
  const env = options.env ?? process.env;
1111
2086
  const home = env.HOME || env.USERPROFILE || os3.homedir();
1112
- const file = env.XDG_STATE_HOME ? path4.join(env.XDG_STATE_HOME, "skills", ".skill-lock.json") : path4.join(home, ".agents", ".skill-lock.json");
2087
+ const file = env.XDG_STATE_HOME ? path6.join(env.XDG_STATE_HOME, "skills", ".skill-lock.json") : path6.join(home, ".agents", ".skill-lock.json");
1113
2088
  const names = /* @__PURE__ */ new Set();
1114
2089
  let content = "";
1115
2090
  const isCliSource = (value, type) => {
1116
2091
  if (typeof value !== "string") return false;
1117
- if (type === "local" && path4.isAbsolute(value)) {
1118
- const source2 = path4.resolve(value);
1119
- if (source2 === path4.resolve(options.skillsDirectory)) return true;
1120
- if (path4.basename(source2) !== "skills") return false;
2092
+ if (type === "local" && path6.isAbsolute(value)) {
2093
+ const source2 = path6.resolve(value);
2094
+ if (source2 === path6.resolve(options.skillsDirectory)) return true;
2095
+ if (path6.basename(source2) !== "skills") return false;
1121
2096
  try {
1122
- const pkg = JSON.parse(fs4.readFileSync(path4.join(source2, "..", "package.json"), "utf8"));
2097
+ const pkg = JSON.parse(fs4.readFileSync(path6.join(source2, "..", "package.json"), "utf8"));
1123
2098
  return ["@tant/ae-cli", "@thinkingai/ae-cli"].includes(pkg.name) && typeof pkg.bin?.["ae-cli"] === "string";
1124
2099
  } catch {
1125
2100
  return false;
@@ -1180,7 +2155,7 @@ function reserveBusinessSkillContext(options) {
1180
2155
  const directory = options.stateDirectory ?? getConfigDir();
1181
2156
  fs4.mkdirSync(directory, { recursive: true, mode: 448 });
1182
2157
  const generation = randomUUID();
1183
- writeJson(path4.join(directory, CONTEXT_FILE), { ...contextIdentity(options), generation });
2158
+ writeJson(path6.join(directory, CONTEXT_FILE), { ...contextIdentity(options), generation });
1184
2159
  return generation;
1185
2160
  }
1186
2161
  function currentContext(options, file, generation) {
@@ -1194,7 +2169,7 @@ function currentContext(options, file, generation) {
1194
2169
  }
1195
2170
  }
1196
2171
  function isBusinessSkillContextCurrent(options) {
1197
- return currentContext(options, path4.join(options.stateDirectory ?? getConfigDir(), CONTEXT_FILE), options.generation);
2172
+ return currentContext(options, path6.join(options.stateDirectory ?? getConfigDir(), CONTEXT_FILE), options.generation);
1198
2173
  }
1199
2174
  function takeLock(file) {
1200
2175
  const owner = randomUUID();
@@ -1210,7 +2185,7 @@ function takeLock(file) {
1210
2185
  };
1211
2186
  try {
1212
2187
  fs4.chmodSync(candidate, 448);
1213
- fs4.writeFileSync(path4.join(candidate, ownerName), JSON.stringify({ pid: process.pid, owner }), { mode: 384 });
2188
+ fs4.writeFileSync(path6.join(candidate, ownerName), JSON.stringify({ pid: process.pid, owner }), { mode: 384 });
1214
2189
  for (let attempt = 0; attempt < 4; attempt++) {
1215
2190
  try {
1216
2191
  fs4.renameSync(candidate, file);
@@ -1220,7 +2195,7 @@ function takeLock(file) {
1220
2195
  }
1221
2196
  return () => {
1222
2197
  try {
1223
- fs4.unlinkSync(path4.join(file, ownerName));
2198
+ fs4.unlinkSync(path6.join(file, ownerName));
1224
2199
  } catch {
1225
2200
  }
1226
2201
  try {
@@ -1265,7 +2240,7 @@ function takeLock(file) {
1265
2240
  }
1266
2241
  for (const name of names) {
1267
2242
  try {
1268
- fs4.unlinkSync(path4.join(file, name));
2243
+ fs4.unlinkSync(path6.join(file, name));
1269
2244
  } catch (cause) {
1270
2245
  if (cause.code !== "ENOENT") throw cause;
1271
2246
  }
@@ -1294,12 +2269,12 @@ function readLedger(file) {
1294
2269
  throw new Error("Managed Skill ledger has an unsupported format.");
1295
2270
  }
1296
2271
  for (const [filePath, copy] of Object.entries(value.copies)) {
1297
- if (!path4.isAbsolute(filePath) || !copy || typeof copy.skill !== "string" || typeof copy.agent !== "string" || !/^[a-f0-9]{64}$/.test(copy.hash) || typeof copy.package_version !== "string") throw new Error("Managed Skill ledger has an invalid copy.");
2272
+ if (!path6.isAbsolute(filePath) || !copy || typeof copy.skill !== "string" || typeof copy.agent !== "string" || !/^[a-f0-9]{64}$/.test(copy.hash) || typeof copy.package_version !== "string") throw new Error("Managed Skill ledger has an invalid copy.");
1298
2273
  }
1299
2274
  return value;
1300
2275
  }
1301
2276
  function result(skill, target, reason) {
1302
- return { skill, agent: target.agent, path: path4.join(target.directory, skill), ...reason ? { reason } : {} };
2277
+ return { skill, agent: target.agent, path: path6.join(target.directory, skill), ...reason ? { reason } : {} };
1303
2278
  }
1304
2279
  function directInstallerLink(file, target, text) {
1305
2280
  if (typeof text !== "string") return false;
@@ -1307,14 +2282,14 @@ function directInstallerLink(file, target, text) {
1307
2282
  if (process.platform === "win32") {
1308
2283
  if (value.toUpperCase().startsWith("\\\\?\\UNC\\")) value = "\\\\" + value.slice(8);
1309
2284
  else if (value.startsWith("\\\\?\\") || value.startsWith("\\??\\")) value = value.slice(4);
1310
- return [target, path4.relative(path4.dirname(file), target)].some((expected) => value.toLowerCase() === expected.toLowerCase());
2285
+ return [target, path6.relative(path6.dirname(file), target)].some((expected) => value.toLowerCase() === expected.toLowerCase());
1311
2286
  }
1312
- return value === target || value === path4.relative(path4.dirname(file), target);
2287
+ return value === target || value === path6.relative(path6.dirname(file), target);
1313
2288
  }
1314
2289
  function legacySkillLink(file, skill, sourceRoot, sourceHash, targets, ledger, removing = false) {
1315
2290
  const canonical = targets.find((target2) => target2.agent === "universal");
1316
2291
  if (!canonical) return;
1317
- const target = path4.join(canonical.directory, skill);
2292
+ const target = path6.join(canonical.directory, skill);
1318
2293
  const managed = ledger.copies[target];
1319
2294
  if (!managed || managed.skill !== skill || managed.agent !== canonical.agent || !removing && managed.hash !== sourceHash || skillPathProblem(canonical.directory, skill, sourceRoot)) return;
1320
2295
  try {
@@ -1338,7 +2313,7 @@ function syncBusinessSkills(options) {
1338
2313
  managed_count: 0
1339
2314
  };
1340
2315
  const directory = options.stateDirectory ?? getConfigDir();
1341
- const contextFile = path4.join(directory, CONTEXT_FILE);
2316
+ const contextFile = path6.join(directory, CONTEXT_FILE);
1342
2317
  let unlock = null;
1343
2318
  try {
1344
2319
  if (options.isCurrentContext && !options.isCurrentContext()) {
@@ -1351,7 +2326,7 @@ function syncBusinessSkills(options) {
1351
2326
  report.status = "stale";
1352
2327
  return report;
1353
2328
  }
1354
- unlock = takeLock(path4.join(directory, LOCK_FILE));
2329
+ unlock = takeLock(path6.join(directory, LOCK_FILE));
1355
2330
  if (!unlock) {
1356
2331
  report.status = "busy";
1357
2332
  return report;
@@ -1360,7 +2335,7 @@ function syncBusinessSkills(options) {
1360
2335
  report.status = "stale";
1361
2336
  return report;
1362
2337
  }
1363
- const ledgerFile = path4.join(directory, LEDGER_FILE);
2338
+ const ledgerFile = path6.join(directory, LEDGER_FILE);
1364
2339
  const ledger = readLedger(ledgerFile);
1365
2340
  const packageVersion = options.packageVersion ?? "unknown";
1366
2341
  const history = historicalCliSkills(options);
@@ -1414,7 +2389,7 @@ function syncBusinessSkills(options) {
1414
2389
  for (const name of skills) {
1415
2390
  const state = getSkillBusinessState(name, options.businesses);
1416
2391
  if (options.mode !== "adopt" && state === void 0) continue;
1417
- const source = path4.join(options.skillsDirectory, name);
2392
+ const source = path6.join(options.skillsDirectory, name);
1418
2393
  const sourceHash = bundled.some((skill) => skill.name === name) ? skillCopyHash(source, true) : null;
1419
2394
  if (!sourceHash && options.mode === "adopt") throw new Error("Complete package Skill source is missing.");
1420
2395
  for (const target of targets) {
@@ -1439,7 +2414,7 @@ function syncBusinessSkills(options) {
1439
2414
  }
1440
2415
  const legacyLink2 = node.type === "symlink" ? legacySkillLink(item.path, name, options.skillsDirectory, sourceHash ?? "", targets, ledger, true) : void 0;
1441
2416
  const canonical = targets.find((copy) => copy.agent === "universal");
1442
- const historicalLink = node.type === "symlink" && canonical && directInstallerLink(item.path, path4.join(canonical.directory, name), node.link);
2417
+ const historicalLink = node.type === "symlink" && canonical && directInstallerLink(item.path, path6.join(canonical.directory, name), node.link);
1443
2418
  const historicalCopy = history.names.has(name) && (target.agent === "universal" && node.type !== "symlink" || historicalLink);
1444
2419
  if (!managed && (legacyLink2 || historicalCopy)) {
1445
2420
  ledger.copies[item.path] = {
@@ -1587,7 +2562,7 @@ function beginBusinessSkillRefresh(host, token, enabled = true) {
1587
2562
  }
1588
2563
  };
1589
2564
  if (!isCurrentContext()) return void 0;
1590
- const identity = { host: normalized, tokenFingerprint: crypto.createHash("sha256").update(token).digest("hex") };
2565
+ const identity = { host: normalized, tokenFingerprint: crypto2.createHash("sha256").update(token).digest("hex") };
1591
2566
  return { ...identity, generation: reserveBusinessSkillContext(identity), isCurrentContext };
1592
2567
  } catch {
1593
2568
  return void 0;
@@ -1602,8 +2577,8 @@ function syncRefreshedBusinessSkills(refresh, businesses) {
1602
2577
  if (!Object.keys(states).length) return;
1603
2578
  try {
1604
2579
  const pkg = getLocalCliPackageInfo();
1605
- const options = { ...refresh, skillsDirectory: path5.join(pkg.root, "skills"), businesses: states, packageVersion: pkg.version };
1606
- if (!fs5.existsSync(path5.join(getConfigDir(), "business-skills.json"))) {
2580
+ const options = { ...refresh, skillsDirectory: path7.join(pkg.root, "skills"), businesses: states, packageVersion: pkg.version };
2581
+ if (!fs5.existsSync(path7.join(getConfigDir(), "business-skills.json"))) {
1607
2582
  const adoption = syncBusinessSkills({ ...options, mode: "adopt" });
1608
2583
  if (["failed", "busy", "stale"].includes(adoption.status)) {
1609
2584
  if (adoption.status !== "stale") process.stderr.write("[ae-cli] Skills could not be synchronized. Retry: ae-cli config refresh\n");
@@ -1623,10 +2598,10 @@ function syncRefreshedBusinessSkills(refresh, businesses) {
1623
2598
  var BUSINESS_CONFIG_TTL_MS = 10 * 60 * 1e3;
1624
2599
  var UNAVAILABLE_TTL_MS = 5 * 60 * 1e3;
1625
2600
  function cachePath() {
1626
- return path6.join(getConfigDir(), "business-config.json");
2601
+ return path8.join(getConfigDir(), "business-config.json");
1627
2602
  }
1628
2603
  function cacheKey(host, token) {
1629
- return `${normalizeUrl(host)}#${crypto2.createHash("sha256").update(token).digest("hex")}`;
2604
+ return `${normalizeUrl(host)}#${crypto3.createHash("sha256").update(token).digest("hex")}`;
1630
2605
  }
1631
2606
  function readStore() {
1632
2607
  try {
@@ -1640,9 +2615,9 @@ function remember(host, token, entry) {
1640
2615
  const store = readStore();
1641
2616
  store.entries[cacheKey(host, token)] = entry;
1642
2617
  const target = cachePath();
1643
- const temporary = `${target}.${process.pid}.${crypto2.randomBytes(6).toString("hex")}.tmp`;
2618
+ const temporary = `${target}.${process.pid}.${crypto3.randomBytes(6).toString("hex")}.tmp`;
1644
2619
  try {
1645
- fs6.mkdirSync(path6.dirname(target), { recursive: true });
2620
+ fs6.mkdirSync(path8.dirname(target), { recursive: true });
1646
2621
  fs6.writeFileSync(temporary, JSON.stringify(store), { encoding: "utf8", mode: 384 });
1647
2622
  fs6.renameSync(temporary, target);
1648
2623
  fs6.chmodSync(target, 384);
@@ -1717,7 +2692,7 @@ async function readBusinessConfigForExecution(hostOverride, synchronizeSkills =
1717
2692
  const token = peekCliToken(host);
1718
2693
  if (!token) return {};
1719
2694
  return await resolveBusinessConfig(host, token, async () => {
1720
- const { fetchCliConfig: fetchCliConfig2 } = await import("./compat-check-7VBBE7KO.js");
2695
+ const { fetchCliConfig: fetchCliConfig2 } = await import("./compat-check-J5K3NO5G.js");
1721
2696
  return fetchCliConfig2(host, token);
1722
2697
  }, Date.now(), synchronizeSkills);
1723
2698
  } catch {
@@ -1731,6 +2706,14 @@ async function assertBusinessEnabled(business, hostOverride, synchronizeSkills =
1731
2706
  }
1732
2707
 
1733
2708
  // src/core/installation.ts
2709
+ var accountChoice = {
2710
+ step: "choose_account",
2711
+ question: "How would you like to connect to AE?",
2712
+ options: [
2713
+ { value: "create_account", label: "Create an AE account" },
2714
+ { value: "existing_account", label: "Sign in to my existing AE account" }
2715
+ ]
2716
+ };
1734
2717
  function distribution(packageName) {
1735
2718
  if (packageName === "@thinkingai/ae-cli") return { registry: "https://registry.npmjs.org", repository: "ThinkingAIAgenticEngine/ae-cli" };
1736
2719
  if (packageName === "@tant/ae-cli") return { registry: "https://npm.thinkingdata.cn:3443", repository: "http://10.27.249.150:8888/te-ai/te-cli.git" };
@@ -1740,6 +2723,10 @@ function newInstallationReport(packageName, version, dryRun = false) {
1740
2723
  return {
1741
2724
  ok: false,
1742
2725
  dry_run: dryRun,
2726
+ // Keep the next interaction and detected language visible before Skill synchronization details.
2727
+ next_action: void 0,
2728
+ interaction: void 0,
2729
+ local_language: void 0,
1743
2730
  cli: { package: packageName, version, path: null, entrypoint: null, verified: false, action: "pending", warnings: [] },
1744
2731
  skills: {
1745
2732
  directory: globalSkillsDirectory(),
@@ -1765,7 +2752,7 @@ function failInstallation(report, stage, message, cause = "validation") {
1765
2752
  function installPlan(packageName, version, root = "<npm-root>") {
1766
2753
  const config = distribution(packageName);
1767
2754
  const target = exactVersion(version);
1768
- const executable = path7.join(root, packageName, "bin", "ae-cli.js");
2755
+ const executable = path9.join(root, packageName, "bin", "ae-cli.js");
1769
2756
  return [
1770
2757
  `npm install -g ${packageName}@${target} --registry=${config.registry}`,
1771
2758
  `node ${JSON.stringify(executable)} install`
@@ -1774,7 +2761,7 @@ function installPlan(packageName, version, root = "<npm-root>") {
1774
2761
  function currentSkillIdentity() {
1775
2762
  const host = getActiveHost();
1776
2763
  const token = host ? peekCliToken(host) : void 0;
1777
- return { host, tokenFingerprint: token ? crypto3.createHash("sha256").update(token).digest("hex") : "" };
2764
+ return { host, tokenFingerprint: token ? crypto4.createHash("sha256").update(token).digest("hex") : "" };
1778
2765
  }
1779
2766
  function skipGlobalSkillReason() {
1780
2767
  try {
@@ -1785,7 +2772,7 @@ function skipGlobalSkillReason() {
1785
2772
  }
1786
2773
  function readPackage(root) {
1787
2774
  try {
1788
- return JSON.parse(fs7.readFileSync(path7.join(root, "package.json"), "utf8"));
2775
+ return JSON.parse(fs7.readFileSync(path9.join(root, "package.json"), "utf8"));
1789
2776
  } catch {
1790
2777
  return null;
1791
2778
  }
@@ -1798,13 +2785,13 @@ function linked(root) {
1798
2785
  }
1799
2786
  }
1800
2787
  function cliBinBelongsToPackage(bin, packageRoot, platform) {
1801
- const entry = fs7.realpathSync(path7.join(packageRoot, "bin", "ae-cli.js"));
2788
+ const entry = fs7.realpathSync(path9.join(packageRoot, "bin", "ae-cli.js"));
1802
2789
  if (platform !== "win32") return fs7.realpathSync(bin) === entry;
1803
2790
  const shim = fs7.readFileSync(bin, "utf8");
1804
2791
  const targets = [...shim.matchAll(/"%(?:dp0%|~dp0)[\\/]([^"\r\n]+)"/gi)];
1805
2792
  return targets.some(([, relative]) => {
1806
2793
  try {
1807
- const target = path7.resolve(path7.dirname(bin), relative.replace(/\\/g, path7.sep));
2794
+ const target = path9.resolve(path9.dirname(bin), relative.replace(/\\/g, path9.sep));
1808
2795
  return fs7.realpathSync(target).toLowerCase() === entry.toLowerCase();
1809
2796
  } catch {
1810
2797
  return false;
@@ -1846,9 +2833,9 @@ function runInstallation(options = {}) {
1846
2833
  const prefixResult = runner(npm, ["prefix", "-g"], 15e3);
1847
2834
  const globalRoot = rootResult.stdout.trim();
1848
2835
  const prefix = prefixResult.stdout.trim();
1849
- if (!commandSucceeded(rootResult) || !commandSucceeded(prefixResult) || !path7.isAbsolute(globalRoot) || !path7.isAbsolute(prefix) || /[\r\n]/.test(globalRoot + prefix)) return failInstallation(report, stage, "Cannot resolve npm global root and prefix. Check npm configuration.");
1850
- const packageRoot = path7.join(globalRoot, packageName);
1851
- const bin = platform === "win32" ? path7.join(prefix, "ae-cli.cmd") : path7.join(prefix, "bin", "ae-cli");
2836
+ if (!commandSucceeded(rootResult) || !commandSucceeded(prefixResult) || !path9.isAbsolute(globalRoot) || !path9.isAbsolute(prefix) || /[\r\n]/.test(globalRoot + prefix)) return failInstallation(report, stage, "Cannot resolve npm global root and prefix. Check npm configuration.");
2837
+ const packageRoot = path9.join(globalRoot, packageName);
2838
+ const bin = platform === "win32" ? path9.join(prefix, "ae-cli.cmd") : path9.join(prefix, "bin", "ae-cli");
1852
2839
  report.cli.path = bin;
1853
2840
  const env = options.env ?? process.env;
1854
2841
  const installedBefore = readPackage(packageRoot);
@@ -1871,8 +2858,8 @@ function runInstallation(options = {}) {
1871
2858
  };
1872
2859
  const generation = reserveBusinessSkillContext({ ...identity, stateDirectory });
1873
2860
  context = { ...identity, stateDirectory, generation, isCurrentContext };
1874
- if (!fs7.existsSync(path7.join(stateDirectory, "business-skills.json")) && installedBefore?.name === packageName) {
1875
- const previousSkills = path7.join(packageRoot, "skills");
2861
+ if (!fs7.existsSync(path9.join(stateDirectory, "business-skills.json")) && installedBefore?.name === packageName) {
2862
+ const previousSkills = path9.join(packageRoot, "skills");
1876
2863
  try {
1877
2864
  readInstallableSkills(previousSkills);
1878
2865
  syncSkills({ ...context, skillsDirectory: previousSkills, businesses: {}, mode: "adopt", packageVersion: installedBefore.version });
@@ -1901,12 +2888,12 @@ function runInstallation(options = {}) {
1901
2888
  if (!cliBinBelongsToPackage(bin, packageRoot, platform)) return failInstallation(report, stage, "The global executable does not belong to the installed CLI package.");
1902
2889
  const versionResult = runner(bin, ["--version"], 15e3);
1903
2890
  if (!commandSucceeded(versionResult) || versionResult.stdout.trim() !== target) return failInstallation(report, stage, "ae-cli --version did not return the requested version. Refresh the shell command cache and check npm bin links.");
1904
- report.cli.entrypoint = fs7.realpathSync(path7.join(packageRoot, "bin", "ae-cli.js"));
2891
+ report.cli.entrypoint = fs7.realpathSync(path9.join(packageRoot, "bin", "ae-cli.js"));
1905
2892
  report.cli.verified = true;
1906
2893
  const pathKey = platform === "win32" ? Object.keys(env).find((key) => key.toLowerCase() === "path") : "PATH";
1907
- const installedPathBin = (env[pathKey ?? "PATH"] ?? "").split(platform === "win32" ? ";" : path7.delimiter).filter(Boolean).map((dir) => path7.join(dir.replace(/^"(.*)"$/, "$1"), platform === "win32" ? "ae-cli.cmd" : "ae-cli")).find((file) => fs7.existsSync(file) && !file.includes(`${path7.sep}_npx${path7.sep}`));
2894
+ const installedPathBin = (env[pathKey ?? "PATH"] ?? "").split(platform === "win32" ? ";" : path9.delimiter).filter(Boolean).map((dir) => path9.join(dir.replace(/^"(.*)"$/, "$1"), platform === "win32" ? "ae-cli.cmd" : "ae-cli")).find((file) => fs7.existsSync(file) && !file.includes(`${path9.sep}_npx${path9.sep}`));
1908
2895
  if (!installedPathBin || fs7.realpathSync(installedPathBin) !== fs7.realpathSync(bin)) {
1909
- report.cli.warnings.push(`Add ${path7.dirname(bin)} to the front of PATH and refresh the shell command cache. The absolute executable was verified.`);
2896
+ report.cli.warnings.push(`Add ${path9.dirname(bin)} to the front of PATH and refresh the shell command cache. The absolute executable was verified.`);
1910
2897
  report.next_steps.push(`Use the verified executable at ${bin}, or correct PATH before invoking ae-cli.`);
1911
2898
  }
1912
2899
  if (skipSkills) {
@@ -1915,7 +2902,7 @@ function runInstallation(options = {}) {
1915
2902
  progress(`[ae-cli] [3/4] ${skipSkills}`);
1916
2903
  } else if (context) {
1917
2904
  stage = "skills_local";
1918
- const skillsPath = path7.join(packageRoot, "skills");
2905
+ const skillsPath = path9.join(packageRoot, "skills");
1919
2906
  const skills = readInstallableSkills(skillsPath);
1920
2907
  if (!isBusinessSkillContextCurrent(context)) {
1921
2908
  return failInstallation(report, stage, "The active environment changed during CLI installation. Re-run install or update to synchronize its Skills.");
@@ -1971,35 +2958,48 @@ function runInstallation(options = {}) {
1971
2958
  report.ok = true;
1972
2959
  return report;
1973
2960
  }
1974
- const localLanguage = localRegistrationLanguage(env);
1975
- const language = localLanguage ?? "en-US";
1976
- const market = registrationMarket(language);
1977
2961
  if (guideAccountSetup) {
2962
+ const localLanguage = localRegistrationLanguage(env, platform, runner);
1978
2963
  if (localLanguage) report.local_language = localLanguage;
1979
- report.next_steps.push("If the user only requested installation, report the verified version and Skill count and finish.");
1980
- if (report.auth.authenticated === true) report.next_action = "continue_using_ae";
1981
- else if (report.auth.warnings.length > 0) report.next_action = "check_authentication";
2964
+ report.onboarding_market = onboardingDeviceMarket(localLanguage);
2965
+ const onboardingSkillPath = path9.join(packageRoot, "skills", "ae-onboarding", "SKILL.md");
2966
+ if (fs7.existsSync(onboardingSkillPath)) report.onboarding_skill_path = onboardingSkillPath;
2967
+ if (report.auth.authenticated === true) {
2968
+ report.next_action = isOnboardingProgressHost(report.auth.host ?? void 0) ? "check_onboarding" : "continue_using_ae";
2969
+ } else if (report.auth.warnings.length > 0) report.next_action = "check_authentication";
1982
2970
  else report.next_action = "choose_account";
1983
2971
  }
1984
2972
  if (report.auth.authenticated === true) {
1985
- report.next_steps.push("You are signed in. Continue your AE task in this AI tool using the existing environment.");
2973
+ if (report.next_action === "check_onboarding") {
2974
+ report.next_steps.push("Check the signed-in account with ae-cli analysis onboarding progress --format json. Offer the current Demo only for not_started or in_progress. Continue the user\u2019s specific AE task first when one was requested.");
2975
+ } else {
2976
+ report.next_steps.push("You are signed in. Continue your AE task in this AI tool using the existing environment.");
2977
+ }
1986
2978
  } else if (report.next_action === "check_authentication") {
1987
2979
  const hostOption = report.auth.host ? ` --host ${report.auth.host}` : "";
1988
2980
  report.next_steps.push(`Check the configured AE environment with ae-cli auth status${hostOption} --format json. If it still cannot be verified, confirm the intended environment before starting signup or login.`);
1989
2981
  } else {
1990
2982
  const chooseAccount = report.next_action === "choose_account";
1991
2983
  if (chooseAccount) {
1992
- report.next_steps.push("If the user explicitly asks for AE onboarding or a walkthrough and has left the account route open, show the account picker with \u201CGet started\u201D, \u201CSign in to my existing account\u201D, and \u201CNot now\u201D. For an explicit signup request, use website onboarding. For an explicit existing-account login request, use the original AE environment.");
2984
+ report.interaction = accountChoice;
2985
+ report.next_steps.push(
2986
+ "After verifying a fresh install, when the user has left the account route open, offer \u201CCreate an AE account\u201D and \u201CSign in to my existing AE account\u201D in the user\u2019s language. In an AI Agent, show these options in the same turn using the native choice dialog, even for a request that only asks to install. Keep the turn open until the user chooses or dismisses the dialog. If the dialog is unavailable or fails, ask with the same options in chat. A supplied host only identifies the environment. Wait for the account choice before starting signup or device authorization. For an explicit existing-account login request, use the original AE environment."
2987
+ );
2988
+ report.next_steps.push("For an explicit onboarding or walkthrough that needs a new account, show \u201CCreate an AE account\u201D and \u201CLearn about AE\u201D using the localized labels from references/about-ae.md next to onboarding_skill_path. If they choose \u201CLearn about AE\u201D, show the localized introduction and available product resources from that reference. Offer \u201CCreate an AE account\u201D and wait for their choice.");
1993
2989
  }
1994
2990
  if (chooseAccount || !report.auth.host) {
1995
2991
  const source = cliEntrySource(void 0, env);
1996
- const registration = aeRegistrationUrl(language, env, source);
1997
2992
  if (chooseAccount) {
1998
- report.next_steps.push(`For website onboarding, run ae-cli analysis onboarding run --language ${language} --source ${source} --browser system --format json. Pass --region for the user's requested market. The CLI opens the system default browser. If it cannot open the page, share the returned login_url for that browser. Read the returned skill_path and continue with its session_id. For manual signup outside the guided session, use ${registration}.`);
2993
+ report.next_steps.push(`After the user confirms signup in the overseas test environment, run ae-cli analysis onboarding run --website-env test --region us --source ${source} --browser system --format json. Use jp or kr for the corresponding requested test market and keep the returned session_id.`);
2994
+ report.next_steps.push(
2995
+ "For production signup, honor an explicitly requested or confirmed market first. Otherwise compare local_language with the language of the user\u2019s own request, excluding commands, links, quoted text, and picker labels. Map Chinese to cn, English to us, Japanese to jp, and Korean to kr. If both signals agree or only one maps to a market, use that market. When the two markets differ, show only those two options and wait. Use us if neither language maps to a market.",
2996
+ `After the user chooses \u201CCreate an AE account\u201D or directly asks to sign up, run ae-cli analysis onboarding run --region <market> --source ${source} --browser system --format json with the resolved market. Pass --language separately for the display preference. If the browser cannot open, share the returned login_url. Read the returned skill_path and resume with its session_id after sign-in.`
2997
+ );
1999
2998
  } else {
2999
+ const language = registrationLanguage(void 0, env);
3000
+ const registration = aeRegistrationUrl(language, env, source);
2000
3001
  report.next_steps.push(`New or returning website users: for guided website verification, run ae-cli analysis onboarding run --language ${language} --source ${source} --browser system. For manual registration or sign-in, use ${registration} in the system default browser.`);
2001
3002
  }
2002
- report.next_steps.push(`The default new-account region is ${market}. Use the user's explicit market when supplied. If the local language and the request language suggest different markets, offer exactly those two markets. For Chinese and English, offer China and the United States. Website onboarding supports --region cn|jp|kr|us. Language does not change an existing account's environment.`);
2003
3003
  }
2004
3004
  if (chooseAccount) report.next_steps.push("Existing AE users: confirm their original AE environment URL and use it for login. Ask for that URL if it is unknown.");
2005
3005
  else if (!report.auth.host) report.next_steps.push("Existing AE users: use your original environment URL, or ask your administrator.");
@@ -2021,10 +3021,10 @@ var LOCK_STALE_MS = 10 * 60 * 1e3;
2021
3021
  var SYNC_STATE_FILE = "version-sync.json";
2022
3022
  var SYNC_LOCK_FILE = "version-sync.lock";
2023
3023
  function syncStatePath() {
2024
- return path8.join(getConfigDir(), SYNC_STATE_FILE);
3024
+ return path10.join(getConfigDir(), SYNC_STATE_FILE);
2025
3025
  }
2026
3026
  function syncLockPath() {
2027
- return path8.join(getConfigDir(), SYNC_LOCK_FILE);
3027
+ return path10.join(getConfigDir(), SYNC_LOCK_FILE);
2028
3028
  }
2029
3029
  function readSyncStore() {
2030
3030
  try {
@@ -2231,16 +3231,16 @@ function autoSyncDirection(current, expected) {
2231
3231
  }
2232
3232
 
2233
3233
  // src/core/feature-config.ts
2234
- import crypto4 from "crypto";
3234
+ import crypto5 from "crypto";
2235
3235
  import fs9 from "fs";
2236
- import path9 from "path";
3236
+ import path11 from "path";
2237
3237
  var FEATURE_TTL_MS = 24 * 60 * 60 * 1e3;
2238
3238
  var UNAVAILABLE_TTL_MS2 = 5 * 60 * 1e3;
2239
3239
  function cachePath2() {
2240
- return path9.join(getConfigDir(), "feature-config.json");
3240
+ return path11.join(getConfigDir(), "feature-config.json");
2241
3241
  }
2242
3242
  function cacheKey2(host, token) {
2243
- const fingerprint = crypto4.createHash("sha256").update(token).digest("hex");
3243
+ const fingerprint = crypto5.createHash("sha256").update(token).digest("hex");
2244
3244
  return `${normalizeUrl(host)}#${fingerprint}`;
2245
3245
  }
2246
3246
  function readStore2() {
@@ -2253,9 +3253,9 @@ function readStore2() {
2253
3253
  }
2254
3254
  function writeStore(store) {
2255
3255
  const target = cachePath2();
2256
- const temp = `${target}.${process.pid}.${crypto4.randomBytes(6).toString("hex")}.tmp`;
3256
+ const temp = `${target}.${process.pid}.${crypto5.randomBytes(6).toString("hex")}.tmp`;
2257
3257
  try {
2258
- fs9.mkdirSync(path9.dirname(target), { recursive: true });
3258
+ fs9.mkdirSync(path11.dirname(target), { recursive: true });
2259
3259
  fs9.writeFileSync(temp, JSON.stringify(store), { encoding: "utf8", mode: 384 });
2260
3260
  fs9.renameSync(temp, target);
2261
3261
  fs9.chmodSync(target, 384);
@@ -2308,7 +3308,7 @@ var NOTIFY_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2308
3308
  var FETCH_TIMEOUT_MS = 3e3;
2309
3309
  var CLI_CONFIG_PATH = "/v1/ta/cli/config";
2310
3310
  function cacheFilePath() {
2311
- return path10.join(getConfigDir(), "compat-check.json");
3311
+ return path12.join(getConfigDir(), "compat-check.json");
2312
3312
  }
2313
3313
  function readStore3() {
2314
3314
  try {
@@ -2667,15 +3667,41 @@ export {
2667
3667
  UUID_PATTERN,
2668
3668
  DEMO_SAMPLE_IDS,
2669
3669
  CHECKOUT_RECOVERY,
3670
+ OVERSEAS_TEST_PRODUCT_HOSTNAME,
3671
+ onboardingDemoCurrency,
2670
3672
  onboardingGrowthScenario,
3673
+ replayReportDates,
3674
+ waitForExperimentSampleSize,
2671
3675
  WEBSITE_MARKETS,
3676
+ OVERSEAS_TEST_MARKETS,
3677
+ OVERSEAS_TEST_WEBSITE_ORIGIN,
3678
+ isWebsiteMarket,
2672
3679
  websiteEnvironment,
2673
3680
  websiteOrigin,
2674
3681
  isProductionWebsiteOrigin,
2675
- environmentForWebsiteOrigin,
2676
3682
  cliEntrySource,
2677
- withCliEntryContext,
3683
+ bootstrapOrigin,
3684
+ trustedProductHost,
3685
+ createBootstrap,
3686
+ readBootstrap,
3687
+ claimBootstrapDevice,
3688
+ normalizeResourceUrlFields,
3689
+ normalizeResourceUrls,
3690
+ resolvePublicWebHost,
3691
+ onboardingDraftReviewInteraction,
3692
+ onboardingDemoOverview,
3693
+ onboardingInteraction,
3694
+ onboardingEvidenceLinks,
3695
+ onboardingExperimentUrl,
3696
+ readCheckoutRecoveryCohort,
3697
+ runOnboardingGrowth,
3698
+ isOnboardingProgressHost,
3699
+ writeProgress,
3700
+ readProgress,
3701
+ verifyAndCompleteProgress,
2678
3702
  normalizeRegistrationLanguage,
3703
+ localRegistrationLanguage,
3704
+ onboardingDeviceMarket,
2679
3705
  registrationLanguage,
2680
3706
  registrationMarket,
2681
3707
  aeRegistrationUrl,