@thinkingai/ae-cli 6.1.39 → 6.1.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/cli-installation-guide.md +17 -10
- package/dist/{ai-monitor-DST4NDOK.js → ai-monitor-OOOD4QDK.js} +5 -7
- package/dist/ai-monitor.js +6 -8
- package/dist/{auth-BD3NIY3T.js → auth-6BUUY5XS.js} +4 -4
- package/dist/{capability-3NJOQHZQ.js → capability-XXFCANX7.js} +8 -10
- package/dist/{chunk-FRJUB66C.js → chunk-5YQSCMGS.js} +2 -2
- package/dist/{chunk-KBJHBVO7.js → chunk-6W56UQPO.js} +1 -1
- package/dist/{chunk-TVSGS5QB.js → chunk-BEVWMPCZ.js} +6 -6
- package/dist/{chunk-WRYXVIJP.js → chunk-DZRQGI2Z.js} +1 -1
- package/dist/{chunk-VXKKTUU2.js → chunk-EHH3ZF7D.js} +2 -2
- package/dist/{chunk-IY5G42YY.js → chunk-FPPCXG6K.js} +2 -2
- package/dist/{chunk-SQEK6S4X.js → chunk-I7H72CMN.js} +1182 -178
- package/dist/{chunk-24DCOJBJ.js → chunk-KDRE7SWM.js} +2 -2
- package/dist/{chunk-STHIGWWC.js → chunk-WG27BD67.js} +75 -4
- package/dist/{compat-check-7VBBE7KO.js → compat-check-AO3BFA3N.js} +2 -2
- package/dist/{config-LFRZBPH5.js → config-N5V4VNER.js} +4 -4
- package/dist/index.js +28 -31
- package/dist/{metadata-AR64J76Z.js → metadata-OUJPEMLD.js} +5 -7
- package/dist/{personal-semantic-preference-BCOSI4DO.js → personal-semantic-preference-WEAIZQXM.js} +4 -6
- package/dist/{project-semantic-DJLXAXLD.js → project-semantic-6VXUYU4A.js} +4 -6
- package/dist/{sync-4TUIQ2PZ.js → sync-BAV3UY46.js} +3 -3
- package/dist/{te-agent-EMDWA3M6.js → te-agent-QWZC36YS.js} +1 -3
- package/dist/{te-analysis-XHAMRMTQ.js → te-analysis-43RCOPUA.js} +32 -15
- package/dist/{te-community-JSUSZEYH.js → te-community-ECNTP35Z.js} +5 -8
- package/dist/{te-dataops-I264BUTI.js → te-dataops-ISEKYRLZ.js} +3 -4
- package/dist/{te-engage-XNMQYO5N.js → te-engage-LBKIZXZO.js} +4 -6
- package/dist/{te-experiment-5SCHMYVO.js → te-experiment-5TPQKN6B.js} +4 -6
- package/dist/{te-kb-QQ53TNRZ.js → te-kb-SHL56BJ5.js} +4 -6
- package/dist/{te-team-V6BBI52R.js → te-team-EZ3TZTLV.js} +4 -6
- package/dist/{things-THHGDSEC.js → things-UBMLTY3S.js} +1 -3
- package/dist/{update-53ZUXWV5.js → update-WE7VNRKZ.js} +3 -3
- package/dist/{web-runtime-ZJHOIPKX.js → web-runtime-H53QKJS2.js} +367 -612
- package/package.json +1 -1
- package/skills/ae-onboarding/SKILL.md +44 -23
- package/skills/ae-onboarding/references/about-ae.md +68 -0
- package/skills/ae-onboarding/references/business-data.md +46 -0
- package/skills/ae-onboarding/references/business-sdk.md +1 -1
- package/skills/ae-onboarding/references/demo-journey.md +58 -0
- package/skills/ae-onboarding/references/demo-operations.md +45 -20
- package/skills/ae-onboarding/references/onboarding_experiment_launch.md +7 -4
- package/skills/ae-onboarding/references/onboarding_experiment_plan.md +9 -2
- package/skills/ae-onboarding/references/onboarding_growth.md +37 -5
- package/skills/ae-onboarding/references/onboarding_run.md +16 -2
- package/skills/ae-onboarding/references/onboarding_status.md +2 -0
- package/skills/ae-onboarding/references/presentation.md +79 -0
- package/skills/ae-onboarding/scripts/experiment-requests.mjs +9 -4
- package/skills/ae-onboarding/scripts/generate.mjs +5 -5
- package/skills/ae-onboarding/scripts/resolve-experiment-preset.mjs +5 -2
- package/skills/ae-onboarding/scripts/web-journey.mjs +39 -27
- package/dist/chunk-6E6HCTP2.js +0 -60
- package/dist/chunk-PUSFEC6B.js +0 -29
- package/dist/chunk-QOJXLXDJ.js +0 -55
|
@@ -1,15 +1,7 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
absolutizeRelativeUrls
|
|
4
|
-
} from "./chunk-QOJXLXDJ.js";
|
|
5
2
|
import {
|
|
6
3
|
fetchSigned
|
|
7
4
|
} from "./chunk-KE5WGBXS.js";
|
|
8
|
-
import {
|
|
9
|
-
CapabilityGatewayError,
|
|
10
|
-
executeCapability
|
|
11
|
-
} from "./chunk-STHIGWWC.js";
|
|
12
|
-
import "./chunk-6E6HCTP2.js";
|
|
13
5
|
import {
|
|
14
6
|
assembleSyncJsonBody,
|
|
15
7
|
localDataUpload,
|
|
@@ -29,24 +21,48 @@ import {
|
|
|
29
21
|
DEMO_SAMPLE_IDS,
|
|
30
22
|
DEMO_STATUS,
|
|
31
23
|
NETWORK_BUDGET_MS,
|
|
24
|
+
OVERSEAS_TEST_MARKETS,
|
|
25
|
+
OVERSEAS_TEST_PRODUCT_HOSTNAME,
|
|
26
|
+
OVERSEAS_TEST_WEBSITE_ORIGIN,
|
|
32
27
|
RUN_BUDGET_MS,
|
|
33
28
|
UUID_PATTERN,
|
|
34
29
|
WEBSITE_MARKETS,
|
|
30
|
+
bootstrapOrigin,
|
|
31
|
+
claimBootstrapDevice,
|
|
35
32
|
cliEntrySource,
|
|
36
|
-
|
|
33
|
+
createBootstrap,
|
|
37
34
|
fetchCliConfig,
|
|
35
|
+
isOnboardingProgressHost,
|
|
38
36
|
isProductionWebsiteOrigin,
|
|
37
|
+
isWebsiteMarket,
|
|
39
38
|
normalizeRegistrationLanguage,
|
|
39
|
+
onboardingDemoCurrency,
|
|
40
|
+
onboardingDemoOverview,
|
|
41
|
+
onboardingDeviceMarket,
|
|
42
|
+
onboardingDraftReviewInteraction,
|
|
43
|
+
onboardingEvidenceLinks,
|
|
44
|
+
onboardingExperimentUrl,
|
|
40
45
|
onboardingGrowthScenario,
|
|
46
|
+
onboardingInteraction,
|
|
47
|
+
readBootstrap,
|
|
48
|
+
readCheckoutRecoveryCohort,
|
|
49
|
+
readProgress,
|
|
41
50
|
registrationLanguage,
|
|
42
51
|
registrationMarket,
|
|
52
|
+
replayReportDates,
|
|
53
|
+
runOnboardingGrowth,
|
|
54
|
+
trustedProductHost,
|
|
55
|
+
verifyAndCompleteProgress,
|
|
56
|
+
waitForExperimentSampleSize,
|
|
43
57
|
websiteEnvironment,
|
|
44
58
|
websiteOrigin,
|
|
45
|
-
|
|
46
|
-
} from "./chunk-
|
|
59
|
+
writeProgress
|
|
60
|
+
} from "./chunk-I7H72CMN.js";
|
|
47
61
|
import {
|
|
62
|
+
CapabilityGatewayError,
|
|
63
|
+
executeCapability,
|
|
48
64
|
getLocalCliPackageInfo
|
|
49
|
-
} from "./chunk-
|
|
65
|
+
} from "./chunk-WG27BD67.js";
|
|
50
66
|
import {
|
|
51
67
|
SecureStoreAuthError,
|
|
52
68
|
assertCredentialsReadable,
|
|
@@ -74,126 +90,11 @@ import {
|
|
|
74
90
|
|
|
75
91
|
// src/core/onboarding/web-runtime.ts
|
|
76
92
|
import { createHash as createHash2 } from "crypto";
|
|
77
|
-
import path8 from "path";
|
|
78
|
-
|
|
79
|
-
// src/core/onboarding/runtime.ts
|
|
80
|
-
import crypto3 from "crypto";
|
|
81
93
|
import path7 from "path";
|
|
82
94
|
|
|
83
|
-
// src/core/onboarding/
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
constructor(websiteStatus) {
|
|
87
|
-
super(`The onboarding website request failed (HTTP ${websiteStatus}).`);
|
|
88
|
-
this.websiteStatus = websiteStatus;
|
|
89
|
-
}
|
|
90
|
-
websiteStatus;
|
|
91
|
-
};
|
|
92
|
-
function loginMode(value) {
|
|
93
|
-
if (value === void 0 || value === null) return void 0;
|
|
94
|
-
if (value === "website_login" || value === "device_confirmation") return value;
|
|
95
|
-
throw new Error("The website returned an invalid login mode.");
|
|
96
|
-
}
|
|
97
|
-
function authorizationStatus(value) {
|
|
98
|
-
if (value === void 0 || value === null) return void 0;
|
|
99
|
-
if (["pending", "authorizing", "approved", "claimed", "expired"].includes(String(value))) return value;
|
|
100
|
-
throw new Error("The website returned an invalid authorization status.");
|
|
101
|
-
}
|
|
102
|
-
function bootstrapOrigin(market, environment = websiteEnvironment()) {
|
|
103
|
-
return websiteOrigin(market, environment);
|
|
104
|
-
}
|
|
105
|
-
function trustedProductHost(value) {
|
|
106
|
-
const url = new URL(value);
|
|
107
|
-
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || !["", "/"].includes(url.pathname)) {
|
|
108
|
-
throw new Error("Onboarding requires a trusted HTTPS product origin.");
|
|
109
|
-
}
|
|
110
|
-
return url.origin;
|
|
111
|
-
}
|
|
112
|
-
function websiteUrl(value, origin) {
|
|
113
|
-
const url = new URL(value);
|
|
114
|
-
if (url.origin !== origin || url.username || url.password) throw new Error("The website returned an untrusted continuation URL.");
|
|
115
|
-
return url.toString();
|
|
116
|
-
}
|
|
117
|
-
async function request(origin, endpoint, init, signal) {
|
|
118
|
-
environmentForWebsiteOrigin(origin);
|
|
119
|
-
const response = await fetch(`${origin}${endpoint}`, {
|
|
120
|
-
...init,
|
|
121
|
-
redirect: "error",
|
|
122
|
-
signal,
|
|
123
|
-
headers: { Accept: "application/json", "Content-Type": "application/json", ...init.headers }
|
|
124
|
-
});
|
|
125
|
-
const body = safeJsonParse(await response.text());
|
|
126
|
-
if (!response.ok || body?.return_code !== 0 || !body.data || typeof body.data !== "object") {
|
|
127
|
-
throw new BootstrapRequestError(response.status);
|
|
128
|
-
}
|
|
129
|
-
return body.data;
|
|
130
|
-
}
|
|
131
|
-
async function createBootstrap(market, source, host, signal, toolReference, environment, language) {
|
|
132
|
-
const origin = bootstrapOrigin(market, environment);
|
|
133
|
-
const tool = cliEntrySource(source);
|
|
134
|
-
if (toolReference && (tool !== "codex" || !UUID_PATTERN.test(toolReference))) throw new Error("Invalid AI tool continuation reference.");
|
|
135
|
-
const data = await request(origin, PATH, { method: "POST", headers: {
|
|
136
|
-
"X-AE-CLI-Login-Mode": "website_login",
|
|
137
|
-
...language ? { "Accept-Language": language } : {}
|
|
138
|
-
}, body: JSON.stringify({
|
|
139
|
-
market,
|
|
140
|
-
source,
|
|
141
|
-
...host ? { requested_host: trustedProductHost(host) } : {},
|
|
142
|
-
...toolReference ? { tool_reference: toolReference } : {}
|
|
143
|
-
}) }, signal);
|
|
144
|
-
if (typeof data.intent_id !== "string" || !UUID_PATTERN.test(data.intent_id) || typeof data.poll_token !== "string" || data.poll_token.length < 16 || !Number.isFinite(Date.parse(data.expires_at))) {
|
|
145
|
-
throw new Error("The website returned an invalid bootstrap session.");
|
|
146
|
-
}
|
|
147
|
-
return { ...data, login_mode: loginMode(data.login_mode), login_url: withCliEntryContext(websiteUrl(data.login_url, origin), tool, market, toolReference) };
|
|
148
|
-
}
|
|
149
|
-
async function readBootstrap(origin, intentId, pollToken, signal, source, market) {
|
|
150
|
-
if (!UUID_PATTERN.test(intentId)) throw new Error("Invalid bootstrap continuation.");
|
|
151
|
-
const data = await request(origin, `${PATH}/${encodeURIComponent(intentId)}`, {
|
|
152
|
-
method: "GET",
|
|
153
|
-
headers: { "X-CLI-Bootstrap-Token": pollToken }
|
|
154
|
-
}, signal);
|
|
155
|
-
if (data.intent_id !== intentId || !["pending", "account_ready", "browser_ready", "expired"].includes(data.status)) throw new Error("Invalid bootstrap state.");
|
|
156
|
-
return {
|
|
157
|
-
...data,
|
|
158
|
-
login_mode: loginMode(data.login_mode),
|
|
159
|
-
authorization_status: authorizationStatus(data.authorization_status),
|
|
160
|
-
host: data.host ? trustedProductHost(data.host) : null,
|
|
161
|
-
ready_url: data.ready_url ? source ? withCliEntryContext(websiteUrl(data.ready_url, origin), cliEntrySource(source), market) : websiteUrl(data.ready_url, origin) : null
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
async function claimBootstrapDevice(origin, intentId, pollToken, signal) {
|
|
165
|
-
if (!UUID_PATTERN.test(intentId)) throw new Error("Invalid bootstrap continuation.");
|
|
166
|
-
const data = await request(origin, `${PATH}/${encodeURIComponent(intentId)}/device`, {
|
|
167
|
-
method: "POST",
|
|
168
|
-
body: "{}",
|
|
169
|
-
headers: { "X-CLI-Bootstrap-Token": pollToken }
|
|
170
|
-
}, signal).catch((error) => {
|
|
171
|
-
if (error instanceof BootstrapRequestError && error.websiteStatus === 410) {
|
|
172
|
-
return { login_mode: "website_login", authorization_status: "expired" };
|
|
173
|
-
}
|
|
174
|
-
throw error;
|
|
175
|
-
});
|
|
176
|
-
if (loginMode(data.login_mode) !== "website_login") throw new Error("The website did not confirm this login mode.");
|
|
177
|
-
const status = authorizationStatus(data.authorization_status);
|
|
178
|
-
if (!status) throw new Error("The website returned an invalid authorization status.");
|
|
179
|
-
if (status !== "approved" && status !== "claimed") return {
|
|
180
|
-
login_mode: "website_login",
|
|
181
|
-
authorization_status: status,
|
|
182
|
-
...Number.isFinite(data.poll_after_ms) ? { poll_after_ms: data.poll_after_ms } : {}
|
|
183
|
-
};
|
|
184
|
-
if (typeof data.device_code !== "string" || !/^uba_[A-Za-z0-9_-]{43}$/.test(data.device_code) || typeof data.user_code !== "string" || !/^[A-HJ-NP-Z2-9]{8}$/.test(data.user_code) || !Number.isFinite(Date.parse(data.expires_at)) || !Number.isFinite(data.interval) || data.interval < 1 || data.interval > 60 || typeof data.expected_login_name !== "string" || !data.expected_login_name.trim() || data.expected_login_name.length > 256 || !/^[1-9][0-9]*$/.test(String(data.expected_company_id)) || !Number.isSafeInteger(Number(data.expected_company_id))) throw new Error("The website returned an invalid device connection.");
|
|
185
|
-
return {
|
|
186
|
-
login_mode: "website_login",
|
|
187
|
-
authorization_status: status,
|
|
188
|
-
host: trustedProductHost(data.host),
|
|
189
|
-
device_code: data.device_code,
|
|
190
|
-
user_code: data.user_code,
|
|
191
|
-
expires_at: data.expires_at,
|
|
192
|
-
interval: data.interval,
|
|
193
|
-
expected_login_name: data.expected_login_name,
|
|
194
|
-
expected_company_id: String(data.expected_company_id)
|
|
195
|
-
};
|
|
196
|
-
}
|
|
95
|
+
// src/core/onboarding/runtime.ts
|
|
96
|
+
import crypto2 from "crypto";
|
|
97
|
+
import path6 from "path";
|
|
197
98
|
|
|
198
99
|
// src/core/onboarding/website-login-identity.ts
|
|
199
100
|
async function verifyWebsiteLoginIdentity(host, accessToken, expected, signal) {
|
|
@@ -331,419 +232,9 @@ var OnboardingStore = class {
|
|
|
331
232
|
}
|
|
332
233
|
};
|
|
333
234
|
|
|
334
|
-
// src/core/onboarding/growth.ts
|
|
335
|
-
import crypto2 from "crypto";
|
|
336
|
-
import path2 from "path";
|
|
337
|
-
|
|
338
|
-
// src/core/onboarding/interaction.ts
|
|
339
|
-
var interactions = {
|
|
340
|
-
complete_website_login: [
|
|
341
|
-
{ value: "login_done", label: "I finished signing in" },
|
|
342
|
-
{ value: "login_help", label: "I need help signing in" }
|
|
343
|
-
],
|
|
344
|
-
approve_device: [
|
|
345
|
-
{ value: "authorization_done", label: "I approved CLI access" },
|
|
346
|
-
{ value: "authorization_help", label: "I need help authorizing the CLI" }
|
|
347
|
-
],
|
|
348
|
-
restart_website_login: [
|
|
349
|
-
{ value: "retry_login", label: "Start a new sign-in" },
|
|
350
|
-
{ value: "not_now", label: "Not now" }
|
|
351
|
-
],
|
|
352
|
-
choose_experience: [
|
|
353
|
-
{ value: "demo", label: "Start the demo" },
|
|
354
|
-
{ value: "business", label: "Connect my business data" }
|
|
355
|
-
],
|
|
356
|
-
confirm_business_project: [
|
|
357
|
-
{ value: "confirm_project", label: "Use this AE project" },
|
|
358
|
-
{ value: "not_now", label: "Not now" }
|
|
359
|
-
],
|
|
360
|
-
offer_growth_questions: [
|
|
361
|
-
{ value: "growth", label: "Find a growth opportunity" },
|
|
362
|
-
{ value: "checkout_recovery", label: "Win back players who started checkout but did not pay" },
|
|
363
|
-
{ value: "change_sample", label: "Change sample" }
|
|
364
|
-
],
|
|
365
|
-
growth_ready: [
|
|
366
|
-
{ value: "follow_up", label: "How should we follow up with these users?" },
|
|
367
|
-
{ value: "change_sample", label: "Change sample" }
|
|
368
|
-
],
|
|
369
|
-
confirm_experiment: [
|
|
370
|
-
{ value: "launch", label: "Confirm and start the A/B experiment" },
|
|
371
|
-
{ value: "start_later", label: "Start later" }
|
|
372
|
-
],
|
|
373
|
-
reauthorize_cli: [
|
|
374
|
-
{ value: "reauthorize", label: "Reconnect the CLI" },
|
|
375
|
-
{ value: "not_now", label: "Not now" }
|
|
376
|
-
]
|
|
377
|
-
};
|
|
378
|
-
function onboardingInteraction(step, web = false) {
|
|
379
|
-
if (!Object.hasOwn(interactions, step)) return void 0;
|
|
380
|
-
const options = web && step === "choose_experience" ? [interactions.choose_experience[0], { value: "not_now", label: "Not now" }] : interactions[step];
|
|
381
|
-
return { step, options };
|
|
382
|
-
}
|
|
383
|
-
function onboardingEvidenceLinks(evidence, projectId, host) {
|
|
384
|
-
if (!evidence || typeof evidence !== "object" || typeof projectId !== "number" || !Number.isSafeInteger(projectId) || projectId < 1) return void 0;
|
|
385
|
-
const paths = evidence;
|
|
386
|
-
const links = {};
|
|
387
|
-
const evidenceRoutes = {
|
|
388
|
-
dashboard_url: "panel/panel",
|
|
389
|
-
purchase_rate_report_url: "tga/ide",
|
|
390
|
-
funnel_report_url: "tga/funnel"
|
|
391
|
-
};
|
|
392
|
-
for (const [key, route] of Object.entries(evidenceRoutes)) {
|
|
393
|
-
const value = paths[key];
|
|
394
|
-
if (typeof value === "string" && new RegExp(`^/#/${route}/${projectId}_[1-9][0-9]*$`).test(value)) {
|
|
395
|
-
links[key] = host ? absolutizeRelativeUrls(value, host) : value;
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
return Object.keys(links).length ? links : void 0;
|
|
399
|
-
}
|
|
400
|
-
function onboardingExperimentUrl(projectId, experimentId, host) {
|
|
401
|
-
const params = new URLSearchParams({ expId: experimentId, currentProjectId: String(projectId) });
|
|
402
|
-
const route = `/#/atlas/experiment/detail?${params}`;
|
|
403
|
-
return host ? absolutizeRelativeUrls(route, host) : route;
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
// src/core/onboarding/growth.ts
|
|
407
|
-
var GROWTH_VERSION = 2;
|
|
408
|
-
var CACHE_TTL_MS = 10 * 6e4;
|
|
409
|
-
var DAY_MS = 864e5;
|
|
410
|
-
var VIEW = "item_detail_view";
|
|
411
|
-
var CHECKOUT = "checkout_start";
|
|
412
|
-
var PAYMENT = "payment_success";
|
|
413
|
-
var fields = [
|
|
414
|
-
"single_viewers",
|
|
415
|
-
"single_buyers",
|
|
416
|
-
"multi_viewers",
|
|
417
|
-
"multi_buyers",
|
|
418
|
-
"funnel_viewers",
|
|
419
|
-
"funnel_checkout",
|
|
420
|
-
"funnel_buyers",
|
|
421
|
-
"account_ids_json",
|
|
422
|
-
"checkout_unpaid",
|
|
423
|
-
"checkout_account_ids_json",
|
|
424
|
-
"unmapped_accounts"
|
|
425
|
-
];
|
|
426
|
-
function date(value) {
|
|
427
|
-
return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
|
|
428
|
-
}
|
|
429
|
-
function shiftDate(value, days) {
|
|
430
|
-
return new Date(Date.parse(value) + days * DAY_MS).toISOString().slice(0, 10);
|
|
431
|
-
}
|
|
432
|
-
function growthScope(session, demo) {
|
|
433
|
-
const { project_id, sample_id, item_id, start_date, end_date, zone_offset } = demo;
|
|
434
|
-
if (!session.host || !sample_id || sample_id !== session.sample_id || typeof project_id !== "number" || !Number.isSafeInteger(project_id) || project_id <= 0 || project_id === session.project_id || typeof item_id !== "string" || !item_id.trim() || item_id.length > 128 || !date(start_date) || !date(end_date) || Date.parse(end_date) - Date.parse(start_date) !== 6 * DAY_MS || typeof zone_offset !== "number" || !Number.isFinite(zone_offset) || Math.abs(zone_offset) > 14) return void 0;
|
|
435
|
-
return {
|
|
436
|
-
sessionId: session.id,
|
|
437
|
-
host: trustedProductHost(session.host),
|
|
438
|
-
projectId: project_id,
|
|
439
|
-
sampleId: sample_id,
|
|
440
|
-
itemId: item_id,
|
|
441
|
-
startDate: start_date,
|
|
442
|
-
endDate: end_date,
|
|
443
|
-
zoneOffset: zone_offset
|
|
444
|
-
};
|
|
445
|
-
}
|
|
446
|
-
function evidenceFile(scope, credentialKey) {
|
|
447
|
-
const digest = crypto2.createHash("sha256").update(JSON.stringify([GROWTH_VERSION, credentialKey, scope])).digest("hex");
|
|
448
|
-
return `growth-${digest}.json`;
|
|
449
|
-
}
|
|
450
|
-
function readGrowthEvidence(store, file, scope) {
|
|
451
|
-
const evidence = store.read(file);
|
|
452
|
-
if (evidence?.analysisVersion === GROWTH_VERSION && evidence.schemaVersion === 1 && Object.entries(scope).every(([key, value]) => evidence[key] === value) && Array.isArray(evidence.accountIds) && Array.isArray(evidence.checkoutAccountIds) && evidence.single_day && evidence.multi_day && evidence.funnel) return evidence;
|
|
453
|
-
}
|
|
454
|
-
function readCheckoutRecoveryCohort(store, session, demo) {
|
|
455
|
-
const scope = growthScope(session, demo);
|
|
456
|
-
if (!scope || !session.credential_key) return void 0;
|
|
457
|
-
const evidence = readGrowthEvidence(store, evidenceFile(scope, session.credential_key), scope);
|
|
458
|
-
if (!evidence) return void 0;
|
|
459
|
-
return { start_date: scope.startDate, end_date: scope.endDate, zone_offset: scope.zoneOffset, account_ids: evidence.checkoutAccountIds };
|
|
460
|
-
}
|
|
461
|
-
function sqlString(value) {
|
|
462
|
-
return `'${value.replaceAll("'", "''")}'`;
|
|
463
|
-
}
|
|
464
|
-
function verifiedTables(result, type) {
|
|
465
|
-
return result.items.filter((item) => item?.table_type === type && typeof item.sql_reference === "string" && /^(?:"(?:[^"\u0000-\u001f]|"")+"\.){2}"(?:[^"\u0000-\u001f]|"")+"$/.test(item.sql_reference)).map((item) => item.sql_reference);
|
|
466
|
-
}
|
|
467
|
-
async function resolveEventSource(call, projectId) {
|
|
468
|
-
let offset = 0;
|
|
469
|
-
const events = /* @__PURE__ */ new Set();
|
|
470
|
-
const users = /* @__PURE__ */ new Set();
|
|
471
|
-
const scope = { project_id: projectId, usage: "analysis" };
|
|
472
|
-
while (true) {
|
|
473
|
-
const page = await call("analysis.sql_table.list", { ...scope, limit: 200, offset });
|
|
474
|
-
if (!Array.isArray(page?.items) || typeof page.has_more !== "boolean") throw new Error("AE did not return the authorized SQL tables.");
|
|
475
|
-
verifiedTables(page, "eventView").forEach((name) => events.add(name));
|
|
476
|
-
verifiedTables(page, "userView").forEach((name) => users.add(name));
|
|
477
|
-
if (!page.has_more) break;
|
|
478
|
-
if (!Number.isSafeInteger(page.next_offset) || page.next_offset <= offset) throw new Error("AE returned an invalid SQL table continuation.");
|
|
479
|
-
offset = page.next_offset;
|
|
480
|
-
}
|
|
481
|
-
if (events.size !== 1) throw new Error("AE did not return exactly one authorized Demo event view.");
|
|
482
|
-
const event = [...events][0];
|
|
483
|
-
const readColumns = async (table_ref) => {
|
|
484
|
-
const result = await call("analysis.sql_table.columns", { ...scope, table_ref });
|
|
485
|
-
if (!Array.isArray(result?.columns)) throw new Error("AE did not return the authorized Demo columns.");
|
|
486
|
-
return new Set(result.columns.map((entry) => entry.column));
|
|
487
|
-
};
|
|
488
|
-
const columns = await readColumns(event);
|
|
489
|
-
if (!["#event_time", "$part_date", "$part_event", "plg_sample_id", "item_id", "plg_seed_event_id"].every((name) => columns.has(name))) {
|
|
490
|
-
throw new Error("The authorized Demo view is missing the fields required for growth analysis.");
|
|
491
|
-
}
|
|
492
|
-
if (columns.has("#account_id")) return { from: `${event} e`, account: 'e."#account_id"' };
|
|
493
|
-
if (!columns.has("#user_id") || users.size !== 1) throw new Error("AE did not expose a verified Demo account-ID mapping.");
|
|
494
|
-
const user = [...users][0];
|
|
495
|
-
const userColumns = await readColumns(user);
|
|
496
|
-
if (!userColumns.has("#user_id") || !userColumns.has("#account_id")) throw new Error("AE did not expose a verified Demo account-ID mapping.");
|
|
497
|
-
return { from: `${event} e LEFT JOIN ${user} u ON e."#user_id" = u."#user_id"`, account: 'u."#account_id"' };
|
|
498
|
-
}
|
|
499
|
-
function growthSql(scope, source) {
|
|
500
|
-
return `WITH sample_events AS (
|
|
501
|
-
SELECT NULLIF(CAST(${source.account} AS varchar), '') AS account_id,
|
|
502
|
-
e."$part_event" AS event_name, e."#event_time" AS event_time
|
|
503
|
-
FROM ${source.from}
|
|
504
|
-
WHERE e."$part_date" BETWEEN '${shiftDate(scope.startDate, -1)}' AND '${shiftDate(scope.endDate, 1)}'
|
|
505
|
-
AND e."#event_time" >= TIMESTAMP '${scope.startDate} 00:00:00'
|
|
506
|
-
AND e."#event_time" < TIMESTAMP '${shiftDate(scope.endDate, 1)} 00:00:00'
|
|
507
|
-
AND e.plg_sample_id = ${sqlString(scope.sampleId)} AND e.item_id = ${sqlString(scope.itemId)}
|
|
508
|
-
AND e.plg_seed_event_id IS NOT NULL
|
|
509
|
-
AND e."$part_event" IN ('${VIEW}', '${CHECKOUT}', '${PAYMENT}')
|
|
510
|
-
), views AS (
|
|
511
|
-
SELECT *, min(CASE WHEN event_name = '${VIEW}' THEN event_time END) OVER (PARTITION BY account_id) AS first_view
|
|
512
|
-
FROM sample_events
|
|
513
|
-
), checkouts AS (
|
|
514
|
-
SELECT *, min(CASE WHEN event_name = '${CHECKOUT}' AND event_time > first_view THEN event_time END)
|
|
515
|
-
OVER (PARTITION BY account_id) AS first_checkout
|
|
516
|
-
FROM views
|
|
517
|
-
), accounts AS (
|
|
518
|
-
SELECT account_id, count(DISTINCT CAST(event_time AS date)) FILTER (WHERE event_name = '${VIEW}') AS view_days,
|
|
519
|
-
count_if(event_name = '${PAYMENT}') > 0 AS bought,
|
|
520
|
-
count_if(first_checkout IS NOT NULL) > 0 AS checked_out,
|
|
521
|
-
count_if(event_name = '${PAYMENT}' AND event_time > first_checkout) > 0 AS paid_after_checkout
|
|
522
|
-
FROM checkouts GROUP BY account_id
|
|
523
|
-
)
|
|
524
|
-
SELECT count_if(view_days = 1) AS single_viewers, count_if(view_days = 1 AND bought) AS single_buyers,
|
|
525
|
-
count_if(view_days >= 2) AS multi_viewers, count_if(view_days >= 2 AND bought) AS multi_buyers,
|
|
526
|
-
count_if(view_days > 0) AS funnel_viewers, count_if(checked_out) AS funnel_checkout,
|
|
527
|
-
count_if(paid_after_checkout) AS funnel_buyers,
|
|
528
|
-
COALESCE(json_format(CAST(array_sort(array_agg(account_id) FILTER (WHERE view_days >= 2 AND NOT bought)) AS JSON)), '[]') AS account_ids_json,
|
|
529
|
-
count_if(checked_out AND NOT bought) AS checkout_unpaid,
|
|
530
|
-
COALESCE(json_format(CAST(array_sort(array_agg(account_id) FILTER (WHERE checked_out AND NOT bought)) AS JSON)), '[]') AS checkout_account_ids_json,
|
|
531
|
-
count_if(account_id IS NULL) AS unmapped_accounts
|
|
532
|
-
FROM accounts`;
|
|
533
|
-
}
|
|
534
|
-
function accountIds(value, expected) {
|
|
535
|
-
let ids;
|
|
536
|
-
try {
|
|
537
|
-
ids = typeof value === "string" ? JSON.parse(value) : void 0;
|
|
538
|
-
} catch {
|
|
539
|
-
}
|
|
540
|
-
if (!Array.isArray(ids) || ids.length !== expected || new Set(ids).size !== ids.length || !ids.every((id) => typeof id === "string" && id.length > 0 && id.length <= 256 && id === id.trim())) {
|
|
541
|
-
throw new Error("AE returned incomplete or inconsistent Demo growth evidence.");
|
|
542
|
-
}
|
|
543
|
-
return ids;
|
|
544
|
-
}
|
|
545
|
-
function parseGrowth(result, scope, verifiedAt) {
|
|
546
|
-
if (result?.has_more !== false || result.returned_rows !== 1 || result.rows?.length !== 1 || !Array.isArray(result.title) || !Array.isArray(result.rows[0])) {
|
|
547
|
-
throw new Error("AE did not return a complete Demo growth result.");
|
|
548
|
-
}
|
|
549
|
-
const row = Object.fromEntries(result.title.map((name, index) => [name, result.rows[0][index]]));
|
|
550
|
-
if (!fields.every((field) => Object.hasOwn(row, field))) throw new Error("AE did not return the expected Demo growth fields.");
|
|
551
|
-
const count = (field) => {
|
|
552
|
-
const raw = row[field];
|
|
553
|
-
const value = typeof raw === "string" && /^\d+$/.test(raw) ? Number(raw) : raw;
|
|
554
|
-
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error("AE returned an invalid Demo growth count.");
|
|
555
|
-
return value;
|
|
556
|
-
};
|
|
557
|
-
const single_day = { viewers: count("single_viewers"), buyers: count("single_buyers") };
|
|
558
|
-
const multi_day = { viewers: count("multi_viewers"), buyers: count("multi_buyers") };
|
|
559
|
-
const funnel = { viewers: count("funnel_viewers"), checkout: count("funnel_checkout"), buyers: count("funnel_buyers") };
|
|
560
|
-
const checkoutUnpaid = count("checkout_unpaid");
|
|
561
|
-
if (single_day.buyers > single_day.viewers || multi_day.buyers > multi_day.viewers || funnel.checkout > funnel.viewers || funnel.buyers + checkoutUnpaid > funnel.checkout || funnel.viewers !== single_day.viewers + multi_day.viewers || count("unmapped_accounts") !== 0 || funnel.viewers === 0) {
|
|
562
|
-
throw new Error("AE returned incomplete or inconsistent Demo growth evidence.");
|
|
563
|
-
}
|
|
564
|
-
return {
|
|
565
|
-
...scope,
|
|
566
|
-
schemaVersion: 1,
|
|
567
|
-
analysisVersion: GROWTH_VERSION,
|
|
568
|
-
verifiedAt,
|
|
569
|
-
single_day,
|
|
570
|
-
multi_day,
|
|
571
|
-
funnel,
|
|
572
|
-
accountIds: accountIds(row.account_ids_json, multi_day.viewers - multi_day.buyers),
|
|
573
|
-
checkoutAccountIds: accountIds(row.checkout_account_ids_json, checkoutUnpaid)
|
|
574
|
-
};
|
|
575
|
-
}
|
|
576
|
-
async function runOnboardingGrowth(store, deps, input, preview) {
|
|
577
|
-
const scenario = onboardingGrowthScenario(input.scenario);
|
|
578
|
-
const sessionId = input.session_id;
|
|
579
|
-
if (!sessionId || !UUID_PATTERN.test(sessionId)) throw new Error("A valid onboarding --session-id is required.");
|
|
580
|
-
const explicitHost = input.host ? trustedProductHost(input.host) : void 0;
|
|
581
|
-
const readSession = () => store.session(sessionId, explicitHost);
|
|
582
|
-
if (preview) {
|
|
583
|
-
const session = readSession();
|
|
584
|
-
return {
|
|
585
|
-
dry_run: true,
|
|
586
|
-
session_id: sessionId,
|
|
587
|
-
host: session.host ?? null,
|
|
588
|
-
sample_id: session.sample_id ?? null,
|
|
589
|
-
scenario,
|
|
590
|
-
capabilities: [DEMO_STATUS, "analysis.sql_table.list", "analysis.sql_table.columns", "analysis.adhoc.run"]
|
|
591
|
-
};
|
|
592
|
-
}
|
|
593
|
-
const started = deps.now();
|
|
594
|
-
const signal = AbortSignal.timeout(RUN_BUDGET_MS);
|
|
595
|
-
return store.locked(`session:${sessionId}`, async () => {
|
|
596
|
-
const session = readSession();
|
|
597
|
-
const base = { session_id: sessionId, host: session.host ?? null, sample_id: session.sample_id ?? null, scenario };
|
|
598
|
-
if (!session.host || !session.credential_key || session.requires_auth || deps.credentialKey(session.host) !== session.credential_key) {
|
|
599
|
-
return {
|
|
600
|
-
...base,
|
|
601
|
-
phase: "action_required",
|
|
602
|
-
next_action: "resume_onboarding",
|
|
603
|
-
poll_after_ms: 0,
|
|
604
|
-
message: "Resume onboarding with the signed-in account for this session."
|
|
605
|
-
};
|
|
606
|
-
}
|
|
607
|
-
const host = trustedProductHost(session.host);
|
|
608
|
-
if (session.choice !== "demo" || !session.sample_id || !DEMO_SAMPLE_IDS.some((sample) => sample === session.sample_id)) {
|
|
609
|
-
return {
|
|
610
|
-
...base,
|
|
611
|
-
phase: "action_required",
|
|
612
|
-
next_action: "choose_demo",
|
|
613
|
-
poll_after_ms: 0,
|
|
614
|
-
message: "Select a supported Demo in this onboarding session."
|
|
615
|
-
};
|
|
616
|
-
}
|
|
617
|
-
const call = async (id, body) => {
|
|
618
|
-
signal.throwIfAborted();
|
|
619
|
-
const request2 = new AbortController();
|
|
620
|
-
const abort = () => request2.abort();
|
|
621
|
-
const timer = setTimeout(abort, NETWORK_BUDGET_MS);
|
|
622
|
-
timer.unref();
|
|
623
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
624
|
-
try {
|
|
625
|
-
const result = await deps.capability(host, id, body, request2.signal);
|
|
626
|
-
request2.signal.throwIfAborted();
|
|
627
|
-
return result;
|
|
628
|
-
} finally {
|
|
629
|
-
signal.removeEventListener("abort", abort);
|
|
630
|
-
clearTimeout(timer);
|
|
631
|
-
}
|
|
632
|
-
};
|
|
633
|
-
try {
|
|
634
|
-
const demo = await call(DEMO_STATUS, { sample_id: session.sample_id });
|
|
635
|
-
if (typeof demo?.status !== "string" || demo.sample_id !== session.sample_id) {
|
|
636
|
-
throw new Error("AE did not confirm the selected Demo sample.");
|
|
637
|
-
}
|
|
638
|
-
if (demo.status !== "ready") {
|
|
639
|
-
return demo.status === "action_required" ? {
|
|
640
|
-
...base,
|
|
641
|
-
phase: "action_required",
|
|
642
|
-
next_action: "inspect_demo_preparation",
|
|
643
|
-
poll_after_ms: 0,
|
|
644
|
-
message: "Demo preparation needs attention before analysis can run."
|
|
645
|
-
} : { ...base, phase: "pending", next_action: "poll_demo", poll_after_ms: 2e3 };
|
|
646
|
-
}
|
|
647
|
-
const scope = growthScope(session, demo);
|
|
648
|
-
if (!scope) throw new Error("AE did not confirm the active Demo project and its seven-day sample scope.");
|
|
649
|
-
const file = evidenceFile(scope, session.credential_key);
|
|
650
|
-
let evidence = readGrowthEvidence(store, file, scope);
|
|
651
|
-
const cached = evidence !== void 0 && deps.now() - evidence.verifiedAt >= 0 && deps.now() - evidence.verifiedAt < CACHE_TTL_MS;
|
|
652
|
-
let queryMs = 0;
|
|
653
|
-
if (!evidence || !cached) {
|
|
654
|
-
const source = await resolveEventSource(call, scope.projectId);
|
|
655
|
-
const queryStarted = deps.now();
|
|
656
|
-
const rows = await call("analysis.adhoc.run", {
|
|
657
|
-
project_id: scope.projectId,
|
|
658
|
-
model_type: "sql",
|
|
659
|
-
definition: { sql: growthSql(scope, source) },
|
|
660
|
-
use_cache: false
|
|
661
|
-
});
|
|
662
|
-
queryMs = Math.max(0, deps.now() - queryStarted);
|
|
663
|
-
evidence = parseGrowth(rows, scope, deps.now());
|
|
664
|
-
}
|
|
665
|
-
if (deps.credentialKey(host) !== session.credential_key) throw new Error("The active CLI account changed during Demo growth analysis.");
|
|
666
|
-
if (!cached) store.write(file, evidence);
|
|
667
|
-
const readyDemo = {
|
|
668
|
-
sample_id: scope.sampleId,
|
|
669
|
-
item_id: scope.itemId,
|
|
670
|
-
project_id: scope.projectId,
|
|
671
|
-
start_date: scope.startDate,
|
|
672
|
-
end_date: scope.endDate,
|
|
673
|
-
zone_offset: scope.zoneOffset
|
|
674
|
-
};
|
|
675
|
-
if (!Object.entries(readyDemo).every(([key, value]) => session.ready_demo?.[key] === value)) {
|
|
676
|
-
session.ready_demo = readyDemo;
|
|
677
|
-
store.save(session);
|
|
678
|
-
}
|
|
679
|
-
const singleRate = evidence.single_day.viewers ? evidence.single_day.buyers / evidence.single_day.viewers : null;
|
|
680
|
-
const multiRate = evidence.multi_day.viewers ? evidence.multi_day.buyers / evidence.multi_day.viewers : null;
|
|
681
|
-
const checkoutUnpaid = evidence.checkoutAccountIds.length;
|
|
682
|
-
const followUpData = scenario === CHECKOUT_RECOVERY ? [
|
|
683
|
-
{ label: "Started checkout", value: evidence.funnel.checkout },
|
|
684
|
-
{ label: "Paid after checkout", value: evidence.funnel.buyers },
|
|
685
|
-
{ label: "Checkout without payment", value: checkoutUnpaid }
|
|
686
|
-
] : [
|
|
687
|
-
{ label: "Multi-day viewers, unpaid", value: evidence.accountIds.length },
|
|
688
|
-
{ label: "Single-day viewers, unpaid", value: evidence.single_day.viewers - evidence.single_day.buyers },
|
|
689
|
-
{ label: "Paid viewers", value: evidence.single_day.buyers + evidence.multi_day.buyers }
|
|
690
|
-
];
|
|
691
|
-
const maxCount = Math.max(1, ...followUpData.map((row) => row.value));
|
|
692
|
-
const followUpMarkdown = followUpData.map(({ label, value }) => {
|
|
693
|
-
const width = value === 0 ? 0 : Math.max(1, Math.round(value * 10 / maxCount));
|
|
694
|
-
return `- ${label} \xB7 ${width ? "\u2588".repeat(width) + " " : ""}**${value}**`;
|
|
695
|
-
}).join("\n");
|
|
696
|
-
return {
|
|
697
|
-
...base,
|
|
698
|
-
phase: "ready",
|
|
699
|
-
demo_project_id: scope.projectId,
|
|
700
|
-
item_id: scope.itemId,
|
|
701
|
-
start_date: scope.startDate,
|
|
702
|
-
end_date: scope.endDate,
|
|
703
|
-
zone_offset: scope.zoneOffset,
|
|
704
|
-
analysis_version: GROWTH_VERSION,
|
|
705
|
-
single_day: evidence.single_day,
|
|
706
|
-
multi_day: evidence.multi_day,
|
|
707
|
-
funnel: evidence.funnel,
|
|
708
|
-
purchase_rates: {
|
|
709
|
-
single_day: singleRate,
|
|
710
|
-
multi_day: multiRate,
|
|
711
|
-
difference_pp: singleRate === null || multiRate === null ? null : (multiRate - singleRate) * 100
|
|
712
|
-
},
|
|
713
|
-
charts: {
|
|
714
|
-
purchase_rate: { type: "bar", data: [
|
|
715
|
-
...singleRate === null ? [] : [{ label: "Single-day viewers", value: Math.round(singleRate * 1e3) / 10 }],
|
|
716
|
-
...multiRate === null ? [] : [{ label: "Multi-day viewers", value: Math.round(multiRate * 1e3) / 10 }]
|
|
717
|
-
] },
|
|
718
|
-
funnel: { type: "bar", data: [
|
|
719
|
-
{ label: "Viewed", value: evidence.funnel.viewers },
|
|
720
|
-
{ label: "Started checkout", value: evidence.funnel.checkout },
|
|
721
|
-
{ label: "Paid", value: evidence.funnel.buyers }
|
|
722
|
-
] }
|
|
723
|
-
},
|
|
724
|
-
follow_up_chart: { type: "bar", data: followUpData, markdown: followUpMarkdown },
|
|
725
|
-
follow_up_count: scenario === CHECKOUT_RECOVERY ? checkoutUnpaid : evidence.accountIds.length,
|
|
726
|
-
checkout_recovery: { unpaid_count: checkoutUnpaid, unpaid_rate: evidence.funnel.checkout ? checkoutUnpaid / evidence.funnel.checkout : null },
|
|
727
|
-
cohort_path: path2.resolve(store.directory, file),
|
|
728
|
-
evidence: onboardingEvidenceLinks(demo.evidence, scope.projectId, deps.webConversation ? void 0 : host),
|
|
729
|
-
interaction: onboardingInteraction(scenario === CHECKOUT_RECOVERY && checkoutUnpaid < 2 ? "offer_growth_questions" : "growth_ready"),
|
|
730
|
-
cached,
|
|
731
|
-
query_ms: queryMs,
|
|
732
|
-
elapsed_ms: Math.max(0, deps.now() - started),
|
|
733
|
-
poll_after_ms: 0
|
|
734
|
-
};
|
|
735
|
-
} catch (error) {
|
|
736
|
-
if (signal.aborted || error instanceof Error && ["AbortError", "TimeoutError"].includes(error.name)) {
|
|
737
|
-
return { ...base, phase: "pending", next_action: "retry_growth", poll_after_ms: 2e3 };
|
|
738
|
-
}
|
|
739
|
-
throw error;
|
|
740
|
-
}
|
|
741
|
-
});
|
|
742
|
-
}
|
|
743
|
-
|
|
744
235
|
// src/core/onboarding/experiment-launch.ts
|
|
745
236
|
import { createHash } from "crypto";
|
|
746
|
-
import
|
|
237
|
+
import path4 from "path";
|
|
747
238
|
import { isDeepStrictEqual } from "util";
|
|
748
239
|
|
|
749
240
|
// skills/ae-onboarding/scripts/experiment-preset.json
|
|
@@ -1002,9 +493,49 @@ var experiment_preset_default = {
|
|
|
1002
493
|
|
|
1003
494
|
// src/core/onboarding/experiment-plan.ts
|
|
1004
495
|
import { randomUUID } from "crypto";
|
|
1005
|
-
import
|
|
496
|
+
import path2 from "path";
|
|
1006
497
|
var PROJECT_INFO = "project.info.get";
|
|
1007
498
|
var APPROVER_ADD = "experiment.approver.add";
|
|
499
|
+
function readActivePlan(store, deps, input) {
|
|
500
|
+
const { session_id: sessionId, run_id: runId } = input;
|
|
501
|
+
if (!sessionId || !UUID_PATTERN.test(sessionId) || !runId || !/^[0-9a-f]{32}$/.test(runId)) {
|
|
502
|
+
throw new Error("Pass the onboarding session ID and the run ID returned by experiment-plan.");
|
|
503
|
+
}
|
|
504
|
+
const session = store.session(sessionId, input.host ? trustedProductHost(input.host) : void 0);
|
|
505
|
+
const file = `experiment-plan-${runId}.json`;
|
|
506
|
+
const plan = store.read(file);
|
|
507
|
+
const scope = session.ready_demo;
|
|
508
|
+
if (!plan || plan.phase !== "ready" || plan.session_id !== session.id || plan.run_id !== runId || !session.host || plan.host !== session.host || session.choice !== "demo" || !scope || plan.sample_id !== session.sample_id || plan.sample_id !== scope.sample_id || plan.item_id !== scope.item_id || plan.demo_project_id !== scope.project_id || !session.credential_key || session.requires_auth || plan.credential_key !== session.credential_key || deps.credentialKey(session.host) !== session.credential_key) {
|
|
509
|
+
throw new Error("The saved experiment plan does not match the active Demo session and account.");
|
|
510
|
+
}
|
|
511
|
+
return { file, plan };
|
|
512
|
+
}
|
|
513
|
+
function publicPlan(plan) {
|
|
514
|
+
const { checkout_cohort: _cohort, credential_key: _key, ...review } = plan;
|
|
515
|
+
return plan.approver?.status === "deferred" ? { ...review, interaction: onboardingDraftReviewInteraction(plan.answered_questions) } : review;
|
|
516
|
+
}
|
|
517
|
+
function readOnboardingExperimentPlan(store, deps, input) {
|
|
518
|
+
return publicPlan(readActivePlan(store, deps, input).plan);
|
|
519
|
+
}
|
|
520
|
+
function recordAnsweredQuestion(store, deps, input, preview) {
|
|
521
|
+
const { session_id: sessionId, answered_question: question } = input;
|
|
522
|
+
if (!sessionId || !UUID_PATTERN.test(sessionId) || !input.run_id || !question || input.scenario || input.draft_only || input.upload_metric_event || input.prepare_approver) {
|
|
523
|
+
throw new Error("Use --session-id, --run-id, and --answered-question together for draft review.");
|
|
524
|
+
}
|
|
525
|
+
if (!onboardingDraftReviewInteraction().options.some((option) => option.value === question && option.value !== "launch")) {
|
|
526
|
+
throw new Error("Use --answered-question review_audience, review_pilot, or review_no_reward.");
|
|
527
|
+
}
|
|
528
|
+
const update = () => {
|
|
529
|
+
const { file, plan } = readActivePlan(store, deps, input);
|
|
530
|
+
if (plan.approver?.status !== "deferred") throw new Error("Only a plan saved with --draft-only supports review questions.");
|
|
531
|
+
const answered = plan.answered_questions ?? [];
|
|
532
|
+
const updated = answered.includes(question) ? plan : { ...plan, answered_questions: [...answered, question] };
|
|
533
|
+
if (!preview && updated !== plan) store.write(file, updated);
|
|
534
|
+
const result = publicPlan(updated);
|
|
535
|
+
return preview ? { ...result, dry_run: true } : result;
|
|
536
|
+
};
|
|
537
|
+
return preview ? update() : store.locked(`session:${sessionId}`, async () => update());
|
|
538
|
+
}
|
|
1008
539
|
function readyDemoScope(demo, session) {
|
|
1009
540
|
if (demo?.status !== "ready" || !demo.sample_id || demo.sample_id !== session.sample_id || typeof demo.item_id !== "string" || !demo.item_id || typeof demo.project_id !== "number" || !Number.isSafeInteger(demo.project_id) || demo.project_id <= 0 || demo.project_id === session.project_id) return void 0;
|
|
1010
541
|
return {
|
|
@@ -1017,10 +548,16 @@ function readyDemoScope(demo, session) {
|
|
|
1017
548
|
};
|
|
1018
549
|
}
|
|
1019
550
|
async function runOnboardingExperimentPlan(store, deps, input, preview) {
|
|
551
|
+
if (input.run_id !== void 0 || input.answered_question !== void 0) {
|
|
552
|
+
return recordAnsweredQuestion(store, deps, input, preview);
|
|
553
|
+
}
|
|
1020
554
|
const scenario = onboardingGrowthScenario(input.scenario);
|
|
1021
555
|
if (scenario === CHECKOUT_RECOVERY && input.upload_metric_event) {
|
|
1022
556
|
throw new Error("Checkout recovery prepares the plan locally. Use experiment-launch after the user confirms it.");
|
|
1023
557
|
}
|
|
558
|
+
if (input.draft_only && (input.upload_metric_event || input.prepare_approver)) {
|
|
559
|
+
throw new Error("Use --draft-only by itself to prepare a plan for review.");
|
|
560
|
+
}
|
|
1024
561
|
const sessionId = input.session_id;
|
|
1025
562
|
if (!sessionId) throw new Error("A valid onboarding --session-id is required.");
|
|
1026
563
|
const explicitHost = input.host ? trustedProductHost(input.host) : void 0;
|
|
@@ -1031,11 +568,12 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
|
|
|
1031
568
|
session_id: sessionId,
|
|
1032
569
|
host: session.host ?? null,
|
|
1033
570
|
sample_id: session.sample_id ?? null,
|
|
571
|
+
currency: deps.demoCurrency(session.host, session.region),
|
|
1034
572
|
...input.scenario ? { scenario } : {},
|
|
1035
573
|
capabilities: [
|
|
1036
574
|
...session.ready_demo ? [] : [DEMO_STATUS],
|
|
1037
575
|
...input.upload_metric_event ? [PROJECT_INFO] : [],
|
|
1038
|
-
APPROVER_ADD
|
|
576
|
+
...input.draft_only ? [] : [APPROVER_ADD]
|
|
1039
577
|
],
|
|
1040
578
|
...input.upload_metric_event ? { metric_event: { event_name: "payment_success", record_count: 1 } } : {}
|
|
1041
579
|
};
|
|
@@ -1073,6 +611,7 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
|
|
|
1073
611
|
throw new Error("The active Demo sample and item have no supported experiment preset.");
|
|
1074
612
|
}
|
|
1075
613
|
const preset = experiment_preset_default.experimentTypes[scenario];
|
|
614
|
+
const currency = deps.demoCurrency(host, session.region);
|
|
1076
615
|
const checkoutCohort = scenario === CHECKOUT_RECOVERY ? readCheckoutRecoveryCohort(store, session, scope) : void 0;
|
|
1077
616
|
if (scenario === CHECKOUT_RECOVERY && !checkoutCohort) {
|
|
1078
617
|
return {
|
|
@@ -1093,6 +632,7 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
|
|
|
1093
632
|
}
|
|
1094
633
|
const eventId = randomUUID();
|
|
1095
634
|
const runId = eventId.replaceAll("-", "");
|
|
635
|
+
const audienceCount = checkoutCohort?.account_ids.length ?? selection.sample.followUpAccountIds.length;
|
|
1096
636
|
const result = {
|
|
1097
637
|
...base,
|
|
1098
638
|
phase: "ready",
|
|
@@ -1102,11 +642,12 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
|
|
|
1102
642
|
industry: selection.industry,
|
|
1103
643
|
experiment_type: scenario,
|
|
1104
644
|
run_id: runId,
|
|
1105
|
-
interaction: onboardingInteraction("confirm_experiment"),
|
|
645
|
+
interaction: input.draft_only ? onboardingDraftReviewInteraction() : onboardingInteraction("confirm_experiment"),
|
|
646
|
+
...input.draft_only ? { answered_questions: [], review: { pilot_accounts_per_arm: Math.min(4, Math.floor(audienceCount / 2)) } } : {},
|
|
1106
647
|
plan: {
|
|
1107
648
|
synthetic: true,
|
|
1108
649
|
hypothesis: preset.experiment.hypothesis,
|
|
1109
|
-
audience_count:
|
|
650
|
+
audience_count: audienceCount,
|
|
1110
651
|
audience: {
|
|
1111
652
|
minimum_view_days: preset.audience.minimumViewDays,
|
|
1112
653
|
view_event: preset.audience.viewEvent,
|
|
@@ -1122,7 +663,7 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
|
|
|
1122
663
|
bucket_id: preset.audience.bucketId,
|
|
1123
664
|
arms: Object.entries(preset.arms).map(([role, arm]) => ({ role, name: arm.name, allocation: arm.allocation, price: arm.price })),
|
|
1124
665
|
metrics: preset.metrics,
|
|
1125
|
-
currency
|
|
666
|
+
currency,
|
|
1126
667
|
cost_per_paid_order: preset.costPerPaidOrder,
|
|
1127
668
|
other_costs: preset.otherCosts
|
|
1128
669
|
}
|
|
@@ -1132,14 +673,24 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
|
|
|
1132
673
|
"| A \xB7 Control | B \xB7 Treatment |",
|
|
1133
674
|
"| --- | --- |",
|
|
1134
675
|
`| ${control.name} | ${treatment.name} |`,
|
|
1135
|
-
`| ${control.price} ${
|
|
676
|
+
`| ${control.price} ${currency} \xB7 ${control.allocation}% | ${treatment.price} ${currency} \xB7 ${treatment.allocation}% |`
|
|
1136
677
|
].join("\n");
|
|
1137
678
|
const file = `experiment-plan-${runId}.json`;
|
|
1138
|
-
const planPath =
|
|
679
|
+
const planPath = path2.resolve(store.directory, file);
|
|
680
|
+
const savePlan = (plan) => store.write(file, {
|
|
681
|
+
...plan,
|
|
682
|
+
...input.draft_only ? { plan_preview_markdown: planPreviewMarkdown } : {},
|
|
683
|
+
...input.draft_only || checkoutCohort ? { credential_key: session.credential_key } : {},
|
|
684
|
+
...checkoutCohort ? { checkout_cohort: checkoutCohort } : {}
|
|
685
|
+
});
|
|
686
|
+
if (input.draft_only) {
|
|
687
|
+
const draft = { ...result, approver: { status: "deferred" } };
|
|
688
|
+
savePlan(draft);
|
|
689
|
+
return { ...draft, plan_path: planPath, plan_preview_markdown: planPreviewMarkdown };
|
|
690
|
+
}
|
|
1139
691
|
const metricEvent = input.upload_metric_event ? { event_name: preset.events.payment, event_id: eventId, persistence_verified: false } : void 0;
|
|
1140
|
-
|
|
692
|
+
savePlan({
|
|
1141
693
|
...result,
|
|
1142
|
-
...checkoutCohort ? { checkout_cohort: checkoutCohort, credential_key: session.credential_key } : {},
|
|
1143
694
|
...metricEvent ? { metric_event: { ...metricEvent, status: "pending" } } : {},
|
|
1144
695
|
approver: { status: "pending" }
|
|
1145
696
|
});
|
|
@@ -1156,7 +707,7 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
|
|
|
1156
707
|
plg_sample_id: sampleId,
|
|
1157
708
|
item_id: scope.item_id,
|
|
1158
709
|
amount: preset.arms.control.price,
|
|
1159
|
-
currency
|
|
710
|
+
currency,
|
|
1160
711
|
order_id: eventId
|
|
1161
712
|
}
|
|
1162
713
|
}) : void 0
|
|
@@ -1166,10 +717,7 @@ async function runOnboardingExperimentPlan(store, deps, input, preview) {
|
|
|
1166
717
|
approver,
|
|
1167
718
|
...delivery ? { metric_event: { ...metricEvent, ...delivery } } : {}
|
|
1168
719
|
};
|
|
1169
|
-
|
|
1170
|
-
...preparedPlan,
|
|
1171
|
-
...checkoutCohort ? { checkout_cohort: checkoutCohort, credential_key: session.credential_key } : {}
|
|
1172
|
-
});
|
|
720
|
+
savePlan(preparedPlan);
|
|
1173
721
|
return { ...preparedPlan, plan_path: planPath, plan_preview_markdown: planPreviewMarkdown };
|
|
1174
722
|
});
|
|
1175
723
|
}
|
|
@@ -1222,7 +770,7 @@ async function uploadPlanPayment(deps, host, credentialKey, scope, event) {
|
|
|
1222
770
|
// src/core/onboarding/experiment-replay.ts
|
|
1223
771
|
import { execFile } from "child_process";
|
|
1224
772
|
import { mkdtemp, readFile, rm, writeFile } from "fs/promises";
|
|
1225
|
-
import
|
|
773
|
+
import path3 from "path";
|
|
1226
774
|
import { promisify } from "util";
|
|
1227
775
|
var exec = promisify(execFile);
|
|
1228
776
|
var OUTCOME_DELAY_MS = 5e3;
|
|
@@ -1231,7 +779,7 @@ async function runExperimentScript(script, args) {
|
|
|
1231
779
|
if (!root) throw new Error("The PLG preset scripts could not be located in this CLI package.");
|
|
1232
780
|
const { stdout } = await exec(
|
|
1233
781
|
process.execPath,
|
|
1234
|
-
[
|
|
782
|
+
[path3.join(root, "skills", "ae-onboarding", "scripts", script), ...args],
|
|
1235
783
|
{ timeout: 15e3 }
|
|
1236
784
|
);
|
|
1237
785
|
return stdout;
|
|
@@ -1248,12 +796,12 @@ async function prepareExperimentReplay(options) {
|
|
|
1248
796
|
const midnight = Math.floor((now + offsetMs) / 864e5) * 864e5 - offsetMs;
|
|
1249
797
|
const experimentStart = Date.parse(options.startTime);
|
|
1250
798
|
if (!Number.isFinite(experimentStart) || experimentStart > now) throw new Error("The running experiment has no elapsed start time.");
|
|
1251
|
-
const start = Math.max(experimentStart, midnight, now - OUTCOME_DELAY_MS);
|
|
1252
|
-
const end = start + OUTCOME_DELAY_MS;
|
|
1253
|
-
const directory = await mkdtemp(
|
|
799
|
+
const start = options.savedTiming ? Date.parse(options.savedTiming.start) : Math.max(experimentStart, midnight, now - OUTCOME_DELAY_MS);
|
|
800
|
+
const end = options.savedTiming ? Date.parse(options.savedTiming.end) : start + OUTCOME_DELAY_MS;
|
|
801
|
+
const directory = await mkdtemp(path3.join(options.directory, "experiment-replay-"));
|
|
1254
802
|
try {
|
|
1255
|
-
const cohort =
|
|
1256
|
-
const replay =
|
|
803
|
+
const cohort = path3.join(directory, "cohort.json");
|
|
804
|
+
const replay = path3.join(directory, "replay");
|
|
1257
805
|
await writeFile(cohort, JSON.stringify(options.accountIds), { mode: 384 });
|
|
1258
806
|
await runExperimentScript("generate.mjs", [
|
|
1259
807
|
"--phase=plg-experiment-today",
|
|
@@ -1262,6 +810,7 @@ async function prepareExperimentReplay(options) {
|
|
|
1262
810
|
`--experiment-type=${options.experimentType}`,
|
|
1263
811
|
`--sample-id=${options.sampleId}`,
|
|
1264
812
|
`--item-id=${options.itemId}`,
|
|
813
|
+
`--currency=${options.currency}`,
|
|
1265
814
|
`--cohort-file=${cohort}`,
|
|
1266
815
|
`--experiment-id=${options.experimentId}`,
|
|
1267
816
|
`--control-id=${options.controlId}`,
|
|
@@ -1271,16 +820,16 @@ async function prepareExperimentReplay(options) {
|
|
|
1271
820
|
`--timezone=${timezone}`,
|
|
1272
821
|
`--output-dir=${replay}`
|
|
1273
822
|
]);
|
|
1274
|
-
const receipt = JSON.parse(await readFile(
|
|
1275
|
-
const mapping = JSON.parse(await readFile(
|
|
823
|
+
const receipt = JSON.parse(await readFile(path3.join(replay, "plg-experiment-receipt.json"), "utf8"));
|
|
824
|
+
const mapping = JSON.parse(await readFile(path3.join(replay, "replay.mapping.json"), "utf8"));
|
|
1276
825
|
const { convertLocalData } = await import("./conversion-4FR3RA45.js");
|
|
1277
826
|
const converted = await convertLocalData({
|
|
1278
|
-
inputFile:
|
|
827
|
+
inputFile: path3.join(replay, "replay.jsonl"),
|
|
1279
828
|
mapping,
|
|
1280
|
-
outputDir:
|
|
829
|
+
outputDir: path3.join(directory, "converted"),
|
|
1281
830
|
now: new Date(options.now())
|
|
1282
831
|
});
|
|
1283
|
-
const rows = (await readFile(
|
|
832
|
+
const rows = (await readFile(path3.join(converted.output_dir, converted.manifest.output.valid_file), "utf8")).trim().split("\n");
|
|
1284
833
|
const count = receipt.event_uuids.exposure.length + receipt.event_uuids.outcomes.length;
|
|
1285
834
|
if (converted.status !== "ready" || count === 0 || converted.manifest.output.invalid_records !== 0 || rows.length !== count || converted.manifest.output.valid_records !== count) {
|
|
1286
835
|
throw new Error("The complete Demo replay did not pass data conversion.");
|
|
@@ -1309,11 +858,13 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1309
858
|
const execute = async (session) => {
|
|
1310
859
|
const plan = store.read(`experiment-plan-${runId}.json`);
|
|
1311
860
|
const scope = session.ready_demo;
|
|
1312
|
-
if (!plan || plan.phase !== "ready" || plan.run_id !== runId || plan.session_id !== sessionId || !session.host || plan.host !== session.host || session.choice !== "demo" || plan.sample_id !== session.sample_id || !scope || scope.sample_id !== plan.sample_id || scope.item_id !== plan.item_id || scope.project_id !== plan.demo_project_id || !Number.isSafeInteger(scope.project_id) || scope.project_id <= 0 || scope.project_id === session.project_id) {
|
|
861
|
+
if (!plan || plan.phase !== "ready" || plan.run_id !== runId || plan.session_id !== sessionId || !session.host || plan.host !== session.host || session.choice !== "demo" || plan.sample_id !== session.sample_id || plan.credential_key && plan.credential_key !== session.credential_key || !scope || scope.sample_id !== plan.sample_id || scope.item_id !== plan.item_id || scope.project_id !== plan.demo_project_id || !Number.isSafeInteger(scope.project_id) || scope.project_id <= 0 || scope.project_id === session.project_id) {
|
|
1313
862
|
throw new Error("The saved experiment plan does not match the active Demo session and sample.");
|
|
1314
863
|
}
|
|
1315
864
|
const host = trustedProductHost(session.host);
|
|
1316
865
|
const project = { project_id: scope.project_id };
|
|
866
|
+
const currency = plan.plan?.currency ?? "CNY";
|
|
867
|
+
if (currency !== "CNY" && currency !== "USD") throw new Error("The saved Demo plan has an unsupported currency.");
|
|
1317
868
|
const checkoutCohort = plan.experiment_type === CHECKOUT_RECOVERY ? plan.checkout_cohort : void 0;
|
|
1318
869
|
if (plan.experiment_type === CHECKOUT_RECOVERY && (!checkoutCohort || plan.credential_key !== session.credential_key || !Array.isArray(checkoutCohort.account_ids) || checkoutCohort.account_ids.length < 2)) {
|
|
1319
870
|
throw new Error("The checkout recovery plan no longer matches the verified Demo scope.");
|
|
@@ -1325,10 +876,12 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1325
876
|
demo_project_id: scope.project_id,
|
|
1326
877
|
sample_id: scope.sample_id,
|
|
1327
878
|
item_id: scope.item_id,
|
|
879
|
+
currency,
|
|
1328
880
|
...checkoutCohort ? { experiment_type: plan.experiment_type } : {}
|
|
1329
881
|
};
|
|
1330
882
|
if (preview) return { ...summary, dry_run: true, steps: [
|
|
1331
883
|
...checkoutCohort ? ["check_other_demo_experiment", "verify_demo_scope"] : [],
|
|
884
|
+
...plan.approver?.status === "deferred" ? ["prepare_signed_in_approver"] : [],
|
|
1332
885
|
"save_metrics_and_feature",
|
|
1333
886
|
"save_draft",
|
|
1334
887
|
"check_readiness",
|
|
@@ -1336,7 +889,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1336
889
|
...plan.approver ? [] : ["add_signed_in_approver_if_needed"],
|
|
1337
890
|
"approve",
|
|
1338
891
|
"start",
|
|
1339
|
-
...input.start_only ? [] : ["upload_one_replay_batch"]
|
|
892
|
+
...input.start_only ? [] : ["upload_one_replay_batch", ...input.wait_report ? ["wait_for_sample_size_report"] : []]
|
|
1340
893
|
] };
|
|
1341
894
|
const key = session.credential_key;
|
|
1342
895
|
const checkAccount = () => {
|
|
@@ -1344,14 +897,27 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1344
897
|
throw new Error("Resume onboarding with the signed-in account that generated the Demo plan.");
|
|
1345
898
|
}
|
|
1346
899
|
};
|
|
1347
|
-
const
|
|
900
|
+
const request = async (id, params, waitSignal) => {
|
|
1348
901
|
checkAccount();
|
|
1349
|
-
const signal = AbortSignal.timeout(NETWORK_BUDGET_MS);
|
|
902
|
+
const signal = waitSignal ?? AbortSignal.timeout(NETWORK_BUDGET_MS);
|
|
1350
903
|
const response = await deps.capability(host, id, params, signal);
|
|
1351
904
|
signal.throwIfAborted();
|
|
1352
905
|
return response;
|
|
1353
906
|
};
|
|
1354
907
|
checkAccount();
|
|
908
|
+
let progressRun;
|
|
909
|
+
const checkpoint = async (experimentId, receipt) => {
|
|
910
|
+
if (!progressRun) return;
|
|
911
|
+
checkAccount();
|
|
912
|
+
const result2 = await writeProgress(deps, host, "checkpoint", {
|
|
913
|
+
...progressRun,
|
|
914
|
+
experiment_id: experimentId,
|
|
915
|
+
...receipt ? { receipt } : {}
|
|
916
|
+
});
|
|
917
|
+
if (result2.state !== "in_progress" || result2.experiment_id !== experimentId) {
|
|
918
|
+
throw new Error("The Demo experiment checkpoint could not be saved. Resume the same run.");
|
|
919
|
+
}
|
|
920
|
+
};
|
|
1355
921
|
const stateFile = `experiment-launch-${runId}.json`;
|
|
1356
922
|
const progress = store.read(stateFile) ?? { timings_ms: {} };
|
|
1357
923
|
const persist = () => store.write(stateFile, progress);
|
|
@@ -1362,7 +928,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1362
928
|
...progress.experiment_id && (progress.experiment_status === "running" || progress.replay) ? {
|
|
1363
929
|
experiment_url: onboardingExperimentUrl(scope.project_id, progress.experiment_id, deps.webConversation ? void 0 : host)
|
|
1364
930
|
} : {},
|
|
1365
|
-
replay_receipt_path: progress.replay ?
|
|
931
|
+
replay_receipt_path: progress.replay ? path4.resolve(store.directory, `experiment-replay-${runId}.json`) : void 0
|
|
1366
932
|
});
|
|
1367
933
|
const completed = () => ({
|
|
1368
934
|
...result("complete"),
|
|
@@ -1372,10 +938,37 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1372
938
|
next_action: "verify_experiment_results"
|
|
1373
939
|
});
|
|
1374
940
|
const started = () => ({ ...result("running"), approval_state: "approved", next_action: "upload_experiment_replay" });
|
|
1375
|
-
|
|
941
|
+
const finishReplay = async () => {
|
|
942
|
+
const accepted = completed();
|
|
943
|
+
if (!input.wait_report) return accepted;
|
|
944
|
+
try {
|
|
945
|
+
const receipt = store.read(`experiment-replay-${runId}.json`);
|
|
946
|
+
if (!receipt || receipt.run_id !== runId || receipt.experiment_id !== progress.experiment_id || receipt.sample_id !== scope.sample_id || receipt.item_id !== scope.item_id || (receipt.currency ?? "CNY") !== currency) {
|
|
947
|
+
throw new Error("The replay receipt does not match this Demo experiment.");
|
|
948
|
+
}
|
|
949
|
+
const dates = replayReportDates(receipt);
|
|
950
|
+
const report = await waitForExperimentSampleSize(
|
|
951
|
+
(params, signal) => request("experiment.report.sample-size", params, signal),
|
|
952
|
+
{ project_id: scope.project_id, exp_id: progress.experiment_id, ...dates }
|
|
953
|
+
);
|
|
954
|
+
return { ...accepted, ...report };
|
|
955
|
+
} catch (error) {
|
|
956
|
+
return {
|
|
957
|
+
...accepted,
|
|
958
|
+
phase: "action_required",
|
|
959
|
+
failed_stage: "wait_experiment_report",
|
|
960
|
+
next_action: "inspect_experiment_report",
|
|
961
|
+
error: {
|
|
962
|
+
message: error instanceof Error ? error.message : "The report query failed.",
|
|
963
|
+
...error instanceof CapabilityGatewayError ? { code: error.code, meta: error.meta } : {}
|
|
964
|
+
}
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
if (progress.replay?.status === "receiver_accepted") return finishReplay();
|
|
1376
969
|
if (progress.replay) return { ...result("action_required"), next_action: "reconcile_replay_delivery" };
|
|
1377
970
|
let stage = "prepare_requests";
|
|
1378
|
-
const call = (id, params = {}) =>
|
|
971
|
+
const call = (id, params = {}) => request(id, { ...project, ...params });
|
|
1379
972
|
const measure = async (name, action) => {
|
|
1380
973
|
const start = deps.now();
|
|
1381
974
|
try {
|
|
@@ -1406,7 +999,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1406
999
|
if (!checkoutCohort && error instanceof CapabilityGatewayError && error.code === "CAPABILITY_NOT_FOUND") return { items: [] };
|
|
1407
1000
|
throw error;
|
|
1408
1001
|
}),
|
|
1409
|
-
checkoutCohort && !progress.experiment_status ?
|
|
1002
|
+
checkoutCohort && !progress.experiment_status ? request(DEMO_STATUS, { sample_id: scope.sample_id }) : void 0
|
|
1410
1003
|
]);
|
|
1411
1004
|
if (!progress.experiment_status && !Array.isArray(otherExperiments?.items)) {
|
|
1412
1005
|
throw new Error("AE did not return the Demo experiment list.");
|
|
@@ -1431,6 +1024,43 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1431
1024
|
};
|
|
1432
1025
|
}
|
|
1433
1026
|
}
|
|
1027
|
+
stage = "claim_onboarding_run";
|
|
1028
|
+
if (session.journey_id) {
|
|
1029
|
+
const current = await readProgress(deps, host);
|
|
1030
|
+
if (current.state !== "completed" && current.state !== "disabled") {
|
|
1031
|
+
checkAccount();
|
|
1032
|
+
const run = {
|
|
1033
|
+
journey_id: session.journey_id,
|
|
1034
|
+
run_id: runId,
|
|
1035
|
+
launch_session_id: session.id,
|
|
1036
|
+
demo_project_id: scope.project_id
|
|
1037
|
+
};
|
|
1038
|
+
const claim = await writeProgress(deps, host, "claim", run);
|
|
1039
|
+
if (claim.state !== "disabled" && !claim.claim_granted) {
|
|
1040
|
+
return {
|
|
1041
|
+
...summary,
|
|
1042
|
+
phase: "action_required",
|
|
1043
|
+
next_action: "resume_onboarding_progress",
|
|
1044
|
+
existing_run_id: claim.run_id,
|
|
1045
|
+
experiment_id: claim.experiment_id
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
if (claim.claim_granted) progressRun = run;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
if (plan.approver?.status === "deferred" && !progress.approver_prepared) {
|
|
1052
|
+
stage = "prepare_approver";
|
|
1053
|
+
checkAccount();
|
|
1054
|
+
const prepared = await prepareDemoApprover(deps, host, key, scope.project_id);
|
|
1055
|
+
if (prepared.status !== "ready") return {
|
|
1056
|
+
...result("action_required"),
|
|
1057
|
+
failed_stage: stage,
|
|
1058
|
+
next_action: "resume_experiment_launch",
|
|
1059
|
+
error: { message: prepared.message, code: prepared.code }
|
|
1060
|
+
};
|
|
1061
|
+
progress.approver_prepared = true;
|
|
1062
|
+
persist();
|
|
1063
|
+
}
|
|
1434
1064
|
stage = "prepare_requests";
|
|
1435
1065
|
const requestsFile = `experiment-requests-${runId}.json`;
|
|
1436
1066
|
let requests = store.read(requestsFile);
|
|
@@ -1442,9 +1072,10 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1442
1072
|
sampleId: plan.sample_id,
|
|
1443
1073
|
itemId: plan.item_id,
|
|
1444
1074
|
runId,
|
|
1075
|
+
currency,
|
|
1445
1076
|
...checkoutCohort ? { accountIds: checkoutCohort.account_ids } : {}
|
|
1446
1077
|
});
|
|
1447
|
-
const generated = JSON.parse(await runExperimentScript("experiment-requests.mjs", [
|
|
1078
|
+
const generated = JSON.parse(await runExperimentScript("experiment-requests.mjs", [path4.join(store.directory, inputFile)]));
|
|
1448
1079
|
store.write(requestsFile, generated);
|
|
1449
1080
|
requests = generated;
|
|
1450
1081
|
}
|
|
@@ -1494,6 +1125,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1494
1125
|
progress.experiment_id = draft.result;
|
|
1495
1126
|
});
|
|
1496
1127
|
const exp = { exp_id: progress.experiment_id };
|
|
1128
|
+
await checkpoint(exp.exp_id);
|
|
1497
1129
|
const approval = async () => (await call("experiment.approval.get", exp)).item;
|
|
1498
1130
|
const verifyRound = (round) => {
|
|
1499
1131
|
if (!Number.isSafeInteger(round?.approval_id) || round.approval_id <= 0 || progress.approval_id && round.approval_id !== progress.approval_id || round.configuration?.exp_id !== exp.exp_id || round.configuration.exp_name !== preset.experiment.expName || !round.configuration.feature_key_list?.includes(preset.feature.featureKey)) {
|
|
@@ -1602,6 +1234,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1602
1234
|
experimentType: plan.experiment_type,
|
|
1603
1235
|
sampleId: plan.sample_id,
|
|
1604
1236
|
itemId: plan.item_id,
|
|
1237
|
+
currency,
|
|
1605
1238
|
experimentId: exp.exp_id,
|
|
1606
1239
|
controlId,
|
|
1607
1240
|
treatmentId,
|
|
@@ -1610,10 +1243,24 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1610
1243
|
zoneOffset,
|
|
1611
1244
|
appid: info.appid.trim(),
|
|
1612
1245
|
receiver: info.public_receiver_address,
|
|
1613
|
-
now: deps.now
|
|
1246
|
+
now: deps.now,
|
|
1247
|
+
savedTiming: progressRun ? store.read(`experiment-replay-${runId}.json`) : void 0
|
|
1614
1248
|
});
|
|
1615
1249
|
checkAccount();
|
|
1616
1250
|
store.write(`experiment-replay-${runId}.json`, replay.receipt);
|
|
1251
|
+
if (progressRun) {
|
|
1252
|
+
const { sample_id, item_id, currency: currency2, start, end, timezone, arms } = replay.receipt;
|
|
1253
|
+
const publicArm = ({ group_id, exposed_account_ids, coupon_claim_account_ids, paid_account_ids }) => ({ group_id, exposed_account_ids, coupon_claim_account_ids, paid_account_ids });
|
|
1254
|
+
await checkpoint(exp.exp_id, {
|
|
1255
|
+
sample_id,
|
|
1256
|
+
item_id,
|
|
1257
|
+
currency: currency2,
|
|
1258
|
+
start,
|
|
1259
|
+
end,
|
|
1260
|
+
timezone,
|
|
1261
|
+
arms: { control: publicArm(arms.control), treatment: publicArm(arms.treatment) }
|
|
1262
|
+
});
|
|
1263
|
+
}
|
|
1617
1264
|
progress.replay = { status: "unknown", record_count: replay.count };
|
|
1618
1265
|
persist();
|
|
1619
1266
|
try {
|
|
@@ -1624,7 +1271,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1624
1271
|
}
|
|
1625
1272
|
progress.replay.status = "receiver_accepted";
|
|
1626
1273
|
});
|
|
1627
|
-
return
|
|
1274
|
+
return finishReplay();
|
|
1628
1275
|
} catch (error) {
|
|
1629
1276
|
return {
|
|
1630
1277
|
...result("action_required"),
|
|
@@ -1645,7 +1292,7 @@ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
|
|
|
1645
1292
|
|
|
1646
1293
|
// src/core/onboarding/workspace-projects.ts
|
|
1647
1294
|
import fs2 from "fs";
|
|
1648
|
-
import
|
|
1295
|
+
import path5 from "path";
|
|
1649
1296
|
var ignored = /* @__PURE__ */ new Set(["node_modules", "vendor", "dist", "build", "Library", "Packages", "Temp", "obj", "Assets"]);
|
|
1650
1297
|
function identifyWorkspaceProjects(root = process.cwd()) {
|
|
1651
1298
|
const projects = [];
|
|
@@ -1660,11 +1307,11 @@ function identifyWorkspaceProjects(root = process.cwd()) {
|
|
|
1660
1307
|
continue;
|
|
1661
1308
|
}
|
|
1662
1309
|
const files = new Set(entries.filter((entry) => entry.isFile()).map((entry) => entry.name));
|
|
1663
|
-
const relative =
|
|
1310
|
+
const relative = path5.relative(root, directory) || ".";
|
|
1664
1311
|
if (entries.some((entry) => entry.name === "Assets" && entry.isDirectory()) && entries.some((entry) => entry.name === "ProjectSettings" && entry.isDirectory())) {
|
|
1665
1312
|
projects.push({ directory: relative, platform: "unity", evidence: "Assets/, ProjectSettings/" });
|
|
1666
1313
|
}
|
|
1667
|
-
const packageManifest = files.has("package.json") ? readManifest(
|
|
1314
|
+
const packageManifest = files.has("package.json") ? readManifest(path5.join(directory, "package.json")) : void 0;
|
|
1668
1315
|
const dependencies = { ...packageManifest?.dependencies, ...packageManifest?.devDependencies };
|
|
1669
1316
|
const hasBrowser = files.has("index.html") || Object.keys(dependencies).some((name) => ["vite", "next", "react-dom", "vue", "@angular/core", "phaser", "pixi.js"].includes(name));
|
|
1670
1317
|
const hasServer = Object.keys(dependencies).some((name) => ["express", "fastify", "@nestjs/core", "koa", "@hapi/hapi", "socket.io"].includes(name)) || ["server.js", "server.mjs", "server.ts"].some((file) => files.has(file));
|
|
@@ -1673,7 +1320,7 @@ function identifyWorkspaceProjects(root = process.cwd()) {
|
|
|
1673
1320
|
if (depth < 4) {
|
|
1674
1321
|
for (const entry of entries) {
|
|
1675
1322
|
if (entry.isDirectory() && !entry.name.startsWith(".") && !ignored.has(entry.name)) {
|
|
1676
|
-
pending.push({ directory:
|
|
1323
|
+
pending.push({ directory: path5.join(directory, entry.name), depth: depth + 1 });
|
|
1677
1324
|
}
|
|
1678
1325
|
}
|
|
1679
1326
|
}
|
|
@@ -1752,6 +1399,8 @@ function clearAccountScope(session) {
|
|
|
1752
1399
|
delete session.choice;
|
|
1753
1400
|
delete session.sample_id;
|
|
1754
1401
|
delete session.ready_demo;
|
|
1402
|
+
delete session.journey_id;
|
|
1403
|
+
delete session.demo_visits;
|
|
1755
1404
|
delete session.confirmed_business_project_id;
|
|
1756
1405
|
}
|
|
1757
1406
|
var defaults = {
|
|
@@ -1764,9 +1413,10 @@ var defaults = {
|
|
|
1764
1413
|
},
|
|
1765
1414
|
credentialKey(host) {
|
|
1766
1415
|
const token = readExternalCliToken(host)?.token ?? (process.env.TE_AGENT_CLI_CONFIG_DIR !== void 0 ? peekCliToken(host) : loadCliToken(host));
|
|
1767
|
-
return token ?
|
|
1416
|
+
return token ? crypto2.createHash("sha256").update(token).digest("hex") : void 0;
|
|
1768
1417
|
},
|
|
1769
1418
|
machineLoginAllowed: (host) => !readExternalCliToken(host),
|
|
1419
|
+
demoCurrency: onboardingDemoCurrency,
|
|
1770
1420
|
createBootstrap,
|
|
1771
1421
|
readBootstrap,
|
|
1772
1422
|
claimBootstrapDevice,
|
|
@@ -1774,7 +1424,7 @@ var defaults = {
|
|
|
1774
1424
|
authorize: authorizeLoginDevice,
|
|
1775
1425
|
poll: (issuer, code, signal) => pollDeviceToken(issuer, code, code.startsWith("uba_") ? "uba" : "legacy", signal),
|
|
1776
1426
|
async persist(host, tokens, signal) {
|
|
1777
|
-
const { persistDeviceTokens, activateHostAfterLogin } = await import("./auth-
|
|
1427
|
+
const { persistDeviceTokens, activateHostAfterLogin } = await import("./auth-6BUUY5XS.js");
|
|
1778
1428
|
await persistDeviceTokens(host, tokens, { signal, checkCompatibility: false });
|
|
1779
1429
|
activateHostAfterLogin(host, host);
|
|
1780
1430
|
},
|
|
@@ -1803,6 +1453,23 @@ var OnboardingRuntime = class {
|
|
|
1803
1453
|
store;
|
|
1804
1454
|
dependencies;
|
|
1805
1455
|
async invoke(action, input) {
|
|
1456
|
+
if (action === "progress" || action === "progress-preview") {
|
|
1457
|
+
const active = input.host ?? this.dependencies.activeHost();
|
|
1458
|
+
const host2 = active ? trustedProductHost(active) : void 0;
|
|
1459
|
+
if (action === "progress-preview") return { dry_run: true, action: input.run_id ? "complete" : "status", host: host2 };
|
|
1460
|
+
if (!host2 || !this.dependencies.webConversation && !isOnboardingProgressHost(host2) || !this.dependencies.authenticated(host2)) return { state: "disabled" };
|
|
1461
|
+
if (!input.run_id) {
|
|
1462
|
+
const { receipt: _receipt2, ...progress2 } = await readProgress(this.dependencies, host2);
|
|
1463
|
+
return progress2;
|
|
1464
|
+
}
|
|
1465
|
+
if (!/^[0-9a-f]{32}$/.test(input.run_id)) throw new Error("Pass the run ID returned by experiment-plan.");
|
|
1466
|
+
const { receipt: _receipt, ...progress } = await verifyAndCompleteProgress(this.dependencies, host2, input.run_id);
|
|
1467
|
+
return progress;
|
|
1468
|
+
}
|
|
1469
|
+
if ((action === "status" || action === "plan") && input.run_id) {
|
|
1470
|
+
const draft = readOnboardingExperimentPlan(this.store, this.dependencies, input);
|
|
1471
|
+
return action === "plan" ? { ...draft, dry_run: true } : draft;
|
|
1472
|
+
}
|
|
1806
1473
|
if (action === "growth" || action === "growth-plan") {
|
|
1807
1474
|
return runOnboardingGrowth(this.store, this.dependencies, input, action === "growth-plan");
|
|
1808
1475
|
}
|
|
@@ -1819,34 +1486,44 @@ var OnboardingRuntime = class {
|
|
|
1819
1486
|
if (input.choice === "business" && input.sample) throw new Error("A sample requires the demo choice.");
|
|
1820
1487
|
if (input.language && !normalizeRegistrationLanguage(input.language)) throw new Error("Unsupported onboarding language. Use zh-CN, en-US, ja-JP, or ko-KR.");
|
|
1821
1488
|
if (input.source && !["codex", "claude-code", "cursor", "other"].includes(input.source)) throw new Error("Unsupported local AI tool source.");
|
|
1822
|
-
const selectedWebsiteEnv = websiteEnvironment(input.website_env, webConversation ? {} : process.env);
|
|
1823
1489
|
const explicitHost = input.host ? trustedProductHost(input.host) : void 0;
|
|
1824
|
-
|
|
1825
|
-
|
|
1490
|
+
const pinnedSession = input.session_id ? this.store.session(input.session_id, explicitHost) : void 0;
|
|
1491
|
+
const websiteEnvOverride = input.website_env ?? (webConversation ? void 0 : process.env.AE_CLI_WEBSITE_ENV);
|
|
1492
|
+
const selectedWebsiteEnv = websiteEnvironment(websiteEnvOverride ?? pinnedSession?.website_env, {});
|
|
1493
|
+
const testHost = selectedWebsiteEnv === "test" ? `https://${OVERSEAS_TEST_PRODUCT_HOSTNAME}` : void 0;
|
|
1494
|
+
if (testHost && explicitHost && explicitHost !== testHost) throw new Error("Use the overseas test product host for test website onboarding.");
|
|
1495
|
+
let session = pinnedSession ?? this.store.session(void 0, explicitHost ?? testHost);
|
|
1496
|
+
let host = explicitHost ?? session?.host ?? testHost;
|
|
1826
1497
|
if (!host) {
|
|
1827
1498
|
const active = this.dependencies.activeHost();
|
|
1828
1499
|
const activeCandidate = active ? trustedProductHost(active) : void 0;
|
|
1829
1500
|
host = activeCandidate && (action === "plan" || this.dependencies.authenticated(activeCandidate)) ? activeCandidate : void 0;
|
|
1830
1501
|
}
|
|
1831
1502
|
if (!session) session = this.store.session(void 0, host);
|
|
1832
|
-
if (session
|
|
1833
|
-
|
|
1834
|
-
|
|
1503
|
+
if (session) {
|
|
1504
|
+
const origin = session.bootstrap?.origin;
|
|
1505
|
+
const matchesOrigin = !origin || (testHost ? origin === OVERSEAS_TEST_WEBSITE_ORIGIN : isProductionWebsiteOrigin(origin));
|
|
1506
|
+
if ((session.website_env ?? "production") !== selectedWebsiteEnv || testHost && session.host !== testHost || !matchesOrigin) {
|
|
1507
|
+
if (pinnedSession) throw new Error("This onboarding session is bound to a previous website environment. Start a separate continuation.");
|
|
1508
|
+
session = void 0;
|
|
1835
1509
|
}
|
|
1836
|
-
session = void 0;
|
|
1837
1510
|
}
|
|
1838
1511
|
const source = cliEntrySource(input.source ?? session?.source);
|
|
1839
1512
|
const language = registrationLanguage(input.language ?? session?.language);
|
|
1840
|
-
const
|
|
1513
|
+
const markets = testHost ? OVERSEAS_TEST_MARKETS : WEBSITE_MARKETS;
|
|
1514
|
+
const languageMarket = registrationMarket(language);
|
|
1515
|
+
const defaultMarket = testHost && languageMarket === "cn" ? "us" : languageMarket;
|
|
1516
|
+
const useDefaultMarket = testHost !== void 0 || !host;
|
|
1841
1517
|
const registrationOrigin = webConversation ? null : websiteOrigin(input.region ?? session?.region ?? defaultMarket, selectedWebsiteEnv);
|
|
1842
1518
|
if (action === "plan") return {
|
|
1843
1519
|
dry_run: true,
|
|
1844
1520
|
host: host ?? null,
|
|
1845
|
-
market: input.region ?? session?.region ?? (
|
|
1521
|
+
market: input.region ?? session?.region ?? (useDefaultMarket ? defaultMarket : null),
|
|
1846
1522
|
language,
|
|
1847
1523
|
default_market: defaultMarket,
|
|
1848
|
-
|
|
1849
|
-
|
|
1524
|
+
device_market: testHost ? "us" : onboardingDeviceMarket(),
|
|
1525
|
+
markets,
|
|
1526
|
+
selection_source: input.region ? "explicit" : session?.region_source ?? (session?.region ? "saved" : useDefaultMarket ? "language_default" : "existing_host"),
|
|
1850
1527
|
website_env: selectedWebsiteEnv,
|
|
1851
1528
|
website_origin: registrationOrigin,
|
|
1852
1529
|
actions: webConversation ? ["read_project_state", "choose_demo", "prepare_demo"] : ["resolve_trusted_host", "resolve_account_host", "authorize_cli", "read_project_state", "choose_demo_or_business", "prepare_demo_or_connect_sdk"],
|
|
@@ -1857,15 +1534,16 @@ var OnboardingRuntime = class {
|
|
|
1857
1534
|
if (!session && action === "status" && (!host || !this.dependencies.authenticated(host))) return { host: host ?? null, project_id: null, phase: "not_started", next_action: "run_onboarding", poll_after_ms: 0 };
|
|
1858
1535
|
const newSession = (market) => ({
|
|
1859
1536
|
schema_version: 1,
|
|
1860
|
-
id:
|
|
1537
|
+
id: crypto2.randomUUID(),
|
|
1861
1538
|
host,
|
|
1862
1539
|
browser: browserMode,
|
|
1863
1540
|
source,
|
|
1864
|
-
region: market ?? (
|
|
1541
|
+
region: market ?? (useDefaultMarket ? defaultMarket : void 0),
|
|
1865
1542
|
language,
|
|
1866
1543
|
language_source: input.language ? "explicit" : "system",
|
|
1867
1544
|
website_env: selectedWebsiteEnv,
|
|
1868
|
-
region_source: market ? "explicit" :
|
|
1545
|
+
region_source: market ? "explicit" : useDefaultMarket ? "language_default" : void 0,
|
|
1546
|
+
...testHost ? { requires_auth: true } : {},
|
|
1869
1547
|
updated_at: new Date(this.dependencies.now()).toISOString()
|
|
1870
1548
|
});
|
|
1871
1549
|
if (!session) session = newSession(input.region);
|
|
@@ -1876,7 +1554,7 @@ var OnboardingRuntime = class {
|
|
|
1876
1554
|
if (credentialKey) session.credential_key = credentialKey;
|
|
1877
1555
|
session.host ??= host;
|
|
1878
1556
|
if (!session.region) {
|
|
1879
|
-
session.region = input.region ?? (
|
|
1557
|
+
session.region = input.region ?? (useDefaultMarket && action === "run" ? defaultMarket : void 0);
|
|
1880
1558
|
if (session.region) session.region_source = input.region ? "explicit" : "language_default";
|
|
1881
1559
|
}
|
|
1882
1560
|
session.language = language;
|
|
@@ -1916,10 +1594,10 @@ var OnboardingRuntime = class {
|
|
|
1916
1594
|
market: current.region ?? null,
|
|
1917
1595
|
default_market: defaultMarket,
|
|
1918
1596
|
website_env: current.website_env,
|
|
1919
|
-
markets
|
|
1597
|
+
markets,
|
|
1920
1598
|
selection_source: current.region_source ?? (current.region ? "saved" : "existing_host"),
|
|
1921
1599
|
...extra,
|
|
1922
|
-
skill_path:
|
|
1600
|
+
skill_path: path6.join(getLocalCliPackageInfo().root, "skills", "ae-onboarding", "SKILL.md"),
|
|
1923
1601
|
...interaction ? { interaction } : {},
|
|
1924
1602
|
...target ? { browser: opening?.receipt ?? extra.browser ?? onboardingBrowserPolicy({ target: target.name, new_page: false }) } : {},
|
|
1925
1603
|
session_id: current.id,
|
|
@@ -1942,7 +1620,7 @@ var OnboardingRuntime = class {
|
|
|
1942
1620
|
const execute = async () => {
|
|
1943
1621
|
const marketChanged = input.region && current.region && input.region !== current.region;
|
|
1944
1622
|
if (marketChanged) {
|
|
1945
|
-
if (action !== "run" || input.session_id || current.host || current.project_id || current.credential_key || current.device) {
|
|
1623
|
+
if (action !== "run" || input.session_id || current.host && !(testHost && current.requires_auth) || current.project_id || current.credential_key || current.device) {
|
|
1946
1624
|
throw new Error("The continuation is bound to another market. Keep the existing account environment and resume its original continuation.");
|
|
1947
1625
|
}
|
|
1948
1626
|
if (current.bootstrap) {
|
|
@@ -1984,6 +1662,25 @@ var OnboardingRuntime = class {
|
|
|
1984
1662
|
this.store.save(current);
|
|
1985
1663
|
}
|
|
1986
1664
|
const compatibility = action === "run" ? await network((signal) => this.dependencies.compatibility(current.host, signal)) : void 0;
|
|
1665
|
+
const versioned = webConversation || isOnboardingProgressHost(current.host);
|
|
1666
|
+
let progress = versioned && action === "run" ? await readProgress(this.dependencies, current.host) : void 0;
|
|
1667
|
+
if (progress?.state === "not_started" && input.choice === "demo" && !loginChangedCredential) {
|
|
1668
|
+
progress = await writeProgress(this.dependencies, current.host, "start", { version: progress.version });
|
|
1669
|
+
}
|
|
1670
|
+
if (progress?.state === "in_progress" && progress.journey_id !== current.journey_id) {
|
|
1671
|
+
current = {
|
|
1672
|
+
...current,
|
|
1673
|
+
id: crypto2.randomUUID(),
|
|
1674
|
+
journey_id: progress.journey_id,
|
|
1675
|
+
choice: void 0,
|
|
1676
|
+
sample_id: void 0,
|
|
1677
|
+
ready_demo: void 0,
|
|
1678
|
+
demo_visits: void 0
|
|
1679
|
+
};
|
|
1680
|
+
this.store.save(current);
|
|
1681
|
+
} else if (progress?.state === "not_started" && !input.choice && (current.choice || current.journey_id)) {
|
|
1682
|
+
current = { ...current, id: crypto2.randomUUID(), journey_id: void 0, choice: void 0, sample_id: void 0, ready_demo: void 0, demo_visits: void 0 };
|
|
1683
|
+
}
|
|
1987
1684
|
const context = await network((signal) => this.dependencies.capability(current.host, DEMO_CONTEXT, {}, signal));
|
|
1988
1685
|
const projectId = context?.business_project?.project_id;
|
|
1989
1686
|
const availableProject = Number.isSafeInteger(projectId) && projectId > 0;
|
|
@@ -2004,7 +1701,21 @@ var OnboardingRuntime = class {
|
|
|
2004
1701
|
if (current.choice !== "demo" || current.ready_demo?.sample_id !== current.sample_id || current.ready_demo?.project_id === projectId) delete current.ready_demo;
|
|
2005
1702
|
this.store.save(current);
|
|
2006
1703
|
}
|
|
2007
|
-
const account = {
|
|
1704
|
+
const account = {
|
|
1705
|
+
...completedLogin,
|
|
1706
|
+
...progress ? { onboarding_progress: {
|
|
1707
|
+
state: progress.state,
|
|
1708
|
+
run_id: progress.run_id,
|
|
1709
|
+
experiment_id: progress.experiment_id,
|
|
1710
|
+
demo_project_id: progress.demo_project_id
|
|
1711
|
+
} } : {},
|
|
1712
|
+
business_project: availableProject ? context.business_project : null,
|
|
1713
|
+
compatibility,
|
|
1714
|
+
...!webConversation ? { business_data: {
|
|
1715
|
+
interaction: onboardingInteraction("choose_data_source"),
|
|
1716
|
+
tools: onboardingInteraction("choose_data_tool")
|
|
1717
|
+
} } : {}
|
|
1718
|
+
};
|
|
2008
1719
|
if (current.choice === "demo" && current.sample_id) {
|
|
2009
1720
|
const prepareDemo = () => network((signal) => this.dependencies.capability(
|
|
2010
1721
|
current.host,
|
|
@@ -2023,15 +1734,42 @@ var OnboardingRuntime = class {
|
|
|
2023
1734
|
}
|
|
2024
1735
|
if (action === "run") {
|
|
2025
1736
|
const scope = readyDemoScope(demo, current);
|
|
2026
|
-
if (scope)
|
|
2027
|
-
|
|
1737
|
+
if (scope) {
|
|
1738
|
+
const sample2 = DEMO_SAMPLE_IDS.find((id) => id === scope.sample_id);
|
|
1739
|
+
if (sample2 && (!current.ready_demo || input.sample)) {
|
|
1740
|
+
current.demo_visits ??= {};
|
|
1741
|
+
current.demo_visits[sample2] = (current.demo_visits[sample2] ?? 0) + 1;
|
|
1742
|
+
}
|
|
1743
|
+
current.ready_demo = scope;
|
|
1744
|
+
} else delete current.ready_demo;
|
|
2028
1745
|
this.store.save(current);
|
|
2029
1746
|
}
|
|
1747
|
+
if (action === "run" && progress?.state === "in_progress" && current.ready_demo) {
|
|
1748
|
+
try {
|
|
1749
|
+
await writeProgress(this.dependencies, current.host, "check_demo", {
|
|
1750
|
+
demo_project_id: current.ready_demo.project_id
|
|
1751
|
+
});
|
|
1752
|
+
} catch (error) {
|
|
1753
|
+
if (error?.code !== "PLG_DEMO_LICENSE_REQUIRED") throw error;
|
|
1754
|
+
return summary({
|
|
1755
|
+
...account,
|
|
1756
|
+
demo,
|
|
1757
|
+
demo_project_id: current.ready_demo.project_id,
|
|
1758
|
+
phase: "action_required",
|
|
1759
|
+
next_action: "check_demo_license",
|
|
1760
|
+
code: error.code,
|
|
1761
|
+
message: error.message,
|
|
1762
|
+
poll_after_ms: 0
|
|
1763
|
+
});
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
const sample = DEMO_SAMPLE_IDS.find((id) => id === current.sample_id);
|
|
2030
1767
|
return summary({
|
|
2031
1768
|
...account,
|
|
2032
1769
|
demo,
|
|
2033
1770
|
samples: context.samples,
|
|
2034
1771
|
demo_project_id: demo?.project_id ?? null,
|
|
1772
|
+
...demo?.status === "ready" && sample ? { demo_overview: onboardingDemoOverview(sample, current.demo_visits?.[sample] ?? 1) } : {},
|
|
2035
1773
|
evidence: onboardingEvidenceLinks(demo?.evidence, demo?.project_id, webConversation ? void 0 : current.host),
|
|
2036
1774
|
phase: demo?.status === "ready" ? "ready" : demo?.status === "action_required" ? "action_required" : "pending",
|
|
2037
1775
|
next_action: demo?.status === "ready" ? "offer_growth_questions" : demo?.status === "action_required" ? "inspect_demo_preparation" : "poll_demo",
|
|
@@ -2062,7 +1800,8 @@ var OnboardingRuntime = class {
|
|
|
2062
1800
|
phase: "waiting_user",
|
|
2063
1801
|
next_action: "choose_experience",
|
|
2064
1802
|
poll_after_ms: 0,
|
|
2065
|
-
choices
|
|
1803
|
+
choices,
|
|
1804
|
+
...!webConversation ? { demo_entry: onboardingInteraction("demo_entry") } : {}
|
|
2066
1805
|
});
|
|
2067
1806
|
};
|
|
2068
1807
|
return action === "run" ? await this.store.locked(`session:${current.id}`, execute) : await execute();
|
|
@@ -2139,7 +1878,7 @@ var OnboardingRuntime = class {
|
|
|
2139
1878
|
}
|
|
2140
1879
|
return summary({ phase: "waiting_user", next_action: "run_onboarding", poll_after_ms: 0 });
|
|
2141
1880
|
}
|
|
2142
|
-
if (!session.region) return summary({ phase: "action_required", next_action: "choose_market",
|
|
1881
|
+
if (!session.region) return summary({ phase: "action_required", next_action: "choose_market", poll_after_ms: 0 });
|
|
2143
1882
|
const language = session.language_source === "explicit" ? registrationLanguage(session.language) : void 0;
|
|
2144
1883
|
if (!session.bootstrap || Date.parse(session.bootstrap.expires_at) <= this.dependencies.now()) {
|
|
2145
1884
|
const thread = session.source === "codex" && UUID_PATTERN.test(process.env.CODEX_THREAD_ID ?? "") ? process.env.CODEX_THREAD_ID : void 0;
|
|
@@ -2241,7 +1980,7 @@ var OnboardingRuntime = class {
|
|
|
2241
1980
|
if (grant.authorization_status === "expired") return restart("WEBSITE_AUTHORIZATION_EXPIRED");
|
|
2242
1981
|
if (grant.authorization_status !== "approved" && grant.authorization_status !== "claimed") return waiting(grant.authorization_status, grant.poll_after_ms ?? ready.poll_after_ms);
|
|
2243
1982
|
if (grant.host !== issuer || !grant.device_code || !grant.expected_login_name || !grant.expected_company_id || !grant.expires_at || !Number.isFinite(Date.parse(grant.expires_at)) || Date.parse(grant.expires_at) <= this.dependencies.now()) throw new Error("The website device connection does not match this continuation.");
|
|
2244
|
-
const fingerprint =
|
|
1983
|
+
const fingerprint = crypto2.createHash("sha256").update(grant.device_code).digest("hex");
|
|
2245
1984
|
const previous = session.website_device;
|
|
2246
1985
|
if (previous && (previous.fingerprint !== fingerprint || previous.issuer !== issuer || previous.expires_at !== grant.expires_at || previous.expected_login_name !== grant.expected_login_name || previous.expected_company_id !== String(grant.expected_company_id))) {
|
|
2247
1986
|
throw new Error("The website device connection changed. Start a separate connection.");
|
|
@@ -2287,10 +2026,10 @@ var GUIDE_AGENT_ID = "system-agent-onboarding-guide";
|
|
|
2287
2026
|
var SESSION_HOST = "https://onboarding-sandbox.invalid";
|
|
2288
2027
|
function webSessionDirectory(env, cwd) {
|
|
2289
2028
|
const conversationId = env.TE_AGENT_CONVERSATION_ID;
|
|
2290
|
-
if (!conversationId || !/^[\w-]+$/.test(conversationId) ||
|
|
2029
|
+
if (!conversationId || !/^[\w-]+$/.test(conversationId) || path7.basename(cwd) !== conversationId) {
|
|
2291
2030
|
throw new Error("Web onboarding must run in the current AE conversation directory.");
|
|
2292
2031
|
}
|
|
2293
|
-
return
|
|
2032
|
+
return path7.join(cwd, ".ae-onboarding", "cli");
|
|
2294
2033
|
}
|
|
2295
2034
|
async function readTaskActor(host, token, conversationId, signal) {
|
|
2296
2035
|
const legacy = token.startsWith("cli_task_");
|
|
@@ -2311,7 +2050,12 @@ async function readTaskActor(host, token, conversationId, signal) {
|
|
|
2311
2050
|
if (legacy && (payload.return_code !== 0 || payload.data?.task_cli_compat_enabled !== true)) return void 0;
|
|
2312
2051
|
const actor = legacy ? payload.data?.plg_onboarding_actor : payload.actor;
|
|
2313
2052
|
if (typeof actor?.account_id === "string" && actor.account_id && typeof actor.company_id === "string" && actor.company_id && actor.conversation_id === conversationId) {
|
|
2314
|
-
return {
|
|
2053
|
+
return {
|
|
2054
|
+
openId: actor.account_id,
|
|
2055
|
+
issuer: actor.company_id,
|
|
2056
|
+
platformRegion: actor.platform_region === "cn" || actor.platform_region === "overseas" ? actor.platform_region : void 0,
|
|
2057
|
+
market: typeof actor.market === "string" && isWebsiteMarket(actor.market) ? actor.market : void 0
|
|
2058
|
+
};
|
|
2315
2059
|
}
|
|
2316
2060
|
}
|
|
2317
2061
|
async function invokeOnboarding(action, input) {
|
|
@@ -2333,7 +2077,12 @@ async function invokeOnboarding(action, input) {
|
|
|
2333
2077
|
if (external && !token.startsWith("cli_task_") && !external.taskContext) {
|
|
2334
2078
|
throw new Error("Web onboarding requires the current AE task context.");
|
|
2335
2079
|
}
|
|
2336
|
-
const actor = token.startsWith("cli_task_") || external?.taskContext ? await readTaskActor(host, token, process.env.TE_AGENT_CONVERSATION_ID, signal) : {
|
|
2080
|
+
const actor = token.startsWith("cli_task_") || external?.taskContext ? await readTaskActor(host, token, process.env.TE_AGENT_CONVERSATION_ID, signal) : {
|
|
2081
|
+
openId: (await validateCliTokenOnServer(host, token, signal)).account?.openId,
|
|
2082
|
+
issuer: host,
|
|
2083
|
+
platformRegion: void 0,
|
|
2084
|
+
market: void 0
|
|
2085
|
+
};
|
|
2337
2086
|
if (!actor?.openId || external?.taskContext && actor.issuer !== external.taskContext.companyId) {
|
|
2338
2087
|
throw new Error("AE could not verify the current onboarding account.");
|
|
2339
2088
|
}
|
|
@@ -2345,6 +2094,7 @@ async function invokeOnboarding(action, input) {
|
|
|
2345
2094
|
}
|
|
2346
2095
|
const runtime = new OnboardingRuntime(store, {
|
|
2347
2096
|
webConversation: true,
|
|
2097
|
+
demoCurrency: () => onboardingDemoCurrency(host),
|
|
2348
2098
|
activeHost: () => SESSION_HOST,
|
|
2349
2099
|
authenticated: (scope) => scope === SESSION_HOST,
|
|
2350
2100
|
credentialKey: (scope) => scope === SESSION_HOST ? key : void 0,
|
|
@@ -2359,6 +2109,11 @@ async function invokeOnboarding(action, input) {
|
|
|
2359
2109
|
});
|
|
2360
2110
|
const output = await runtime.invoke(action, input);
|
|
2361
2111
|
if (output.host === SESSION_HOST) output.host = null;
|
|
2112
|
+
if (typeof output.language === "string") {
|
|
2113
|
+
const languageMarket = registrationMarket(registrationLanguage(output.language));
|
|
2114
|
+
const overseasMarket = languageMarket === "cn" ? "us" : languageMarket;
|
|
2115
|
+
output.product_resource_market = actor.market ?? (actor.platformRegion === "overseas" ? overseasMarket : actor.platformRegion ?? null);
|
|
2116
|
+
}
|
|
2362
2117
|
return output;
|
|
2363
2118
|
}
|
|
2364
2119
|
export {
|