@thinkingai/ae-cli 6.1.33 → 6.1.35

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 (85) hide show
  1. package/README.md +2 -2
  2. package/README.zh.md +2 -6
  3. package/cli-installation-guide.md +18 -4
  4. package/dist/{ai-monitor-OHTSU6SV.js → ai-monitor-TVRFVZBH.js} +10 -9
  5. package/dist/ai-monitor.js +17 -16
  6. package/dist/{auth-2MOK4OI6.js → auth-JAXLMPBB.js} +25 -317
  7. package/dist/{automation-6L6IAYRK.js → automation-OQ647CSW.js} +7 -6
  8. package/dist/{capability-EMIHQJA3.js → capability-2Z4ZXTPD.js} +18 -16
  9. package/dist/chunk-2H3SFJE3.js +344 -0
  10. package/dist/{chunk-RC3PPCYD.js → chunk-3PZNM5KN.js} +3 -3
  11. package/dist/chunk-3ZQY7SLZ.js +147 -0
  12. package/dist/{chunk-NNK3JBH4.js → chunk-6E6HCTP2.js} +2 -2
  13. package/dist/{local-data-upload-client-YTWMAAGE.js → chunk-6IUTXRAD.js} +32 -4
  14. package/dist/{chunk-VLOGOM7N.js → chunk-CYZV5AXW.js} +8 -5
  15. package/dist/{chunk-O45NOIWR.js → chunk-DE5XHQQ6.js} +2 -2
  16. package/dist/{chunk-KD5UC33N.js → chunk-E5CJI7L3.js} +7 -5
  17. package/dist/{chunk-UCMO4LKL.js → chunk-EQMGH32F.js} +2 -2
  18. package/dist/{chunk-E3ONSFUN.js → chunk-FNACCKQR.js} +211 -12
  19. package/dist/{chunk-2I5SZ5DS.js → chunk-GD5JSAGV.js} +2 -2
  20. package/dist/{chunk-EFGUBGA6.js → chunk-GYODT7C4.js} +1 -1
  21. package/dist/chunk-HBI7IQH3.js +1207 -0
  22. package/dist/{chunk-AMURHMS3.js → chunk-IGU3R2JD.js} +4 -4
  23. package/dist/{chunk-YE6MJB5V.js → chunk-IWMDPHMI.js} +3 -3
  24. package/dist/{chunk-LFJ7N36I.js → chunk-L7MT53VM.js} +5 -3
  25. package/dist/{chunk-HIMOBNEY.js → chunk-LXRALNNA.js} +2 -2
  26. package/dist/{chunk-BQFLABJQ.js → chunk-M2OCZRVX.js} +7 -5
  27. package/dist/{chunk-R2SVAO4G.js → chunk-MTK4ZE7W.js} +3 -143
  28. package/dist/{chunk-7DHSB3FL.js → chunk-NK5PS5X7.js} +3 -3
  29. package/dist/{chunk-HQED4YB4.js → chunk-NPH5J65M.js} +1 -1
  30. package/dist/{chunk-EWVEAERM.js → chunk-Q764EZND.js} +78 -72
  31. package/dist/chunk-QOJXLXDJ.js +55 -0
  32. package/dist/{chunk-THTROEGD.js → chunk-QPUPWGZ3.js} +1 -1
  33. package/dist/{chunk-XZDKAR4N.js → chunk-RLPMXKDQ.js} +8921 -10119
  34. package/dist/{chunk-DWAG2QJM.js → chunk-S74XV3A6.js} +4 -4
  35. package/dist/{chunk-COOMXFUG.js → chunk-SHB7A2JE.js} +3 -3
  36. package/dist/{chunk-PLNS5J33.js → chunk-UWQXGF44.js} +17 -9
  37. package/dist/{data-integration-UNJ7EPW2.js → chunk-V6UKLIM6.js} +160 -2258
  38. package/dist/{chunk-4IQYPWCX.js → chunk-VPLRZSMY.js} +18 -10
  39. package/dist/{chunk-KA5WKR5P.js → chunk-Z6WSCIHM.js} +2 -2
  40. package/dist/{community-report-client-ULRNXLQV.js → community-report-client-5VNT6HCV.js} +4 -2
  41. package/dist/{compat-check-CADG7GND.js → compat-check-E7AQ7UCG.js} +5 -4
  42. package/dist/{config-PFD3KWQG.js → config-PGSUWIK5.js} +15 -11
  43. package/dist/{context-SOQDFZIB.js → context-Y2A6QIS3.js} +5 -4
  44. package/dist/conversion-4FR3RA45.js +16 -0
  45. package/dist/data-integration-EIF5QHYF.js +2138 -0
  46. package/dist/{evaluation-Q3AIGFOG.js → evaluation-OZM54MES.js} +6 -5
  47. package/dist/index.js +74 -51
  48. package/dist/local-data-upload-client-2U3LFD7Z.js +16 -0
  49. package/dist/{memory-HKNGUIPK.js → memory-6QMZS4HF.js} +7 -6
  50. package/dist/{metadata-GFWR5ZHC.js → metadata-7MZ3CJ2N.js} +10 -9
  51. package/dist/{model-NAKQWK4W.js → model-LEYRQKOS.js} +8 -7
  52. package/dist/{personal-semantic-preference-JCTKXLC3.js → personal-semantic-preference-SWOUNDWJ.js} +9 -8
  53. package/dist/{project-semantic-B2NWQOKK.js → project-semantic-M2DDPAMD.js} +9 -8
  54. package/dist/{sync-UQH4J4BD.js → sync-PWC63JCO.js} +16 -15
  55. package/dist/{te-agent-L6EYFQCC.js → te-agent-S7UH657Z.js} +11 -9
  56. package/dist/{te-analysis-U7NNOY66.js → te-analysis-BK6PE333.js} +281 -214
  57. package/dist/{te-community-3UQEW3KD.js → te-community-OLNTKGCW.js} +12 -10
  58. package/dist/{te-dataops-SUNYXF5G.js → te-dataops-XUWRIF5R.js} +12 -10
  59. package/dist/{te-engage-KMXZJ2KN.js → te-engage-I3I4FJOM.js} +9 -8
  60. package/dist/{te-experiment-IEYKP6VC.js → te-experiment-XSDUL4KH.js} +9 -8
  61. package/dist/{te-kb-MT3V5ZMH.js → te-kb-QFH3YLFQ.js} +15 -13
  62. package/dist/{te-system-F4ZU2HRQ.js → te-system-DB5Z3LLF.js} +7 -6
  63. package/dist/{te-team-M6E6XQ5H.js → te-team-UADF2HBO.js} +9 -8
  64. package/dist/{things-FRLBZV2Z.js → things-G2QFXDK7.js} +9 -8
  65. package/dist/{update-NULYHVE6.js → update-6I366ICW.js} +7 -8
  66. package/dist/web-runtime-3XFREWRF.js +2367 -0
  67. package/dist/{workspace-Z7L33OBQ.js → workspace-RZESYB6T.js} +7 -6
  68. package/package.json +4 -3
  69. package/skills/ae-analysis/SKILL.md +1 -1
  70. package/skills/ae-data-integration/references/ue-mapping.md +2 -0
  71. package/skills/ae-onboarding/SKILL.md +64 -0
  72. package/skills/ae-onboarding/references/business-sdk.md +8 -0
  73. package/skills/ae-onboarding/references/demo-operations.md +79 -0
  74. package/skills/ae-onboarding/references/import.md +19 -0
  75. package/skills/ae-onboarding/references/onboarding_experiment_launch.md +12 -0
  76. package/skills/ae-onboarding/references/onboarding_experiment_plan.md +14 -0
  77. package/skills/ae-onboarding/references/onboarding_growth.md +36 -0
  78. package/skills/ae-onboarding/references/onboarding_run.md +11 -0
  79. package/skills/ae-onboarding/references/onboarding_status.md +5 -0
  80. package/skills/ae-onboarding/scripts/experiment-preset.json +252 -0
  81. package/skills/ae-onboarding/scripts/experiment-requests.mjs +120 -0
  82. package/skills/ae-onboarding/scripts/generate.mjs +170 -0
  83. package/skills/ae-onboarding/scripts/resolve-experiment-preset.mjs +26 -0
  84. package/skills/ae-onboarding/scripts/web-journey.mjs +39 -0
  85. package/dist/chunk-6ZIQV5GW.js +0 -26
@@ -0,0 +1,2367 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+ import {
3
+ absolutizeRelativeUrls
4
+ } from "./chunk-QOJXLXDJ.js";
5
+ import {
6
+ fetchSigned
7
+ } from "./chunk-CYZV5AXW.js";
8
+ import {
9
+ CapabilityGatewayError,
10
+ executeCapability
11
+ } from "./chunk-VPLRZSMY.js";
12
+ import "./chunk-6E6HCTP2.js";
13
+ import {
14
+ assembleSyncJsonBody,
15
+ localDataUpload,
16
+ resolveSyncJsonEndpoint
17
+ } from "./chunk-6IUTXRAD.js";
18
+ import {
19
+ authorizeLoginDevice,
20
+ buildVerificationUrl,
21
+ openBrowser,
22
+ pollDeviceToken,
23
+ resolveDeviceSessionRoute
24
+ } from "./chunk-2H3SFJE3.js";
25
+ import {
26
+ CHECKOUT_RECOVERY,
27
+ DEMO_CONTEXT,
28
+ DEMO_ENSURE,
29
+ DEMO_SAMPLE_IDS,
30
+ DEMO_STATUS,
31
+ NETWORK_BUDGET_MS,
32
+ RUN_BUDGET_MS,
33
+ UUID_PATTERN,
34
+ WEBSITE_MARKETS,
35
+ cliEntrySource,
36
+ environmentForWebsiteOrigin,
37
+ fetchCliConfig,
38
+ isProductionWebsiteOrigin,
39
+ normalizeRegistrationLanguage,
40
+ onboardingGrowthScenario,
41
+ registrationLanguage,
42
+ registrationMarket,
43
+ websiteEnvironment,
44
+ websiteOrigin,
45
+ withCliEntryContext
46
+ } from "./chunk-FNACCKQR.js";
47
+ import {
48
+ getLocalCliPackageInfo
49
+ } from "./chunk-PUSFEC6B.js";
50
+ import {
51
+ SecureStoreAuthError,
52
+ assertCredentialsReadable,
53
+ getActiveCredential,
54
+ getCliToken,
55
+ loadCliToken,
56
+ peekCliToken,
57
+ validateCliTokenOnServer
58
+ } from "./chunk-UWQXGF44.js";
59
+ import {
60
+ getActiveHost,
61
+ getConfigDir,
62
+ isAeSandboxRuntime,
63
+ safeJsonParse
64
+ } from "./chunk-IGU3R2JD.js";
65
+ import {
66
+ externalCliTokenRequestOptions,
67
+ readExternalCliToken
68
+ } from "./chunk-MTK4ZE7W.js";
69
+ import {
70
+ CliApiError,
71
+ LocalDataUploadError,
72
+ PermissionError
73
+ } from "./chunk-3ZQY7SLZ.js";
74
+
75
+ // src/core/onboarding/web-runtime.ts
76
+ import { createHash as createHash2 } from "crypto";
77
+ import path8 from "path";
78
+
79
+ // src/core/onboarding/runtime.ts
80
+ import crypto3 from "crypto";
81
+ import path7 from "path";
82
+
83
+ // src/core/onboarding/bootstrap-client.ts
84
+ var PATH = "/backend/demo/v1/experience/cli/bootstrap-intents";
85
+ var BootstrapRequestError = class extends Error {
86
+ constructor(websiteStatus) {
87
+ super(`The onboarding website request failed (HTTP ${websiteStatus}).`);
88
+ this.websiteStatus = websiteStatus;
89
+ }
90
+ websiteStatus;
91
+ };
92
+ function loginMode(value) {
93
+ if (value === void 0 || value === null) return void 0;
94
+ if (value === "website_login" || value === "device_confirmation") return value;
95
+ throw new Error("The website returned an invalid login mode.");
96
+ }
97
+ function authorizationStatus(value) {
98
+ if (value === void 0 || value === null) return void 0;
99
+ if (["pending", "authorizing", "approved", "claimed", "expired"].includes(String(value))) return value;
100
+ throw new Error("The website returned an invalid authorization status.");
101
+ }
102
+ function bootstrapOrigin(market, environment = websiteEnvironment()) {
103
+ return websiteOrigin(market, environment);
104
+ }
105
+ function trustedProductHost(value) {
106
+ const url = new URL(value);
107
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || !["", "/"].includes(url.pathname)) {
108
+ throw new Error("Onboarding requires a trusted HTTPS product origin.");
109
+ }
110
+ return url.origin;
111
+ }
112
+ function websiteUrl(value, origin) {
113
+ const url = new URL(value);
114
+ if (url.origin !== origin || url.username || url.password) throw new Error("The website returned an untrusted continuation URL.");
115
+ return url.toString();
116
+ }
117
+ async function request(origin, endpoint, init, signal) {
118
+ environmentForWebsiteOrigin(origin);
119
+ const response = await fetch(`${origin}${endpoint}`, {
120
+ ...init,
121
+ redirect: "error",
122
+ signal,
123
+ headers: { Accept: "application/json", "Content-Type": "application/json", ...init.headers }
124
+ });
125
+ const body = safeJsonParse(await response.text());
126
+ if (!response.ok || body?.return_code !== 0 || !body.data || typeof body.data !== "object") {
127
+ throw new BootstrapRequestError(response.status);
128
+ }
129
+ return body.data;
130
+ }
131
+ async function createBootstrap(market, source, host, signal, toolReference, environment, language) {
132
+ const origin = bootstrapOrigin(market, environment);
133
+ const tool = cliEntrySource(source);
134
+ if (toolReference && (tool !== "codex" || !UUID_PATTERN.test(toolReference))) throw new Error("Invalid AI tool continuation reference.");
135
+ const data = await request(origin, PATH, { method: "POST", headers: {
136
+ "X-AE-CLI-Login-Mode": "website_login",
137
+ ...language ? { "Accept-Language": language } : {}
138
+ }, body: JSON.stringify({
139
+ market,
140
+ source,
141
+ ...host ? { requested_host: trustedProductHost(host) } : {},
142
+ ...toolReference ? { tool_reference: toolReference } : {}
143
+ }) }, signal);
144
+ if (typeof data.intent_id !== "string" || !UUID_PATTERN.test(data.intent_id) || typeof data.poll_token !== "string" || data.poll_token.length < 16 || !Number.isFinite(Date.parse(data.expires_at))) {
145
+ throw new Error("The website returned an invalid bootstrap session.");
146
+ }
147
+ return { ...data, login_mode: loginMode(data.login_mode), login_url: withCliEntryContext(websiteUrl(data.login_url, origin), tool, market, toolReference) };
148
+ }
149
+ async function readBootstrap(origin, intentId, pollToken, signal, source, market) {
150
+ if (!UUID_PATTERN.test(intentId)) throw new Error("Invalid bootstrap continuation.");
151
+ const data = await request(origin, `${PATH}/${encodeURIComponent(intentId)}`, {
152
+ method: "GET",
153
+ headers: { "X-CLI-Bootstrap-Token": pollToken }
154
+ }, signal);
155
+ if (data.intent_id !== intentId || !["pending", "account_ready", "browser_ready", "expired"].includes(data.status)) throw new Error("Invalid bootstrap state.");
156
+ return {
157
+ ...data,
158
+ login_mode: loginMode(data.login_mode),
159
+ authorization_status: authorizationStatus(data.authorization_status),
160
+ host: data.host ? trustedProductHost(data.host) : null,
161
+ ready_url: data.ready_url ? source ? withCliEntryContext(websiteUrl(data.ready_url, origin), cliEntrySource(source), market) : websiteUrl(data.ready_url, origin) : null
162
+ };
163
+ }
164
+ async function claimBootstrapDevice(origin, intentId, pollToken, signal) {
165
+ if (!UUID_PATTERN.test(intentId)) throw new Error("Invalid bootstrap continuation.");
166
+ const data = await request(origin, `${PATH}/${encodeURIComponent(intentId)}/device`, {
167
+ method: "POST",
168
+ body: "{}",
169
+ headers: { "X-CLI-Bootstrap-Token": pollToken }
170
+ }, signal).catch((error) => {
171
+ if (error instanceof BootstrapRequestError && error.websiteStatus === 410) {
172
+ return { login_mode: "website_login", authorization_status: "expired" };
173
+ }
174
+ throw error;
175
+ });
176
+ if (loginMode(data.login_mode) !== "website_login") throw new Error("The website did not confirm this login mode.");
177
+ const status = authorizationStatus(data.authorization_status);
178
+ if (!status) throw new Error("The website returned an invalid authorization status.");
179
+ if (status !== "approved" && status !== "claimed") return {
180
+ login_mode: "website_login",
181
+ authorization_status: status,
182
+ ...Number.isFinite(data.poll_after_ms) ? { poll_after_ms: data.poll_after_ms } : {}
183
+ };
184
+ if (typeof data.device_code !== "string" || !/^uba_[A-Za-z0-9_-]{43}$/.test(data.device_code) || typeof data.user_code !== "string" || !/^[A-HJ-NP-Z2-9]{8}$/.test(data.user_code) || !Number.isFinite(Date.parse(data.expires_at)) || !Number.isFinite(data.interval) || data.interval < 1 || data.interval > 60 || typeof data.expected_login_name !== "string" || !data.expected_login_name.trim() || data.expected_login_name.length > 256 || !/^[1-9][0-9]*$/.test(String(data.expected_company_id)) || !Number.isSafeInteger(Number(data.expected_company_id))) throw new Error("The website returned an invalid device connection.");
185
+ return {
186
+ login_mode: "website_login",
187
+ authorization_status: status,
188
+ host: trustedProductHost(data.host),
189
+ device_code: data.device_code,
190
+ user_code: data.user_code,
191
+ expires_at: data.expires_at,
192
+ interval: data.interval,
193
+ expected_login_name: data.expected_login_name,
194
+ expected_company_id: String(data.expected_company_id)
195
+ };
196
+ }
197
+
198
+ // src/core/onboarding/website-login-identity.ts
199
+ async function verifyWebsiteLoginIdentity(host, accessToken, expected, signal) {
200
+ const origin = trustedProductHost(host);
201
+ if (!accessToken || !expected.login_name || !/^[1-9][0-9]*$/.test(expected.company_id) || !Number.isSafeInteger(Number(expected.company_id))) throw new Error("Website login identity is incomplete.");
202
+ try {
203
+ const response = await fetch(`${origin}/v1/oauth/check`, {
204
+ method: "POST",
205
+ redirect: "error",
206
+ signal,
207
+ body: "{}",
208
+ headers: { Accept: "application/json", Authorization: `bearer ${accessToken}`, "Content-Type": "application/x-www-form-urlencoded" }
209
+ });
210
+ const body = safeJsonParse(await response.text());
211
+ if (!response.ok || body?.return_code !== 0 || typeof body.data?.loginName !== "string" || body.data.cliAccessEnabled === false || !/^[1-9][0-9]*$/.test(String(body.data?.belongCompanyId)) || !Number.isSafeInteger(Number(body.data.belongCompanyId)) || body.data.loginName !== expected.login_name || String(body.data.belongCompanyId) !== expected.company_id) {
212
+ throw new Error("Identity mismatch.");
213
+ }
214
+ } catch {
215
+ signal.throwIfAborted();
216
+ throw new Error("The website login account or company could not be verified. Credentials were not saved.");
217
+ }
218
+ }
219
+
220
+ // src/core/onboarding/session-store.ts
221
+ import fs from "fs";
222
+ import path from "path";
223
+ import crypto from "crypto";
224
+ var OnboardingStore = class {
225
+ constructor(directory = path.join(getConfigDir(), "plg")) {
226
+ this.directory = directory;
227
+ }
228
+ directory;
229
+ ensureDirectory(directory = this.directory) {
230
+ fs.mkdirSync(directory, { recursive: true, mode: 448 });
231
+ if (fs.lstatSync(directory).isSymbolicLink()) throw new Error("Onboarding storage cannot be a symbolic link.");
232
+ if (process.platform !== "win32") fs.chmodSync(directory, 448);
233
+ }
234
+ file(name) {
235
+ if (!/^[a-zA-Z0-9_-]+\.json$/.test(name)) throw new Error("Invalid local onboarding reference.");
236
+ return path.join(this.directory, name);
237
+ }
238
+ read(name) {
239
+ const file = this.file(name);
240
+ try {
241
+ const info = fs.lstatSync(file);
242
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 65536) throw new Error("Unsafe onboarding record.");
243
+ if (process.platform !== "win32" && info.mode & 63) throw new Error("Onboarding record permissions must be private.");
244
+ return JSON.parse(fs.readFileSync(file, "utf8"));
245
+ } catch (error) {
246
+ if (error.code === "ENOENT") return void 0;
247
+ throw new Error("The local onboarding record is unreadable. Preserve it and use a new continuation.");
248
+ }
249
+ }
250
+ write(name, value) {
251
+ this.ensureDirectory();
252
+ const file = this.file(name);
253
+ if (fs.existsSync(file) && fs.lstatSync(file).isSymbolicLink()) throw new Error("Unsafe onboarding record.");
254
+ const temp = this.file(`tmp-${crypto.randomUUID()}.json`);
255
+ try {
256
+ fs.writeFileSync(temp, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
257
+ fs.renameSync(temp, file);
258
+ if (process.platform !== "win32") fs.chmodSync(file, 384);
259
+ } finally {
260
+ if (fs.existsSync(temp)) fs.unlinkSync(temp);
261
+ }
262
+ }
263
+ remove(name) {
264
+ const file = this.file(name);
265
+ if (fs.existsSync(file) && !fs.lstatSync(file).isSymbolicLink()) fs.unlinkSync(file);
266
+ }
267
+ session(id, host) {
268
+ if (id) {
269
+ if (!UUID_PATTERN.test(id)) throw new Error("Invalid local onboarding session identifier.");
270
+ const value = this.read(`session-${id}.json`);
271
+ if (!value || value.schema_version !== 1 || value.id !== id) throw new Error("Local onboarding session was not found.");
272
+ if (host && value.host && value.host !== host) throw new Error("The continuation belongs to another AE host.");
273
+ return value;
274
+ }
275
+ if (!fs.existsSync(this.directory)) return void 0;
276
+ const values = fs.readdirSync(this.directory).filter((name) => /^session-[0-9a-f-]+\.json$/i.test(name)).flatMap((name) => {
277
+ try {
278
+ const value = this.read(name);
279
+ return value?.schema_version === 1 ? [value] : [];
280
+ } catch {
281
+ return [];
282
+ }
283
+ });
284
+ const matching = values.filter((value) => host ? value.host === host : !value.host);
285
+ return matching.sort((a, b) => b.updated_at.localeCompare(a.updated_at))[0];
286
+ }
287
+ save(session) {
288
+ session.updated_at = (/* @__PURE__ */ new Date()).toISOString();
289
+ this.write(`session-${session.id}.json`, session);
290
+ }
291
+ async locked(key, action) {
292
+ this.ensureDirectory();
293
+ const directory = path.join(this.directory, `lock-${crypto.createHash("sha256").update(key).digest("hex")}`);
294
+ try {
295
+ fs.mkdirSync(directory, { mode: 448 });
296
+ } catch (error) {
297
+ if (error.code !== "EEXIST") throw error;
298
+ let stale = false;
299
+ try {
300
+ const owner = JSON.parse(fs.readFileSync(path.join(directory, "owner.json"), "utf8"));
301
+ if (Number.isInteger(owner.pid) && owner.pid > 0) {
302
+ try {
303
+ process.kill(owner.pid, 0);
304
+ } catch (failure) {
305
+ stale = failure.code === "ESRCH";
306
+ }
307
+ }
308
+ } catch {
309
+ try {
310
+ if (Date.now() - fs.statSync(directory).mtimeMs > 6e4 && fs.readdirSync(directory).length === 0) {
311
+ fs.rmdirSync(directory);
312
+ return this.locked(key, action);
313
+ }
314
+ } catch {
315
+ }
316
+ }
317
+ if (!stale) throw new Error("Another local onboarding operation is active. Retry after it returns.");
318
+ fs.rmSync(directory, { recursive: true });
319
+ return this.locked(key, action);
320
+ }
321
+ const ownerId = crypto.randomUUID();
322
+ try {
323
+ fs.writeFileSync(path.join(directory, "owner.json"), JSON.stringify({ pid: process.pid, id: ownerId }), { mode: 384, flag: "wx" });
324
+ return await action();
325
+ } finally {
326
+ try {
327
+ if (JSON.parse(fs.readFileSync(path.join(directory, "owner.json"), "utf8")).id === ownerId) fs.rmSync(directory, { recursive: true });
328
+ } catch {
329
+ }
330
+ }
331
+ }
332
+ };
333
+
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
+ // src/core/onboarding/experiment-launch.ts
745
+ import { createHash } from "crypto";
746
+ import path5 from "path";
747
+ import { isDeepStrictEqual } from "util";
748
+
749
+ // skills/ae-onboarding/scripts/experiment-preset.json
750
+ var experiment_preset_default = {
751
+ industries: {
752
+ game: {
753
+ samples: {
754
+ "star-island": {
755
+ itemId: "starlight-bundle",
756
+ userCount: 140,
757
+ experimentTypes: [
758
+ "item-coupon",
759
+ "checkout-recovery"
760
+ ],
761
+ followUpAccountIds: [
762
+ "star-island-user-1",
763
+ "star-island-user-2",
764
+ "star-island-user-3",
765
+ "star-island-user-4",
766
+ "star-island-user-5",
767
+ "star-island-user-6",
768
+ "star-island-user-7",
769
+ "star-island-user-8",
770
+ "star-island-user-9",
771
+ "star-island-user-10",
772
+ "star-island-user-11",
773
+ "star-island-user-12",
774
+ "star-island-user-13",
775
+ "star-island-user-14",
776
+ "star-island-user-15",
777
+ "star-island-user-16",
778
+ "star-island-user-17",
779
+ "star-island-user-18",
780
+ "star-island-user-131",
781
+ "star-island-user-132",
782
+ "star-island-user-133",
783
+ "star-island-user-134",
784
+ "star-island-user-135",
785
+ "star-island-user-136",
786
+ "star-island-user-137",
787
+ "star-island-user-138",
788
+ "star-island-user-139",
789
+ "star-island-user-140"
790
+ ],
791
+ netRevenueMetricId: "plg_net_revenue_star_island"
792
+ },
793
+ "season-pass": {
794
+ itemId: "season-pass-item",
795
+ userCount: 120,
796
+ experimentTypes: [
797
+ "item-coupon",
798
+ "checkout-recovery"
799
+ ],
800
+ followUpAccountIds: [
801
+ "season-pass-user-1",
802
+ "season-pass-user-2",
803
+ "season-pass-user-3",
804
+ "season-pass-user-4",
805
+ "season-pass-user-5",
806
+ "season-pass-user-6",
807
+ "season-pass-user-7",
808
+ "season-pass-user-8",
809
+ "season-pass-user-9",
810
+ "season-pass-user-10",
811
+ "season-pass-user-11",
812
+ "season-pass-user-12",
813
+ "season-pass-user-101",
814
+ "season-pass-user-102",
815
+ "season-pass-user-103",
816
+ "season-pass-user-104",
817
+ "season-pass-user-105",
818
+ "season-pass-user-106",
819
+ "season-pass-user-107",
820
+ "season-pass-user-108",
821
+ "season-pass-user-109",
822
+ "season-pass-user-110",
823
+ "season-pass-user-111",
824
+ "season-pass-user-112",
825
+ "season-pass-user-113",
826
+ "season-pass-user-114",
827
+ "season-pass-user-115",
828
+ "season-pass-user-116",
829
+ "season-pass-user-117",
830
+ "season-pass-user-118",
831
+ "season-pass-user-119",
832
+ "season-pass-user-120"
833
+ ],
834
+ netRevenueMetricId: "plg_net_revenue_season_pass"
835
+ }
836
+ }
837
+ }
838
+ },
839
+ experimentTypes: {
840
+ "item-coupon": {
841
+ audience: {
842
+ bucketId: "#account_id",
843
+ viewEvent: "item_detail_view",
844
+ minimumViewDays: 2,
845
+ excludeEvent: "payment_success"
846
+ },
847
+ durationDays: 7,
848
+ allocation: 100,
849
+ currency: "CNY",
850
+ costPerPaidOrder: 50,
851
+ otherCosts: 0,
852
+ arms: {
853
+ control: {
854
+ featureValue: "full_price",
855
+ allocation: 50,
856
+ price: 100,
857
+ exposureLimit: 12,
858
+ couponClaims: 0,
859
+ paidUsers: 1,
860
+ name: "Full-price reminder"
861
+ },
862
+ treatment: {
863
+ featureValue: "coupon_20",
864
+ allocation: 50,
865
+ price: 80,
866
+ exposureLimit: 12,
867
+ couponClaims: 8,
868
+ paidUsers: 7,
869
+ name: "20% coupon"
870
+ }
871
+ },
872
+ events: {
873
+ exposure: "te_experiment_exposure",
874
+ couponClaim: "demo_coupon_claim",
875
+ payment: "payment_success"
876
+ },
877
+ exposureProperties: [
878
+ [
879
+ "experiment_id",
880
+ "string",
881
+ "#experiment_id"
882
+ ],
883
+ [
884
+ "experiment_group_id",
885
+ "string",
886
+ "#experiment_group_id"
887
+ ],
888
+ [
889
+ "is_control_group",
890
+ "boolean",
891
+ "#is_control_group"
892
+ ]
893
+ ],
894
+ metrics: [
895
+ {
896
+ role: "primary",
897
+ event: "payment_success",
898
+ aggregation: "user_count",
899
+ format: "integer"
900
+ },
901
+ {
902
+ role: "secondary",
903
+ event: "payment_success",
904
+ aggregation: "sum",
905
+ property: "amount",
906
+ format: "float2"
907
+ }
908
+ ],
909
+ metricFilters: [
910
+ "plg_sample_id",
911
+ "item_id"
912
+ ],
913
+ runFilter: "demo_run_id",
914
+ orderKey: "order_id",
915
+ feature: {
916
+ type: "string",
917
+ targetPlatform: [
918
+ "client"
919
+ ],
920
+ keyPrefix: "plg_offer",
921
+ displayName: "Demo offer"
922
+ },
923
+ experiment: {
924
+ name: "Demo offer A/B",
925
+ hypothesis: "An item-specific 20% coupon increases the number of buyers.",
926
+ atlasType: "feature"
927
+ }
928
+ },
929
+ "checkout-recovery": {
930
+ audience: {
931
+ bucketId: "#account_id",
932
+ viewEvent: "item_detail_view",
933
+ minimumViewDays: 1,
934
+ checkoutEvent: "checkout_start",
935
+ excludeEvent: "payment_success"
936
+ },
937
+ durationDays: 7,
938
+ allocation: 100,
939
+ currency: "CNY",
940
+ costPerPaidOrder: 50,
941
+ otherCosts: 0,
942
+ arms: {
943
+ control: {
944
+ featureValue: "product_details",
945
+ allocation: 50,
946
+ price: 100,
947
+ paidUsers: 2,
948
+ name: "Reminder to product details"
949
+ },
950
+ treatment: {
951
+ featureValue: "direct_checkout",
952
+ allocation: 50,
953
+ price: 100,
954
+ paidUsers: 4,
955
+ name: "Reminder directly to checkout"
956
+ }
957
+ },
958
+ events: {
959
+ exposure: "te_experiment_exposure",
960
+ payment: "payment_success"
961
+ },
962
+ exposureProperties: [
963
+ ["experiment_id", "string", "#experiment_id"],
964
+ ["experiment_group_id", "string", "#experiment_group_id"],
965
+ ["is_control_group", "boolean", "#is_control_group"]
966
+ ],
967
+ metrics: [
968
+ {
969
+ role: "primary",
970
+ event: "payment_success",
971
+ aggregation: "user_count",
972
+ format: "integer"
973
+ },
974
+ {
975
+ role: "secondary",
976
+ event: "payment_success",
977
+ aggregation: "sum",
978
+ property: "amount",
979
+ format: "float2"
980
+ }
981
+ ],
982
+ metricFilters: [
983
+ "plg_sample_id",
984
+ "item_id"
985
+ ],
986
+ runFilter: "demo_run_id",
987
+ orderKey: "order_id",
988
+ feature: {
989
+ type: "string",
990
+ targetPlatform: ["client"],
991
+ keyPrefix: "plg_checkout",
992
+ displayName: "Demo checkout recovery"
993
+ },
994
+ experiment: {
995
+ name: "Demo checkout recovery A/B",
996
+ hypothesis: "At the same price, sending checkout abandoners directly to checkout increases the number of buyers.",
997
+ atlasType: "feature"
998
+ }
999
+ }
1000
+ }
1001
+ };
1002
+
1003
+ // src/core/onboarding/experiment-plan.ts
1004
+ import { randomUUID } from "crypto";
1005
+ import path3 from "path";
1006
+ var PROJECT_INFO = "project.info.get";
1007
+ var APPROVER_ADD = "experiment.approver.add";
1008
+ function readyDemoScope(demo, session) {
1009
+ 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
+ return {
1011
+ sample_id: demo.sample_id,
1012
+ item_id: demo.item_id,
1013
+ project_id: demo.project_id,
1014
+ start_date: demo.start_date,
1015
+ end_date: demo.end_date,
1016
+ zone_offset: demo.zone_offset
1017
+ };
1018
+ }
1019
+ async function runOnboardingExperimentPlan(store, deps, input, preview) {
1020
+ const scenario = onboardingGrowthScenario(input.scenario);
1021
+ if (scenario === CHECKOUT_RECOVERY && input.upload_metric_event) {
1022
+ throw new Error("Checkout recovery prepares the plan locally. Use experiment-launch after the user confirms it.");
1023
+ }
1024
+ const sessionId = input.session_id;
1025
+ if (!sessionId) throw new Error("A valid onboarding --session-id is required.");
1026
+ const explicitHost = input.host ? trustedProductHost(input.host) : void 0;
1027
+ if (preview) {
1028
+ const session = store.session(sessionId, explicitHost);
1029
+ return {
1030
+ dry_run: true,
1031
+ session_id: sessionId,
1032
+ host: session.host ?? null,
1033
+ sample_id: session.sample_id ?? null,
1034
+ ...input.scenario ? { scenario } : {},
1035
+ capabilities: [
1036
+ ...session.ready_demo ? [] : [DEMO_STATUS],
1037
+ ...input.upload_metric_event ? [PROJECT_INFO] : [],
1038
+ APPROVER_ADD
1039
+ ],
1040
+ ...input.upload_metric_event ? { metric_event: { event_name: "payment_success", record_count: 1 } } : {}
1041
+ };
1042
+ }
1043
+ return store.locked(`session:${sessionId}`, async () => {
1044
+ const session = store.session(sessionId, explicitHost);
1045
+ const base = { session_id: sessionId, host: session.host ?? null, sample_id: session.sample_id ?? null };
1046
+ const host = session.host && trustedProductHost(session.host);
1047
+ if (!host || !session.credential_key || session.requires_auth || deps.credentialKey(host) !== session.credential_key) {
1048
+ return { ...base, phase: "action_required", next_action: "resume_onboarding" };
1049
+ }
1050
+ if (session.choice !== "demo" || !session.sample_id) {
1051
+ return { ...base, phase: "action_required", next_action: "choose_demo" };
1052
+ }
1053
+ let scope = readyDemoScope({ ...session.ready_demo, status: "ready" }, session);
1054
+ if (!scope) {
1055
+ const demo = await deps.capability(
1056
+ host,
1057
+ DEMO_STATUS,
1058
+ { sample_id: session.sample_id },
1059
+ AbortSignal.timeout(NETWORK_BUDGET_MS)
1060
+ );
1061
+ if (demo?.sample_id === session.sample_id && demo.status && demo.status !== "ready") {
1062
+ return demo.status === "action_required" ? { ...base, phase: "action_required", next_action: "inspect_demo_preparation" } : { ...base, phase: "pending", next_action: "poll_demo", poll_after_ms: 2e3 };
1063
+ }
1064
+ scope = readyDemoScope(demo, session);
1065
+ if (!scope) throw new Error("AE did not confirm the active Demo project and item.");
1066
+ if (deps.credentialKey(host) !== session.credential_key) throw new Error("The active CLI account changed while reading Demo status.");
1067
+ session.ready_demo = scope;
1068
+ store.save(session);
1069
+ }
1070
+ const sampleId = scope.sample_id;
1071
+ const selection = Object.entries(experiment_preset_default.industries).flatMap(([industry, { samples }]) => Object.entries(samples).map(([id, sample]) => ({ industry, id, sample }))).find(({ id, sample }) => id === sampleId && sample.itemId === scope.item_id);
1072
+ if (!selection || !selection.sample.experimentTypes.includes(scenario)) {
1073
+ throw new Error("The active Demo sample and item have no supported experiment preset.");
1074
+ }
1075
+ const preset = experiment_preset_default.experimentTypes[scenario];
1076
+ const checkoutCohort = scenario === CHECKOUT_RECOVERY ? readCheckoutRecoveryCohort(store, session, scope) : void 0;
1077
+ if (scenario === CHECKOUT_RECOVERY && !checkoutCohort) {
1078
+ return {
1079
+ ...base,
1080
+ phase: "action_required",
1081
+ next_action: "run_checkout_recovery_growth",
1082
+ message: "Run onboarding growth with --scenario checkout-recovery for the active Demo first."
1083
+ };
1084
+ }
1085
+ if (checkoutCohort && checkoutCohort.account_ids.length < 2) {
1086
+ return {
1087
+ ...base,
1088
+ phase: "action_required",
1089
+ next_action: "choose_growth_scenario",
1090
+ message: "Checkout recovery needs at least two eligible Demo accounts.",
1091
+ interaction: onboardingInteraction("offer_growth_questions")
1092
+ };
1093
+ }
1094
+ const eventId = randomUUID();
1095
+ const runId = eventId.replaceAll("-", "");
1096
+ const result = {
1097
+ ...base,
1098
+ phase: "ready",
1099
+ next_action: "confirm_experiment",
1100
+ demo_project_id: scope.project_id,
1101
+ item_id: scope.item_id,
1102
+ industry: selection.industry,
1103
+ experiment_type: scenario,
1104
+ run_id: runId,
1105
+ interaction: onboardingInteraction("confirm_experiment"),
1106
+ plan: {
1107
+ synthetic: true,
1108
+ hypothesis: preset.experiment.hypothesis,
1109
+ audience_count: checkoutCohort?.account_ids.length ?? selection.sample.followUpAccountIds.length,
1110
+ audience: {
1111
+ minimum_view_days: preset.audience.minimumViewDays,
1112
+ view_event: preset.audience.viewEvent,
1113
+ exclude_event: preset.audience.excludeEvent,
1114
+ ...checkoutCohort ? {
1115
+ checkout_event: experiment_preset_default.experimentTypes[CHECKOUT_RECOVERY].audience.checkoutEvent,
1116
+ start_date: checkoutCohort.start_date,
1117
+ end_date: checkoutCohort.end_date
1118
+ } : {}
1119
+ },
1120
+ duration_days: preset.durationDays,
1121
+ allocation: preset.allocation,
1122
+ bucket_id: preset.audience.bucketId,
1123
+ arms: Object.entries(preset.arms).map(([role, arm]) => ({ role, name: arm.name, allocation: arm.allocation, price: arm.price })),
1124
+ metrics: preset.metrics,
1125
+ currency: preset.currency,
1126
+ cost_per_paid_order: preset.costPerPaidOrder,
1127
+ other_costs: preset.otherCosts
1128
+ }
1129
+ };
1130
+ const { control, treatment } = preset.arms;
1131
+ const planPreviewMarkdown = [
1132
+ "| A \xB7 Control | B \xB7 Treatment |",
1133
+ "| --- | --- |",
1134
+ `| ${control.name} | ${treatment.name} |`,
1135
+ `| ${control.price} ${preset.currency} \xB7 ${control.allocation}% | ${treatment.price} ${preset.currency} \xB7 ${treatment.allocation}% |`
1136
+ ].join("\n");
1137
+ const file = `experiment-plan-${runId}.json`;
1138
+ const planPath = path3.resolve(store.directory, file);
1139
+ const metricEvent = input.upload_metric_event ? { event_name: preset.events.payment, event_id: eventId, persistence_verified: false } : void 0;
1140
+ store.write(file, {
1141
+ ...result,
1142
+ ...checkoutCohort ? { checkout_cohort: checkoutCohort, credential_key: session.credential_key } : {},
1143
+ ...metricEvent ? { metric_event: { ...metricEvent, status: "pending" } } : {},
1144
+ approver: { status: "pending" }
1145
+ });
1146
+ const [approver, delivery] = await Promise.all([
1147
+ prepareDemoApprover(deps, host, session.credential_key, scope.project_id),
1148
+ metricEvent ? uploadPlanPayment(deps, host, session.credential_key, scope, {
1149
+ "#type": "track",
1150
+ "#event_name": metricEvent.event_name,
1151
+ "#account_id": selection.sample.followUpAccountIds[0],
1152
+ "#time": new Date(deps.now()).toISOString().slice(0, -1).replace("T", " "),
1153
+ "#uuid": eventId,
1154
+ properties: {
1155
+ "#zone_offset": 0,
1156
+ plg_sample_id: sampleId,
1157
+ item_id: scope.item_id,
1158
+ amount: preset.arms.control.price,
1159
+ currency: preset.currency,
1160
+ order_id: eventId
1161
+ }
1162
+ }) : void 0
1163
+ ]);
1164
+ const preparedPlan = {
1165
+ ...result,
1166
+ approver,
1167
+ ...delivery ? { metric_event: { ...metricEvent, ...delivery } } : {}
1168
+ };
1169
+ store.write(file, {
1170
+ ...preparedPlan,
1171
+ ...checkoutCohort ? { checkout_cohort: checkoutCohort, credential_key: session.credential_key } : {}
1172
+ });
1173
+ return { ...preparedPlan, plan_path: planPath, plan_preview_markdown: planPreviewMarkdown };
1174
+ });
1175
+ }
1176
+ async function prepareDemoApprover(deps, host, credentialKey, projectId) {
1177
+ try {
1178
+ const signal = AbortSignal.timeout(NETWORK_BUDGET_MS);
1179
+ const openId = await deps.approverOpenId(host, signal);
1180
+ signal.throwIfAborted();
1181
+ if (!openId) throw new Error("The signed-in account has no available open ID.");
1182
+ if (deps.credentialKey(host) !== credentialKey) throw new Error("The active CLI account changed while preparing the approver.");
1183
+ const response = await deps.capability(host, APPROVER_ADD, { project_id: projectId, approvers: [openId] }, signal);
1184
+ signal.throwIfAborted();
1185
+ if (response?.result !== true) throw new Error("The Demo project did not acknowledge the approver registration.");
1186
+ return { status: "ready" };
1187
+ } catch (error) {
1188
+ return {
1189
+ status: "failed",
1190
+ message: error instanceof Error ? error.message : "Demo approver registration failed.",
1191
+ ...error instanceof CliApiError || error instanceof PermissionError ? { code: error.code } : {}
1192
+ };
1193
+ }
1194
+ }
1195
+ async function uploadPlanPayment(deps, host, credentialKey, scope, event) {
1196
+ let endpoint;
1197
+ let appid;
1198
+ try {
1199
+ const project = await deps.capability(host, PROJECT_INFO, { project_id: scope.project_id }, AbortSignal.timeout(NETWORK_BUDGET_MS));
1200
+ if (project?.project_id !== scope.project_id || typeof project.appid !== "string" || !project.appid.trim() || project.appid.trim().length > 256 || typeof project.public_receiver_address !== "string") {
1201
+ return { status: "not_sent", reason: "demo_receiver_unavailable" };
1202
+ }
1203
+ const receiver = project.public_receiver_address.trim().replace(/\/+$/, "");
1204
+ if (!receiver) return { status: "not_sent", reason: "demo_receiver_unavailable" };
1205
+ endpoint = resolveSyncJsonEndpoint(receiver.endsWith("/sync_json") ? receiver : `${receiver}/sync_json`);
1206
+ appid = project.appid.trim();
1207
+ if (deps.credentialKey(host) !== credentialKey) return { status: "not_sent", reason: "account_changed" };
1208
+ } catch {
1209
+ return { status: "not_sent", reason: "demo_receiver_unavailable" };
1210
+ }
1211
+ try {
1212
+ await deps.upload(endpoint, assembleSyncJsonBody([JSON.stringify(event)], appid));
1213
+ return { status: "receiver_accepted" };
1214
+ } catch (error) {
1215
+ if (error instanceof LocalDataUploadError) {
1216
+ return { status: error.meta?.delivery_state ?? "unknown", code: error.code };
1217
+ }
1218
+ return { status: "unknown" };
1219
+ }
1220
+ }
1221
+
1222
+ // src/core/onboarding/experiment-replay.ts
1223
+ import { execFile } from "child_process";
1224
+ import { mkdtemp, readFile, rm, writeFile } from "fs/promises";
1225
+ import path4 from "path";
1226
+ import { promisify } from "util";
1227
+ var exec = promisify(execFile);
1228
+ var OUTCOME_DELAY_MS = 5e3;
1229
+ async function runExperimentScript(script, args) {
1230
+ const { root } = getLocalCliPackageInfo();
1231
+ if (!root) throw new Error("The PLG preset scripts could not be located in this CLI package.");
1232
+ const { stdout } = await exec(
1233
+ process.execPath,
1234
+ [path4.join(root, "skills", "ae-onboarding", "scripts", script), ...args],
1235
+ { timeout: 15e3 }
1236
+ );
1237
+ return stdout;
1238
+ }
1239
+ async function prepareExperimentReplay(options) {
1240
+ const receiver = options.receiver.trim().replace(/\/+$/, "");
1241
+ const endpoint = resolveSyncJsonEndpoint(receiver.endsWith("/sync_json") ? receiver : `${receiver}/sync_json`);
1242
+ const offsetMinutes = Math.round(options.zoneOffset * 60);
1243
+ const hours = String(Math.floor(Math.abs(offsetMinutes) / 60)).padStart(2, "0");
1244
+ const minutes = String(Math.abs(offsetMinutes) % 60).padStart(2, "0");
1245
+ const timezone = `${offsetMinutes < 0 ? "-" : "+"}${hours}:${minutes}`;
1246
+ const now = options.now();
1247
+ const offsetMs = offsetMinutes * 6e4;
1248
+ const midnight = Math.floor((now + offsetMs) / 864e5) * 864e5 - offsetMs;
1249
+ const experimentStart = Date.parse(options.startTime);
1250
+ if (!Number.isFinite(experimentStart) || experimentStart > now) throw new Error("The running experiment has no elapsed start time.");
1251
+ const start = Math.max(experimentStart, midnight, now - OUTCOME_DELAY_MS);
1252
+ const end = start + OUTCOME_DELAY_MS;
1253
+ const directory = await mkdtemp(path4.join(options.directory, "experiment-replay-"));
1254
+ try {
1255
+ const cohort = path4.join(directory, "cohort.json");
1256
+ const replay = path4.join(directory, "replay");
1257
+ await writeFile(cohort, JSON.stringify(options.accountIds), { mode: 384 });
1258
+ await runExperimentScript("generate.mjs", [
1259
+ "--phase=plg-experiment-today",
1260
+ `--run-id=${options.runId}`,
1261
+ `--industry=${options.industry}`,
1262
+ `--experiment-type=${options.experimentType}`,
1263
+ `--sample-id=${options.sampleId}`,
1264
+ `--item-id=${options.itemId}`,
1265
+ `--cohort-file=${cohort}`,
1266
+ `--experiment-id=${options.experimentId}`,
1267
+ `--control-id=${options.controlId}`,
1268
+ `--treatment-id=${options.treatmentId}`,
1269
+ `--start=${new Date(start).toISOString()}`,
1270
+ `--end=${new Date(end).toISOString()}`,
1271
+ `--timezone=${timezone}`,
1272
+ `--output-dir=${replay}`
1273
+ ]);
1274
+ const receipt = JSON.parse(await readFile(path4.join(replay, "plg-experiment-receipt.json"), "utf8"));
1275
+ const mapping = JSON.parse(await readFile(path4.join(replay, "replay.mapping.json"), "utf8"));
1276
+ const { convertLocalData } = await import("./conversion-4FR3RA45.js");
1277
+ const converted = await convertLocalData({
1278
+ inputFile: path4.join(replay, "replay.jsonl"),
1279
+ mapping,
1280
+ outputDir: path4.join(directory, "converted"),
1281
+ now: new Date(options.now())
1282
+ });
1283
+ const rows = (await readFile(path4.join(converted.output_dir, converted.manifest.output.valid_file), "utf8")).trim().split("\n");
1284
+ const count = receipt.event_uuids.exposure.length + receipt.event_uuids.outcomes.length;
1285
+ if (converted.status !== "ready" || count === 0 || converted.manifest.output.invalid_records !== 0 || rows.length !== count || converted.manifest.output.valid_records !== count) {
1286
+ throw new Error("The complete Demo replay did not pass data conversion.");
1287
+ }
1288
+ return { endpoint, body: assembleSyncJsonBody(rows, options.appid), receipt, count };
1289
+ } finally {
1290
+ await rm(directory, { recursive: true, force: true });
1291
+ }
1292
+ }
1293
+
1294
+ // src/core/onboarding/experiment-launch.ts
1295
+ function isApprovalBlocker(error) {
1296
+ return error instanceof SecureStoreAuthError || error instanceof PermissionError || error instanceof CapabilityGatewayError && (error.httpStatus === 401 || error.httpStatus === 403 || error.type === "validation");
1297
+ }
1298
+ var SUBSCRIPTION_RETRY_DELAYS_MS = [500, 1e3, 1500, 2e3, 3e3, 4e3];
1299
+ function matchesMetric(item, metric) {
1300
+ return item?.metric_id === metric.metricId && item.format === metric.format && item.metric_purpose === metric.metricPurpose && isDeepStrictEqual(item.metric_definition, metric.metricDefinition);
1301
+ }
1302
+ async function runOnboardingExperimentLaunch(store, deps, input, preview) {
1303
+ const { session_id: sessionId, run_id: runId } = input;
1304
+ if (!sessionId || !UUID_PATTERN.test(sessionId) || !runId || !/^[0-9a-f]{32}$/.test(runId)) {
1305
+ throw new Error("Pass the onboarding session ID and the run ID returned by experiment-plan.");
1306
+ }
1307
+ const hostOverride = input.host ? trustedProductHost(input.host) : void 0;
1308
+ const readSession = () => store.session(sessionId, hostOverride);
1309
+ const execute = async (session) => {
1310
+ const plan = store.read(`experiment-plan-${runId}.json`);
1311
+ 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) {
1313
+ throw new Error("The saved experiment plan does not match the active Demo session and sample.");
1314
+ }
1315
+ const host = trustedProductHost(session.host);
1316
+ const project = { project_id: scope.project_id };
1317
+ const checkoutCohort = plan.experiment_type === CHECKOUT_RECOVERY ? plan.checkout_cohort : void 0;
1318
+ if (plan.experiment_type === CHECKOUT_RECOVERY && (!checkoutCohort || plan.credential_key !== session.credential_key || !Array.isArray(checkoutCohort.account_ids) || checkoutCohort.account_ids.length < 2)) {
1319
+ throw new Error("The checkout recovery plan no longer matches the verified Demo scope.");
1320
+ }
1321
+ const summary = {
1322
+ session_id: sessionId,
1323
+ run_id: runId,
1324
+ host,
1325
+ demo_project_id: scope.project_id,
1326
+ sample_id: scope.sample_id,
1327
+ item_id: scope.item_id,
1328
+ ...checkoutCohort ? { experiment_type: plan.experiment_type } : {}
1329
+ };
1330
+ if (preview) return { ...summary, dry_run: true, steps: [
1331
+ ...checkoutCohort ? ["check_other_demo_experiment", "verify_demo_scope"] : [],
1332
+ "save_metrics_and_feature",
1333
+ "save_draft",
1334
+ "check_readiness",
1335
+ "submit_approval",
1336
+ ...plan.approver ? [] : ["add_signed_in_approver_if_needed"],
1337
+ "approve",
1338
+ "start",
1339
+ ...input.start_only ? [] : ["upload_one_replay_batch"]
1340
+ ] };
1341
+ const key = session.credential_key;
1342
+ const checkAccount = () => {
1343
+ if (!key || session.requires_auth || deps.credentialKey(host) !== key) {
1344
+ throw new Error("Resume onboarding with the signed-in account that generated the Demo plan.");
1345
+ }
1346
+ };
1347
+ const request2 = async (id, params) => {
1348
+ checkAccount();
1349
+ const signal = AbortSignal.timeout(NETWORK_BUDGET_MS);
1350
+ const response = await deps.capability(host, id, params, signal);
1351
+ signal.throwIfAborted();
1352
+ return response;
1353
+ };
1354
+ checkAccount();
1355
+ const stateFile = `experiment-launch-${runId}.json`;
1356
+ const progress = store.read(stateFile) ?? { timings_ms: {} };
1357
+ const persist = () => store.write(stateFile, progress);
1358
+ const result = (phase) => ({
1359
+ ...summary,
1360
+ ...progress,
1361
+ phase,
1362
+ ...progress.experiment_id && (progress.experiment_status === "running" || progress.replay) ? {
1363
+ experiment_url: onboardingExperimentUrl(scope.project_id, progress.experiment_id, deps.webConversation ? void 0 : host)
1364
+ } : {},
1365
+ replay_receipt_path: progress.replay ? path5.resolve(store.directory, `experiment-replay-${runId}.json`) : void 0
1366
+ });
1367
+ const completed = () => ({
1368
+ ...result("complete"),
1369
+ experiment_status: "running",
1370
+ approval_state: "approved",
1371
+ persistence_verified: false,
1372
+ next_action: "verify_experiment_results"
1373
+ });
1374
+ const started = () => ({ ...result("running"), approval_state: "approved", next_action: "upload_experiment_replay" });
1375
+ if (progress.replay?.status === "receiver_accepted") return completed();
1376
+ if (progress.replay) return { ...result("action_required"), next_action: "reconcile_replay_delivery" };
1377
+ let stage = "prepare_requests";
1378
+ const call = (id, params = {}) => request2(id, { ...project, ...params });
1379
+ const measure = async (name, action) => {
1380
+ const start = deps.now();
1381
+ try {
1382
+ return await action();
1383
+ } finally {
1384
+ progress.timings_ms[name] = (progress.timings_ms[name] ?? 0) + Math.max(0, deps.now() - start);
1385
+ persist();
1386
+ }
1387
+ };
1388
+ const timed = (name, action) => {
1389
+ stage = name;
1390
+ return measure(name, action);
1391
+ };
1392
+ const saveMetric = async (metric) => {
1393
+ try {
1394
+ if ((await call("experiment.metric.save", { req: metric })).result !== true) throw new Error("Metric save was not acknowledged.");
1395
+ } catch (error) {
1396
+ const existing = await call("experiment.metric.get", { metric_id: metric.metricId }).catch(() => void 0);
1397
+ if (!matchesMetric(existing?.item, metric)) throw error;
1398
+ }
1399
+ };
1400
+ try {
1401
+ stage = "check_other_demo_experiment";
1402
+ const otherType = plan.experiment_type === CHECKOUT_RECOVERY ? "item-coupon" : CHECKOUT_RECOVERY;
1403
+ const otherName = experiment_preset_default.experimentTypes[otherType].experiment.name;
1404
+ const [otherExperiments, currentDemo] = await Promise.all([
1405
+ progress.experiment_status ? void 0 : call("experiment.experiment.list", { query_name: otherName }).catch((error) => {
1406
+ if (!checkoutCohort && error instanceof CapabilityGatewayError && error.code === "CAPABILITY_NOT_FOUND") return { items: [] };
1407
+ throw error;
1408
+ }),
1409
+ checkoutCohort && !progress.experiment_status ? request2(DEMO_STATUS, { sample_id: scope.sample_id }) : void 0
1410
+ ]);
1411
+ if (!progress.experiment_status && !Array.isArray(otherExperiments?.items)) {
1412
+ throw new Error("AE did not return the Demo experiment list.");
1413
+ }
1414
+ const active = otherExperiments?.items.find((item) => typeof item?.exp_name === "string" && item.exp_name.startsWith(`${otherName} (`) && item.status !== "draft" && item.status !== "ended" && item.status !== "archive");
1415
+ if (active) return {
1416
+ ...result("action_required"),
1417
+ next_action: "wait_for_other_demo_experiment",
1418
+ message: "Finish the other growth experiment for this Demo before starting this one.",
1419
+ ...typeof active.exp_id === "string" && active.exp_id ? {
1420
+ active_experiment_url: onboardingExperimentUrl(scope.project_id, active.exp_id, deps.webConversation ? void 0 : host)
1421
+ } : {}
1422
+ };
1423
+ if (checkoutCohort && !progress.experiment_status) {
1424
+ stage = "verify_demo_scope";
1425
+ const verified = readyDemoScope(currentDemo, session);
1426
+ if (!verified || verified.item_id !== scope.item_id || verified.project_id !== scope.project_id || verified.start_date !== checkoutCohort.start_date || verified.end_date !== checkoutCohort.end_date || verified.zone_offset !== checkoutCohort.zone_offset) {
1427
+ return {
1428
+ ...result("action_required"),
1429
+ next_action: "run_checkout_recovery_growth",
1430
+ message: "The Demo scope changed. Refresh growth analysis and confirm a new experiment plan."
1431
+ };
1432
+ }
1433
+ }
1434
+ stage = "prepare_requests";
1435
+ const requestsFile = `experiment-requests-${runId}.json`;
1436
+ let requests = store.read(requestsFile);
1437
+ if (!requests) {
1438
+ const inputFile = `experiment-input-${runId}.json`;
1439
+ store.write(inputFile, {
1440
+ industry: plan.industry,
1441
+ experimentType: plan.experiment_type,
1442
+ sampleId: plan.sample_id,
1443
+ itemId: plan.item_id,
1444
+ runId,
1445
+ ...checkoutCohort ? { accountIds: checkoutCohort.account_ids } : {}
1446
+ });
1447
+ const generated = JSON.parse(await runExperimentScript("experiment-requests.mjs", [path5.join(store.directory, inputFile)]));
1448
+ store.write(requestsFile, generated);
1449
+ requests = generated;
1450
+ }
1451
+ const preset = requests;
1452
+ const projectInfo = input.start_only ? void 0 : Promise.allSettled([call("project.info.get")]);
1453
+ const revenueKey = createHash("sha256").update(JSON.stringify([host, scope.project_id, preset.revenueMetric])).digest("hex");
1454
+ const revenueFile = `experiment-revenue-${revenueKey}.json`;
1455
+ if (!store.read(revenueFile)) await timed("save_revenue_metric", async () => {
1456
+ await saveMetric(preset.revenueMetric);
1457
+ store.write(revenueFile, { metric_id: preset.revenueMetric.metricId });
1458
+ });
1459
+ const assetSaves = [];
1460
+ if (!progress.feature) assetSaves.push(["save_feature", measure("save_feature", async () => {
1461
+ try {
1462
+ if ((await call("experiment.feature.save", { req: preset.feature })).result !== true) throw new Error("Feature save was not acknowledged.");
1463
+ } catch (error) {
1464
+ const existing = await call("experiment.feature.get", { feature_key: preset.feature.featureKey }).catch(() => void 0);
1465
+ if (existing?.item?.feature_key !== preset.feature.featureKey || existing.item.display_name !== preset.feature.displayName) throw error;
1466
+ }
1467
+ progress.feature = true;
1468
+ })]);
1469
+ if (!progress.metric) assetSaves.push(["save_primary_metric", measure("save_primary_metric", async () => {
1470
+ await saveMetric(preset.metric);
1471
+ progress.metric = true;
1472
+ })]);
1473
+ const outcomes = await Promise.allSettled(assetSaves.map(([, save]) => save));
1474
+ for (const [index, outcome] of outcomes.entries()) {
1475
+ if (outcome.status === "rejected") {
1476
+ stage = assetSaves[index][0];
1477
+ throw outcome.reason;
1478
+ }
1479
+ }
1480
+ if (!progress.experiment_id) await timed("save_experiment", async () => {
1481
+ if (progress.draft_attempted) {
1482
+ const found = await call("experiment.experiment.list", { query_name: preset.experiment.expName });
1483
+ const matches = found.items?.filter((item) => item.exp_name === preset.experiment.expName);
1484
+ if (matches?.length === 1 && typeof matches[0].exp_id === "string" && matches[0].exp_id) {
1485
+ progress.experiment_id = matches[0].exp_id;
1486
+ return;
1487
+ }
1488
+ if (matches?.length !== 0) throw new Error("The previous experiment save could not be reconciled to a unique draft.");
1489
+ }
1490
+ progress.draft_attempted = true;
1491
+ persist();
1492
+ const draft = await call("experiment.experiment.save", { req: preset.experiment });
1493
+ if (typeof draft.result !== "string" || !draft.result) throw new Error("Experiment save returned no experiment ID.");
1494
+ progress.experiment_id = draft.result;
1495
+ });
1496
+ const exp = { exp_id: progress.experiment_id };
1497
+ const approval = async () => (await call("experiment.approval.get", exp)).item;
1498
+ const verifyRound = (round) => {
1499
+ 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)) {
1500
+ throw new Error("The approval round does not match this Demo draft.");
1501
+ }
1502
+ progress.approval_id = round.approval_id;
1503
+ persist();
1504
+ };
1505
+ if (!progress.experiment_status) await timed("approve_experiment", async () => {
1506
+ let round = progress.submission_attempted ? await approval() : void 0;
1507
+ if (!round) {
1508
+ if (progress.approval_id) throw new Error("The saved approval round is unavailable.");
1509
+ const readiness = (await call("experiment.experiment.ready-check", exp)).readiness;
1510
+ if (readiness?.valid !== true) throw new Error("The Demo experiment did not pass readiness checks.");
1511
+ progress.submission_attempted = true;
1512
+ persist();
1513
+ await call("experiment.approval.submit", exp);
1514
+ round = await approval();
1515
+ }
1516
+ verifyRound(round);
1517
+ if (round.state === "approved") return;
1518
+ if (round.state !== "pending_review") throw new Error(`The Demo approval is ${round.state}.`);
1519
+ if (!round.can_approve) {
1520
+ if (plan.approver) throw new Error("The signed-in account cannot approve this round. Check the Demo approver registration.");
1521
+ const openId = await deps.approverOpenId(host, AbortSignal.timeout(NETWORK_BUDGET_MS));
1522
+ if (!openId) throw new Error("The signed-in account has no available open ID.");
1523
+ await call("experiment.approver.add", { approvers: [openId] });
1524
+ round = await approval();
1525
+ verifyRound(round);
1526
+ if (round.state === "approved") return;
1527
+ if (round.state !== "pending_review" || !round.can_approve) throw new Error("The signed-in account cannot approve this round.");
1528
+ }
1529
+ let shouldApprove = true;
1530
+ let acknowledged = false;
1531
+ let delayMs = 500;
1532
+ for (; ; ) {
1533
+ if (shouldApprove) {
1534
+ checkAccount();
1535
+ try {
1536
+ acknowledged = (await call("experiment.approval.approve", { ...exp, approval_id: progress.approval_id })).result === true;
1537
+ } catch (error) {
1538
+ if (isApprovalBlocker(error)) throw error;
1539
+ }
1540
+ }
1541
+ shouldApprove = false;
1542
+ checkAccount();
1543
+ try {
1544
+ round = await approval();
1545
+ } catch (error) {
1546
+ if (isApprovalBlocker(error)) throw error;
1547
+ round = void 0;
1548
+ }
1549
+ if (round) {
1550
+ verifyRound(round);
1551
+ if (round.state === "approved") return;
1552
+ if (round.state !== "pending_review") throw new Error(`The Demo approval is ${round.state}.`);
1553
+ if (!acknowledged && !round.can_approve) throw new Error("The signed-in account cannot approve this round.");
1554
+ shouldApprove = !acknowledged;
1555
+ }
1556
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
1557
+ delayMs = Math.min(delayMs * 2, 1e4);
1558
+ }
1559
+ });
1560
+ const effective = await timed("start_experiment", async () => {
1561
+ const detail = async () => (await call("experiment.experiment.get", exp)).item;
1562
+ let item = await detail();
1563
+ if (item?.exp_id !== exp.exp_id) throw new Error("The active experiment does not match the saved draft.");
1564
+ if (item.status === "pending") {
1565
+ for (const [attempt, delay] of [0, ...SUBSCRIPTION_RETRY_DELAYS_MS].entries()) {
1566
+ if (delay) {
1567
+ await new Promise((resolve) => setTimeout(resolve, delay));
1568
+ item = await detail();
1569
+ if (item?.exp_id !== exp.exp_id || item.status !== "pending") break;
1570
+ }
1571
+ try {
1572
+ await call("experiment.experiment.manage", { ...exp, target_status: "running" });
1573
+ item = await detail();
1574
+ break;
1575
+ } catch (error) {
1576
+ if (!(error instanceof Error) || !/subscription\.notReady|subscription is not ready/i.test(error.message) || attempt === SUBSCRIPTION_RETRY_DELAYS_MS.length) throw error;
1577
+ }
1578
+ }
1579
+ }
1580
+ if (item?.exp_id !== exp.exp_id || item.status !== "running") throw new Error("The experiment has not reached running status.");
1581
+ progress.experiment_status = "running";
1582
+ return item;
1583
+ });
1584
+ if (!projectInfo) return started();
1585
+ await timed("upload_replay", async () => {
1586
+ const [lookup] = await projectInfo;
1587
+ if (lookup.status === "rejected") throw lookup.reason;
1588
+ const info = lookup.value;
1589
+ const zoneOffset = info?.default_time_zone_offset;
1590
+ if (info?.project_id !== scope.project_id || typeof zoneOffset !== "number" || !Number.isFinite(zoneOffset) || Math.abs(zoneOffset) > 14 || typeof info.appid !== "string" || !info.appid.trim() || info.appid.trim().length > 256 || typeof info.public_receiver_address !== "string" || !info.public_receiver_address.trim()) {
1591
+ throw new Error("The Demo project did not return a verified receiver, APPID and timezone.");
1592
+ }
1593
+ const controlId = effective.groups?.find((group) => group.is_control === 1)?.exp_group_id;
1594
+ const treatmentId = effective.groups?.find((group) => group.is_control === 0)?.exp_group_id;
1595
+ if (typeof controlId !== "string" || typeof treatmentId !== "string" || controlId === treatmentId) {
1596
+ throw new Error("The running experiment did not return both group IDs.");
1597
+ }
1598
+ const replay = await prepareExperimentReplay({
1599
+ directory: store.directory,
1600
+ runId,
1601
+ industry: plan.industry,
1602
+ experimentType: plan.experiment_type,
1603
+ sampleId: plan.sample_id,
1604
+ itemId: plan.item_id,
1605
+ experimentId: exp.exp_id,
1606
+ controlId,
1607
+ treatmentId,
1608
+ startTime: effective.start_time,
1609
+ accountIds: preset.experiment.targeting.definitionRequest.conditions.items.map((item) => item.values[0]),
1610
+ zoneOffset,
1611
+ appid: info.appid.trim(),
1612
+ receiver: info.public_receiver_address,
1613
+ now: deps.now
1614
+ });
1615
+ checkAccount();
1616
+ store.write(`experiment-replay-${runId}.json`, replay.receipt);
1617
+ progress.replay = { status: "unknown", record_count: replay.count };
1618
+ persist();
1619
+ try {
1620
+ await deps.upload(replay.endpoint, replay.body);
1621
+ } catch (error) {
1622
+ if (error instanceof LocalDataUploadError && error.meta?.delivery_state === "not_accepted") delete progress.replay;
1623
+ throw error;
1624
+ }
1625
+ progress.replay.status = "receiver_accepted";
1626
+ });
1627
+ return completed();
1628
+ } catch (error) {
1629
+ return {
1630
+ ...result("action_required"),
1631
+ failed_stage: stage,
1632
+ next_action: progress.replay ? "reconcile_replay_delivery" : "resume_experiment_launch",
1633
+ error: {
1634
+ message: error instanceof Error ? error.message : "The experiment workflow failed.",
1635
+ ...error instanceof CliApiError || error instanceof LocalDataUploadError ? { code: error.code } : {}
1636
+ }
1637
+ };
1638
+ }
1639
+ };
1640
+ return preview ? execute(readSession()) : store.locked(`session:${sessionId}`, async () => {
1641
+ const session = readSession();
1642
+ return session.ready_demo && session.host ? store.locked(`experiment:${session.host}:${session.ready_demo.project_id}`, () => execute(session)) : execute(session);
1643
+ });
1644
+ }
1645
+
1646
+ // src/core/onboarding/workspace-projects.ts
1647
+ import fs2 from "fs";
1648
+ import path6 from "path";
1649
+ var ignored = /* @__PURE__ */ new Set(["node_modules", "vendor", "dist", "build", "Library", "Packages", "Temp", "obj", "Assets"]);
1650
+ function identifyWorkspaceProjects(root = process.cwd()) {
1651
+ const projects = [];
1652
+ const pending = [{ directory: root, depth: 0 }];
1653
+ let visited = 0;
1654
+ while (pending.length && visited++ < 500 && projects.length < 30) {
1655
+ const { directory, depth } = pending.shift();
1656
+ let entries;
1657
+ try {
1658
+ entries = fs2.readdirSync(directory, { withFileTypes: true });
1659
+ } catch {
1660
+ continue;
1661
+ }
1662
+ const files = new Set(entries.filter((entry) => entry.isFile()).map((entry) => entry.name));
1663
+ const relative = path6.relative(root, directory) || ".";
1664
+ if (entries.some((entry) => entry.name === "Assets" && entry.isDirectory()) && entries.some((entry) => entry.name === "ProjectSettings" && entry.isDirectory())) {
1665
+ projects.push({ directory: relative, platform: "unity", evidence: "Assets/, ProjectSettings/" });
1666
+ }
1667
+ const packageManifest = files.has("package.json") ? readManifest(path6.join(directory, "package.json")) : void 0;
1668
+ const dependencies = { ...packageManifest?.dependencies, ...packageManifest?.devDependencies };
1669
+ const hasBrowser = files.has("index.html") || Object.keys(dependencies).some((name) => ["vite", "next", "react-dom", "vue", "@angular/core", "phaser", "pixi.js"].includes(name));
1670
+ 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));
1671
+ if (hasBrowser) projects.push({ directory: relative, platform: "web", evidence: files.has("index.html") ? "index.html" : "package.json" });
1672
+ if (hasServer) projects.push({ directory: relative, platform: "nodejs", evidence: "server entry or package.json" });
1673
+ if (depth < 4) {
1674
+ for (const entry of entries) {
1675
+ if (entry.isDirectory() && !entry.name.startsWith(".") && !ignored.has(entry.name)) {
1676
+ pending.push({ directory: path6.join(directory, entry.name), depth: depth + 1 });
1677
+ }
1678
+ }
1679
+ }
1680
+ }
1681
+ return projects;
1682
+ }
1683
+ function readManifest(filename) {
1684
+ try {
1685
+ if (fs2.statSync(filename).size <= 1024 * 1024) return JSON.parse(fs2.readFileSync(filename, "utf8"));
1686
+ } catch {
1687
+ }
1688
+ return void 0;
1689
+ }
1690
+
1691
+ // src/core/onboarding/browser-policy.ts
1692
+ function readBrowserMode(value) {
1693
+ if (value === void 0 || value === "auto" || value === "agent" || value === "system") return "system";
1694
+ throw new Error("Unsupported onboarding browser. Use auto, agent, or system.");
1695
+ }
1696
+ function onboardingBrowserPolicy(input) {
1697
+ const base = {
1698
+ owner: "cli",
1699
+ target: input.target,
1700
+ attempted_this_call: false,
1701
+ open_command_succeeded: null,
1702
+ agent_action: "guide_existing_window"
1703
+ };
1704
+ if (!input.new_page) return base;
1705
+ if (input.system_open_allowed === false || !input.open_system) {
1706
+ return { ...base, agent_action: "show_fallback_link" };
1707
+ }
1708
+ let succeeded = false;
1709
+ try {
1710
+ succeeded = input.open_system() === true;
1711
+ } catch {
1712
+ }
1713
+ return {
1714
+ ...base,
1715
+ attempted_this_call: true,
1716
+ open_command_succeeded: succeeded,
1717
+ agent_action: succeeded ? "guide_existing_window" : "show_fallback_link"
1718
+ };
1719
+ }
1720
+
1721
+ // src/core/onboarding/runtime.ts
1722
+ function agentVerificationUrl(base, authorization, language) {
1723
+ let issuer;
1724
+ try {
1725
+ issuer = new URL(base);
1726
+ } catch {
1727
+ throw new Error("The selected Agent authentication issuer is invalid.");
1728
+ }
1729
+ if (!["http:", "https:"].includes(issuer.protocol) || issuer.username || issuer.password || /[?#]/.test(issuer.href)) {
1730
+ throw new Error("The selected Agent authentication issuer is unsafe.");
1731
+ }
1732
+ if (typeof authorization.user_code !== "string" || !/^[\x21-\x7e]{1,128}$/.test(authorization.user_code)) {
1733
+ throw new Error("The Agent returned an invalid user code.");
1734
+ }
1735
+ const target = new URL(buildVerificationUrl(issuer.toString(), authorization.user_code, authorization.device_code.startsWith("uba_") ? "uba" : "legacy"));
1736
+ if (language) target.searchParams.set("locale", language);
1737
+ return target.href;
1738
+ }
1739
+ function readyAccountHost(state, expectedHost) {
1740
+ if (state.status !== "account_ready" && state.status !== "browser_ready") return void 0;
1741
+ if (!state.host) throw new Error("The website did not return a trusted product host.");
1742
+ const host = trustedProductHost(state.host);
1743
+ if (expectedHost && expectedHost !== host) throw new Error("The verified account belongs to another product host. Start a separate continuation.");
1744
+ return host;
1745
+ }
1746
+ function clearAccountScope(session) {
1747
+ delete session.project_id;
1748
+ delete session.bootstrap;
1749
+ delete session.device;
1750
+ delete session.requires_auth;
1751
+ delete session.website_device;
1752
+ delete session.choice;
1753
+ delete session.sample_id;
1754
+ delete session.ready_demo;
1755
+ delete session.confirmed_business_project_id;
1756
+ }
1757
+ var defaults = {
1758
+ activeHost: () => readExternalCliToken()?.url ?? getActiveHost(),
1759
+ authenticated(host) {
1760
+ if (readExternalCliToken(host)) return true;
1761
+ if (process.env.TE_AGENT_CLI_CONFIG_DIR !== void 0) return Boolean(peekCliToken(host));
1762
+ assertCredentialsReadable(host);
1763
+ return Boolean(loadCliToken(host));
1764
+ },
1765
+ credentialKey(host) {
1766
+ const token = readExternalCliToken(host)?.token ?? (process.env.TE_AGENT_CLI_CONFIG_DIR !== void 0 ? peekCliToken(host) : loadCliToken(host));
1767
+ return token ? crypto3.createHash("sha256").update(token).digest("hex") : void 0;
1768
+ },
1769
+ machineLoginAllowed: (host) => !readExternalCliToken(host),
1770
+ createBootstrap,
1771
+ readBootstrap,
1772
+ claimBootstrapDevice,
1773
+ verifyWebsiteLoginIdentity,
1774
+ authorize: authorizeLoginDevice,
1775
+ poll: (issuer, code, signal) => pollDeviceToken(issuer, code, code.startsWith("uba_") ? "uba" : "legacy", signal),
1776
+ async persist(host, tokens, signal) {
1777
+ const { persistDeviceTokens, activateHostAfterLogin } = await import("./auth-JAXLMPBB.js");
1778
+ await persistDeviceTokens(host, tokens, { signal, checkCompatibility: false });
1779
+ activateHostAfterLogin(host, host);
1780
+ },
1781
+ upload: localDataUpload,
1782
+ async approverOpenId(host, signal) {
1783
+ const external = readExternalCliToken(host);
1784
+ const stored = !external && process.env.TE_AGENT_CLI_CONFIG_DIR === void 0 ? getActiveCredential(host) : null;
1785
+ if (stored?.account?.openId) return stored.account.openId;
1786
+ const token = external?.token ?? await getCliToken(host, signal);
1787
+ return (await validateCliTokenOnServer(host, token, signal)).account?.openId;
1788
+ },
1789
+ capability: (host, id, input, signal) => executeCapability(host, id.startsWith("experiment.") ? "engage" : "analysis", id, input, { signal }),
1790
+ async compatibility(host, signal) {
1791
+ const config = await fetchCliConfig(host, await getCliToken(host, signal), signal);
1792
+ signal.throwIfAborted();
1793
+ return config ? { current: getLocalCliPackageInfo().version, expected: config.aeCliVersion, cluster: config.clusterVersion } : void 0;
1794
+ },
1795
+ open: openBrowser,
1796
+ now: Date.now
1797
+ };
1798
+ var OnboardingRuntime = class {
1799
+ constructor(store = new OnboardingStore(), dependencies = {}) {
1800
+ this.store = store;
1801
+ this.dependencies = { ...defaults, ...dependencies };
1802
+ }
1803
+ store;
1804
+ dependencies;
1805
+ async invoke(action, input) {
1806
+ if (action === "growth" || action === "growth-plan") {
1807
+ return runOnboardingGrowth(this.store, this.dependencies, input, action === "growth-plan");
1808
+ }
1809
+ if (action === "experiment-plan" || action === "experiment-plan-preview") {
1810
+ return runOnboardingExperimentPlan(this.store, this.dependencies, input, action === "experiment-plan-preview");
1811
+ }
1812
+ if (action === "experiment-launch" || action === "experiment-launch-preview") {
1813
+ return runOnboardingExperimentLaunch(this.store, this.dependencies, input, action === "experiment-launch-preview");
1814
+ }
1815
+ const browserMode = readBrowserMode(input.browser);
1816
+ const webConversation = this.dependencies.webConversation;
1817
+ if (input.choice && input.choice !== "demo" && input.choice !== "business") throw new Error("Choose demo or business.");
1818
+ if (input.sample && !DEMO_SAMPLE_IDS.some((sample) => sample === input.sample)) throw new Error("Unknown demo sample.");
1819
+ if (input.choice === "business" && input.sample) throw new Error("A sample requires the demo choice.");
1820
+ if (input.language && !normalizeRegistrationLanguage(input.language)) throw new Error("Unsupported onboarding language. Use zh-CN, en-US, ja-JP, or ko-KR.");
1821
+ 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
+ const explicitHost = input.host ? trustedProductHost(input.host) : void 0;
1824
+ let session = this.store.session(input.session_id, explicitHost);
1825
+ let host = explicitHost ?? session?.host;
1826
+ if (!host) {
1827
+ const active = this.dependencies.activeHost();
1828
+ const activeCandidate = active ? trustedProductHost(active) : void 0;
1829
+ host = activeCandidate && (action === "plan" || this.dependencies.authenticated(activeCandidate)) ? activeCandidate : void 0;
1830
+ }
1831
+ if (!session) session = this.store.session(void 0, host);
1832
+ if (session?.website_env === "test" || session?.bootstrap && !isProductionWebsiteOrigin(session.bootstrap.origin)) {
1833
+ if (input.session_id || session.host || session.project_id || session.device || session.credential_key) {
1834
+ throw new Error("This onboarding session is bound to a previous website environment. To use an existing account, sign in with ae-cli auth login --host <url>.");
1835
+ }
1836
+ session = void 0;
1837
+ }
1838
+ const source = cliEntrySource(input.source ?? session?.source);
1839
+ const language = registrationLanguage(input.language ?? session?.language);
1840
+ const defaultMarket = registrationMarket(language);
1841
+ const registrationOrigin = webConversation ? null : websiteOrigin(input.region ?? session?.region ?? defaultMarket, selectedWebsiteEnv);
1842
+ if (action === "plan") return {
1843
+ dry_run: true,
1844
+ host: host ?? null,
1845
+ market: input.region ?? session?.region ?? (!host ? defaultMarket : null),
1846
+ language,
1847
+ default_market: defaultMarket,
1848
+ markets: WEBSITE_MARKETS,
1849
+ selection_source: input.region ? "explicit" : session?.region_source ?? (session?.region ? "saved" : !host ? "language_default" : "existing_host"),
1850
+ website_env: selectedWebsiteEnv,
1851
+ website_origin: registrationOrigin,
1852
+ 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"],
1853
+ browser_mode: browserMode,
1854
+ capabilities: [DEMO_CONTEXT, DEMO_ENSURE, DEMO_STATUS],
1855
+ requires_node: ">=20"
1856
+ };
1857
+ 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
+ const newSession = (market) => ({
1859
+ schema_version: 1,
1860
+ id: crypto3.randomUUID(),
1861
+ host,
1862
+ browser: browserMode,
1863
+ source,
1864
+ region: market ?? (!host ? defaultMarket : void 0),
1865
+ language,
1866
+ language_source: input.language ? "explicit" : "system",
1867
+ website_env: selectedWebsiteEnv,
1868
+ region_source: market ? "explicit" : !host ? "language_default" : void 0,
1869
+ updated_at: new Date(this.dependencies.now()).toISOString()
1870
+ });
1871
+ if (!session) session = newSession(input.region);
1872
+ const credentialKey = host && this.dependencies.authenticated(host) ? this.dependencies.credentialKey(host) : void 0;
1873
+ if (credentialKey && session.credential_key && credentialKey !== session.credential_key) {
1874
+ clearAccountScope(session);
1875
+ }
1876
+ if (credentialKey) session.credential_key = credentialKey;
1877
+ session.host ??= host;
1878
+ if (!session.region) {
1879
+ session.region = input.region ?? (!session.host && action === "run" ? defaultMarket : void 0);
1880
+ if (session.region) session.region_source = input.region ? "explicit" : "language_default";
1881
+ }
1882
+ session.language = language;
1883
+ if (input.language) session.language_source = "explicit";
1884
+ session.source = source;
1885
+ session.website_env ??= selectedWebsiteEnv;
1886
+ session.browser = browserMode;
1887
+ let current = session;
1888
+ const startedAt = this.dependencies.now();
1889
+ const controller = new AbortController();
1890
+ const timer = setTimeout(() => controller.abort(), RUN_BUDGET_MS);
1891
+ timer.unref();
1892
+ const network = async (operation) => {
1893
+ const child = new AbortController();
1894
+ const abort = () => child.abort();
1895
+ controller.signal.addEventListener("abort", abort, { once: true });
1896
+ if (controller.signal.aborted) child.abort();
1897
+ const requestTimer = setTimeout(abort, NETWORK_BUDGET_MS);
1898
+ requestTimer.unref();
1899
+ try {
1900
+ child.signal.throwIfAborted();
1901
+ const value = await operation(child.signal);
1902
+ child.signal.throwIfAborted();
1903
+ return value;
1904
+ } finally {
1905
+ clearTimeout(requestTimer);
1906
+ controller.signal.removeEventListener("abort", abort);
1907
+ }
1908
+ };
1909
+ let browserOpening;
1910
+ const summary = (extra) => {
1911
+ const target = typeof extra.verification_url === "string" ? { name: "device_authorization", url: extra.verification_url } : typeof extra.login_url === "string" ? { name: "website_login", url: extra.login_url } : void 0;
1912
+ const opening = target && browserOpening?.url === target.url ? browserOpening : void 0;
1913
+ const interaction = typeof extra.next_action === "string" ? onboardingInteraction(extra.next_action, webConversation) : void 0;
1914
+ return {
1915
+ language: current.language ?? language,
1916
+ market: current.region ?? null,
1917
+ default_market: defaultMarket,
1918
+ website_env: current.website_env,
1919
+ markets: WEBSITE_MARKETS,
1920
+ selection_source: current.region_source ?? (current.region ? "saved" : "existing_host"),
1921
+ ...extra,
1922
+ skill_path: path7.join(getLocalCliPackageInfo().root, "skills", "ae-onboarding", "SKILL.md"),
1923
+ ...interaction ? { interaction } : {},
1924
+ ...target ? { browser: opening?.receipt ?? extra.browser ?? onboardingBrowserPolicy({ target: target.name, new_page: false }) } : {},
1925
+ session_id: current.id,
1926
+ host: current.host ?? null,
1927
+ project_id: current.project_id ?? null
1928
+ };
1929
+ };
1930
+ const open = (url, target) => {
1931
+ controller.signal.throwIfAborted();
1932
+ const receipt = onboardingBrowserPolicy({
1933
+ target,
1934
+ new_page: true,
1935
+ system_open_allowed: this.dependencies.now() - startedAt + 5e3 < RUN_BUDGET_MS,
1936
+ open_system: () => this.dependencies.open(url)
1937
+ });
1938
+ browserOpening = { url, receipt };
1939
+ return receipt.open_command_succeeded === true;
1940
+ };
1941
+ try {
1942
+ const execute = async () => {
1943
+ const marketChanged = input.region && current.region && input.region !== current.region;
1944
+ if (marketChanged) {
1945
+ if (action !== "run" || input.session_id || current.host || current.project_id || current.credential_key || current.device) {
1946
+ throw new Error("The continuation is bound to another market. Keep the existing account environment and resume its original continuation.");
1947
+ }
1948
+ if (current.bootstrap) {
1949
+ const previous = await network((signal) => this.dependencies.readBootstrap(current.bootstrap.origin, current.bootstrap.intent_id, current.bootstrap.poll_token, signal, current.source, current.region));
1950
+ if (previous.host || !["pending", "expired"].includes(previous.status)) {
1951
+ return summary({
1952
+ phase: "action_required",
1953
+ next_action: "resume_existing_registration",
1954
+ code: "REGISTRATION_MARKET_BOUND",
1955
+ login_url: previous.ready_url ?? current.bootstrap.login_url,
1956
+ poll_after_ms: 0
1957
+ });
1958
+ }
1959
+ }
1960
+ const previousRegionSource = current.region_source;
1961
+ current = newSession(input.region ?? current.region);
1962
+ if (!input.region) current.region_source = previousRegionSource;
1963
+ return this.store.locked(`session:${current.id}`, execute);
1964
+ }
1965
+ if (action === "run") {
1966
+ this.store.save(current);
1967
+ }
1968
+ let completedLogin = {};
1969
+ let loginChangedCredential = false;
1970
+ if (current.requires_auth || !current.host || !this.dependencies.authenticated(current.host)) {
1971
+ if (!this.dependencies.machineLoginAllowed(current.host)) return summary({ phase: "action_required", next_action: "replace_external_cli_token", code: "EXTERNAL_CLI_TOKEN_ACTIVE", poll_after_ms: 0 });
1972
+ const result = await this.authentication(action, current, summary, network, open);
1973
+ if (action !== "run" || result.phase !== "pending" || result.next_action !== "run_onboarding" || result.poll_after_ms !== 0 || !current.host || !this.dependencies.authenticated(current.host)) return result;
1974
+ const signedIn = this.dependencies.credentialKey(current.host);
1975
+ if (!signedIn) return result;
1976
+ if (result.login_mode === "website_login" && result.authorization_status === "claimed") {
1977
+ completedLogin = { login_mode: result.login_mode, authorization_status: result.authorization_status };
1978
+ }
1979
+ if (current.credential_key && current.credential_key !== signedIn) {
1980
+ clearAccountScope(current);
1981
+ loginChangedCredential = true;
1982
+ }
1983
+ current.credential_key = signedIn;
1984
+ this.store.save(current);
1985
+ }
1986
+ const compatibility = action === "run" ? await network((signal) => this.dependencies.compatibility(current.host, signal)) : void 0;
1987
+ const context = await network((signal) => this.dependencies.capability(current.host, DEMO_CONTEXT, {}, signal));
1988
+ const projectId = context?.business_project?.project_id;
1989
+ const availableProject = Number.isSafeInteger(projectId) && projectId > 0;
1990
+ if (action === "run" && !loginChangedCredential && input.confirm_business_project_id !== void 0) {
1991
+ if (!availableProject || input.confirm_business_project_id !== projectId) throw new Error("Confirm the eligible business project shown by AE.");
1992
+ current.confirmed_business_project_id = projectId;
1993
+ }
1994
+ const boundProject = availableProject && (!context.requires_confirmation || current.confirmed_business_project_id === projectId);
1995
+ if (boundProject) current.project_id = projectId;
1996
+ else delete current.project_id;
1997
+ if (action === "run") {
1998
+ if (!loginChangedCredential) {
1999
+ if (input.choice === "demo" || input.sample) current.choice = "demo";
2000
+ else if (input.choice === "business") current.choice = "business";
2001
+ else if (webConversation && current.choice === "business") delete current.choice;
2002
+ if (current.choice === "demo") current.sample_id = input.sample ?? current.sample_id ?? context.recommended_sample;
2003
+ }
2004
+ if (current.choice !== "demo" || current.ready_demo?.sample_id !== current.sample_id || current.ready_demo?.project_id === projectId) delete current.ready_demo;
2005
+ this.store.save(current);
2006
+ }
2007
+ const account = { ...completedLogin, business_project: availableProject ? context.business_project : null, compatibility };
2008
+ if (current.choice === "demo" && current.sample_id) {
2009
+ const prepareDemo = () => network((signal) => this.dependencies.capability(
2010
+ current.host,
2011
+ action === "run" ? DEMO_ENSURE : DEMO_STATUS,
2012
+ { sample_id: current.sample_id },
2013
+ signal
2014
+ ));
2015
+ let demo = await prepareDemo();
2016
+ if (action === "run" && demo?.status === "initialized") {
2017
+ try {
2018
+ demo = await prepareDemo();
2019
+ if (demo?.status === "uploaded") demo = await prepareDemo();
2020
+ } catch (error) {
2021
+ if (!controller.signal.aborted && error?.name !== "AbortError" && error?.name !== "TimeoutError") throw error;
2022
+ }
2023
+ }
2024
+ if (action === "run") {
2025
+ const scope = readyDemoScope(demo, current);
2026
+ if (scope) current.ready_demo = scope;
2027
+ else delete current.ready_demo;
2028
+ this.store.save(current);
2029
+ }
2030
+ return summary({
2031
+ ...account,
2032
+ demo,
2033
+ samples: context.samples,
2034
+ demo_project_id: demo?.project_id ?? null,
2035
+ evidence: onboardingEvidenceLinks(demo?.evidence, demo?.project_id, webConversation ? void 0 : current.host),
2036
+ phase: demo?.status === "ready" ? "ready" : demo?.status === "action_required" ? "action_required" : "pending",
2037
+ next_action: demo?.status === "ready" ? "offer_growth_questions" : demo?.status === "action_required" ? "inspect_demo_preparation" : "poll_demo",
2038
+ poll_after_ms: demo?.status === "ready" || demo?.status === "action_required" ? 0 : 2e3
2039
+ });
2040
+ }
2041
+ if (!webConversation && current.choice === "business") {
2042
+ if (!boundProject) return summary({
2043
+ ...account,
2044
+ phase: "waiting_user",
2045
+ next_action: availableProject ? "confirm_business_project" : "resolve_business_project",
2046
+ poll_after_ms: 0
2047
+ });
2048
+ const completed = action === "run" && input.sdk_complete;
2049
+ return summary({
2050
+ ...account,
2051
+ phase: completed ? "completed" : "waiting_user",
2052
+ next_action: completed ? "show_realtime_data" : "identify_workspace_projects",
2053
+ poll_after_ms: 0,
2054
+ realtime_data_url: `${current.host}/#/data/realtime?setupProjectId=${projectId}`,
2055
+ ...action === "run" && !completed ? { workspace_projects: identifyWorkspaceProjects() } : {}
2056
+ });
2057
+ }
2058
+ const choices = [{ value: "demo", label: "Start the demo" }];
2059
+ if (!webConversation) choices.push({ value: "business", label: "Connect my business data" });
2060
+ return summary({
2061
+ ...account,
2062
+ phase: "waiting_user",
2063
+ next_action: "choose_experience",
2064
+ poll_after_ms: 0,
2065
+ choices
2066
+ });
2067
+ };
2068
+ return action === "run" ? await this.store.locked(`session:${current.id}`, execute) : await execute();
2069
+ } catch (error) {
2070
+ if (controller.signal.aborted || error?.name === "AbortError" || error?.name === "TimeoutError") {
2071
+ return summary({ phase: "pending", next_action: "retry_onboarding", poll_after_ms: 1e3 });
2072
+ }
2073
+ if (action === "run" && (error?.httpStatus === 401 || error?.name === "SecureStoreAuthError")) {
2074
+ if (this.dependencies.webConversation) {
2075
+ return summary({ phase: "action_required", next_action: "retry_web_onboarding", code: "PLATFORM_CREDENTIAL_UNAVAILABLE", poll_after_ms: 0 });
2076
+ }
2077
+ current.requires_auth = true;
2078
+ this.store.save(current);
2079
+ return summary({ phase: "waiting_user", next_action: "reauthorize_cli", poll_after_ms: 0 });
2080
+ }
2081
+ throw error;
2082
+ } finally {
2083
+ clearTimeout(timer);
2084
+ }
2085
+ }
2086
+ async authentication(action, session, summary, network, open) {
2087
+ if (session.device) {
2088
+ const route = resolveDeviceSessionRoute(session.host, session.device.device_code);
2089
+ if (session.device.host !== session.host || session.device.base_url !== route.baseUrl) {
2090
+ if (action === "status") return summary({ phase: "action_required", next_action: "run_onboarding", login_recovery_url: session.bootstrap?.login_url, poll_after_ms: 0 });
2091
+ delete session.device;
2092
+ this.store.save(session);
2093
+ }
2094
+ }
2095
+ if (session.device) {
2096
+ if (action === "status" && Date.parse(session.device.expires_at) <= this.dependencies.now()) return summary({ phase: "waiting_user", next_action: "reauthorize_cli", login_recovery_url: session.bootstrap?.login_url, poll_after_ms: 0 });
2097
+ if (action === "status") return summary({ phase: "waiting_user", next_action: "approve_device", verification_url: session.device.verification_url, login_recovery_url: session.bootstrap?.login_url, poll_after_ms: session.device.interval_ms });
2098
+ if (Date.parse(session.device.expires_at) <= this.dependencies.now()) {
2099
+ delete session.device;
2100
+ this.store.save(session);
2101
+ } else {
2102
+ if (session.device.host !== session.host) throw new Error("The device session belongs to another host.");
2103
+ if (this.dependencies.now() < session.device.next_poll_at) return summary({ phase: "waiting_user", next_action: "approve_device", verification_url: session.device.verification_url, login_recovery_url: session.bootstrap?.login_url, poll_after_ms: session.device.next_poll_at - this.dependencies.now() });
2104
+ const result = await network((signal) => this.dependencies.poll(session.device.base_url, session.device.device_code, signal));
2105
+ if (result.status === "approved") {
2106
+ await network((signal) => this.dependencies.persist(session.host, result.tokens, signal));
2107
+ delete session.device;
2108
+ delete session.bootstrap;
2109
+ delete session.requires_auth;
2110
+ delete session.project_id;
2111
+ this.store.save(session);
2112
+ return summary({ phase: "pending", next_action: "run_onboarding", poll_after_ms: 0 });
2113
+ }
2114
+ if (result.status === "expired") {
2115
+ delete session.device;
2116
+ this.store.save(session);
2117
+ return summary({ phase: "waiting_user", next_action: "reauthorize_cli", login_recovery_url: session.bootstrap?.login_url, poll_after_ms: 0 });
2118
+ }
2119
+ if (result.status === "denied" || result.status === "unsupported") return summary({ phase: "action_required", next_action: "review_cli_authorization", code: result.status === "denied" ? result.code : "DEVICE_AUTH_UNSUPPORTED", poll_after_ms: 0 });
2120
+ if (result.status === "slow_down") session.device.interval_ms += 5e3;
2121
+ session.device.next_poll_at = this.dependencies.now() + session.device.interval_ms;
2122
+ this.store.save(session);
2123
+ return summary({ phase: "waiting_user", next_action: "approve_device", verification_url: session.device.verification_url, login_recovery_url: session.bootstrap?.login_url, poll_after_ms: session.device.interval_ms });
2124
+ }
2125
+ }
2126
+ if (action === "status") {
2127
+ if (session.bootstrap && Date.parse(session.bootstrap.expires_at) > this.dependencies.now()) {
2128
+ const ready2 = await network((signal) => this.dependencies.readBootstrap(session.bootstrap.origin, session.bootstrap.intent_id, session.bootstrap.poll_token, signal, session.source, session.region));
2129
+ const host2 = readyAccountHost(ready2, session.host);
2130
+ return summary({
2131
+ phase: "waiting_user",
2132
+ bootstrap_status: ready2.status,
2133
+ next_action: host2 ? "run_onboarding" : "complete_website_login",
2134
+ login_url: ready2.ready_url ?? session.bootstrap.login_url,
2135
+ login_mode: ready2.login_mode,
2136
+ authorization_status: ready2.authorization_status,
2137
+ poll_after_ms: ready2.poll_after_ms
2138
+ });
2139
+ }
2140
+ return summary({ phase: "waiting_user", next_action: "run_onboarding", poll_after_ms: 0 });
2141
+ }
2142
+ if (!session.region) return summary({ phase: "action_required", next_action: "choose_market", markets: WEBSITE_MARKETS, poll_after_ms: 0 });
2143
+ const language = session.language_source === "explicit" ? registrationLanguage(session.language) : void 0;
2144
+ if (!session.bootstrap || Date.parse(session.bootstrap.expires_at) <= this.dependencies.now()) {
2145
+ const thread = session.source === "codex" && UUID_PATTERN.test(process.env.CODEX_THREAD_ID ?? "") ? process.env.CODEX_THREAD_ID : void 0;
2146
+ const created = await network((signal) => this.dependencies.createBootstrap(session.region, session.source ?? "other", session.host, signal, thread, session.website_env, language));
2147
+ session.bootstrap = {
2148
+ origin: bootstrapOrigin(session.region, session.website_env),
2149
+ intent_id: created.intent_id,
2150
+ poll_token: created.poll_token,
2151
+ login_url: created.login_url,
2152
+ expires_at: created.expires_at,
2153
+ ...created.login_mode ? { login_mode: created.login_mode } : {}
2154
+ };
2155
+ delete session.website_device;
2156
+ this.store.save(session);
2157
+ open(created.login_url, "website_login");
2158
+ return summary({
2159
+ phase: "waiting_user",
2160
+ next_action: "complete_website_login",
2161
+ login_url: created.login_url,
2162
+ login_mode: created.login_mode,
2163
+ poll_after_ms: created.poll_after_ms
2164
+ });
2165
+ }
2166
+ const ready = await network((signal) => this.dependencies.readBootstrap(session.bootstrap.origin, session.bootstrap.intent_id, session.bootstrap.poll_token, signal, session.source, session.region));
2167
+ if (ready.status === "expired") {
2168
+ delete session.bootstrap;
2169
+ delete session.website_device;
2170
+ this.store.save(session);
2171
+ return summary({ phase: "waiting_user", next_action: "restart_website_login", poll_after_ms: 0 });
2172
+ }
2173
+ if (ready.authorization_status) {
2174
+ session.bootstrap.authorization_status = ready.authorization_status;
2175
+ this.store.save(session);
2176
+ }
2177
+ const host = readyAccountHost(ready, session.host);
2178
+ if (!host) return summary({
2179
+ phase: "waiting_user",
2180
+ next_action: "complete_website_login",
2181
+ login_url: ready.ready_url ?? session.bootstrap.login_url,
2182
+ login_mode: ready.login_mode ?? session.bootstrap.login_mode,
2183
+ authorization_status: ready.authorization_status,
2184
+ poll_after_ms: ready.poll_after_ms
2185
+ });
2186
+ session.host = host;
2187
+ const mode = ready.login_mode ?? (session.bootstrap.login_mode === "website_login" ? void 0 : "device_confirmation");
2188
+ if (!mode) return summary({
2189
+ phase: "waiting_user",
2190
+ next_action: "complete_website_login",
2191
+ login_mode: "website_login",
2192
+ login_url: ready.ready_url ?? session.bootstrap.login_url,
2193
+ poll_after_ms: ready.poll_after_ms
2194
+ });
2195
+ if (session.bootstrap.effective_login_mode && session.bootstrap.effective_login_mode !== mode) throw new Error("The website login mode changed. Start a separate connection.");
2196
+ session.bootstrap.effective_login_mode = mode;
2197
+ if (mode === "website_login") {
2198
+ if (session.bootstrap.login_mode !== "website_login") throw new Error("This continuation did not negotiate website login.");
2199
+ session.requires_auth = true;
2200
+ this.store.save(session);
2201
+ return this.websiteAuthentication(session, ready, summary, network);
2202
+ }
2203
+ const device = await network((signal) => this.dependencies.authorize(session.host, signal));
2204
+ const auth = device.authorization;
2205
+ session.device = {
2206
+ host: session.host,
2207
+ base_url: device.baseUrl,
2208
+ device_code: auth.device_code,
2209
+ verification_url: agentVerificationUrl(device.baseUrl, auth, language),
2210
+ expires_at: new Date(this.dependencies.now() + (auth.expires_in ?? 300) * 1e3).toISOString(),
2211
+ interval_ms: Math.max(1e3, (auth.interval ?? 5) * 1e3),
2212
+ next_poll_at: this.dependencies.now() + Math.max(1e3, (auth.interval ?? 5) * 1e3)
2213
+ };
2214
+ this.store.save(session);
2215
+ open(session.device.verification_url, "device_authorization");
2216
+ return summary({ phase: "waiting_user", next_action: "approve_device", verification_url: session.device.verification_url, login_recovery_url: session.bootstrap?.login_url, poll_after_ms: session.device.interval_ms });
2217
+ }
2218
+ async websiteAuthentication(session, ready, summary, network) {
2219
+ const bootstrap = session.bootstrap;
2220
+ const issuer = trustedProductHost(session.host);
2221
+ const waiting = (status, delay = ready.poll_after_ms) => summary({
2222
+ phase: "waiting_user",
2223
+ next_action: "complete_website_login",
2224
+ login_mode: "website_login",
2225
+ authorization_status: status,
2226
+ login_url: ready.ready_url ?? bootstrap.login_url,
2227
+ poll_after_ms: delay
2228
+ });
2229
+ const restart = (code) => {
2230
+ delete session.bootstrap;
2231
+ delete session.website_device;
2232
+ this.store.save(session);
2233
+ return summary({ phase: "action_required", next_action: "restart_website_login", login_mode: "website_login", code, poll_after_ms: 0 });
2234
+ };
2235
+ if (session.website_device && Date.parse(session.website_device.expires_at) <= this.dependencies.now()) {
2236
+ return restart("WEBSITE_AUTHORIZATION_EXPIRED");
2237
+ }
2238
+ if (session.website_device && session.website_device.next_poll_at > this.dependencies.now()) return waiting(ready.authorization_status ?? "pending", session.website_device.next_poll_at - this.dependencies.now());
2239
+ const grant = await network((signal) => this.dependencies.claimBootstrapDevice(bootstrap.origin, bootstrap.intent_id, bootstrap.poll_token, signal));
2240
+ if (grant.login_mode !== "website_login") throw new Error("The website did not confirm this login mode.");
2241
+ if (grant.authorization_status === "expired") return restart("WEBSITE_AUTHORIZATION_EXPIRED");
2242
+ if (grant.authorization_status !== "approved" && grant.authorization_status !== "claimed") return waiting(grant.authorization_status, grant.poll_after_ms ?? ready.poll_after_ms);
2243
+ 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 = crypto3.createHash("sha256").update(grant.device_code).digest("hex");
2245
+ const previous = session.website_device;
2246
+ 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
+ throw new Error("The website device connection changed. Start a separate connection.");
2248
+ }
2249
+ session.website_device = {
2250
+ fingerprint,
2251
+ issuer,
2252
+ expires_at: grant.expires_at,
2253
+ expected_login_name: grant.expected_login_name,
2254
+ expected_company_id: String(grant.expected_company_id),
2255
+ next_poll_at: this.dependencies.now(),
2256
+ interval_ms: previous?.interval_ms ?? Math.max(1e3, (grant.interval ?? 5) * 1e3)
2257
+ };
2258
+ this.store.save(session);
2259
+ const result = await network((signal) => this.dependencies.poll(issuer, grant.device_code, signal));
2260
+ if (result.status === "approved") {
2261
+ await network((signal) => this.dependencies.verifyWebsiteLoginIdentity(
2262
+ session.host,
2263
+ result.tokens.access_token,
2264
+ { login_name: grant.expected_login_name, company_id: String(grant.expected_company_id) },
2265
+ signal
2266
+ ));
2267
+ await network((signal) => this.dependencies.persist(session.host, result.tokens, signal));
2268
+ delete session.website_device;
2269
+ delete session.bootstrap;
2270
+ delete session.requires_auth;
2271
+ delete session.project_id;
2272
+ this.store.save(session);
2273
+ return summary({ phase: "pending", next_action: "run_onboarding", login_mode: "website_login", authorization_status: "claimed", poll_after_ms: 0 });
2274
+ }
2275
+ if (result.status === "denied" || result.status === "unsupported" || result.status === "expired") return restart(
2276
+ result.status === "denied" ? "WEBSITE_AUTHORIZATION_DENIED" : result.status === "expired" ? "WEBSITE_AUTHORIZATION_EXPIRED" : "DEVICE_AUTH_UNSUPPORTED"
2277
+ );
2278
+ if (result.status === "slow_down") session.website_device.interval_ms += 5e3;
2279
+ session.website_device.next_poll_at = this.dependencies.now() + session.website_device.interval_ms;
2280
+ this.store.save(session);
2281
+ return waiting("approved", session.website_device.interval_ms);
2282
+ }
2283
+ };
2284
+
2285
+ // src/core/onboarding/web-runtime.ts
2286
+ var GUIDE_AGENT_ID = "system-agent-onboarding-guide";
2287
+ var SESSION_HOST = "https://onboarding-sandbox.invalid";
2288
+ function webSessionDirectory(env, cwd) {
2289
+ const conversationId = env.TE_AGENT_CONVERSATION_ID;
2290
+ if (!conversationId || !/^[\w-]+$/.test(conversationId) || path8.basename(cwd) !== conversationId) {
2291
+ throw new Error("Web onboarding must run in the current AE conversation directory.");
2292
+ }
2293
+ return path8.join(cwd, ".ae-onboarding", "cli");
2294
+ }
2295
+ async function readTaskActor(host, token, conversationId, signal) {
2296
+ const legacy = token.startsWith("cli_task_");
2297
+ const url = new URL("/v1/ta/cli/config", host);
2298
+ const response = legacy ? await fetch(url, {
2299
+ headers: { Accept: "application/json", "cli-token": token },
2300
+ ...externalCliTokenRequestOptions(url.toString()),
2301
+ signal
2302
+ }) : await fetchSigned({
2303
+ method: "GET",
2304
+ path: "/api/sandbox/onboarding/context",
2305
+ hostOverride: host,
2306
+ authMode: "cli-token",
2307
+ timeoutMs: NETWORK_BUDGET_MS
2308
+ });
2309
+ if (!response.ok) return void 0;
2310
+ const payload = await response.json();
2311
+ if (legacy && (payload.return_code !== 0 || payload.data?.task_cli_compat_enabled !== true)) return void 0;
2312
+ const actor = legacy ? payload.data?.plg_onboarding_actor : payload.actor;
2313
+ if (typeof actor?.account_id === "string" && actor.account_id && typeof actor.company_id === "string" && actor.company_id && actor.conversation_id === conversationId) {
2314
+ return { openId: actor.account_id, issuer: actor.company_id };
2315
+ }
2316
+ }
2317
+ async function invokeOnboarding(action, input) {
2318
+ if (process.env.TE_AGENT_CURRENT_AGENT_ID !== GUIDE_AGENT_ID || !isAeSandboxRuntime() && !process.env.TE_AGENT_CLI_CONFIG_DIR && !process.env.AE_CLI_TOKEN?.startsWith("cli_task_")) {
2319
+ return new OnboardingRuntime().invoke(action, input);
2320
+ }
2321
+ if (input.host || input.region || input.website_env) throw new Error("Web onboarding uses the current AE account and environment.");
2322
+ if (input.choice === "business" || input.confirm_business_project_id !== void 0 || input.sdk_complete) {
2323
+ throw new Error("Business SDK setup requires a local agent. Web onboarding supports the Demo.");
2324
+ }
2325
+ const directory = webSessionDirectory(process.env, process.cwd());
2326
+ const external = readExternalCliToken();
2327
+ const host = external?.url ?? getActiveHost();
2328
+ if (!host || !external && !process.env.TE_AGENT_CLI_CONFIG_DIR) {
2329
+ throw new Error("AE did not provide credentials for the current onboarding conversation.");
2330
+ }
2331
+ const signal = AbortSignal.timeout(NETWORK_BUDGET_MS);
2332
+ const token = external?.token ?? await getCliToken(host, signal);
2333
+ if (external && !token.startsWith("cli_task_") && !external.taskContext) {
2334
+ throw new Error("Web onboarding requires the current AE task context.");
2335
+ }
2336
+ const actor = token.startsWith("cli_task_") || external?.taskContext ? await readTaskActor(host, token, process.env.TE_AGENT_CONVERSATION_ID, signal) : { openId: (await validateCliTokenOnServer(host, token, signal)).account?.openId, issuer: host };
2337
+ if (!actor?.openId || external?.taskContext && actor.issuer !== external.taskContext.companyId) {
2338
+ throw new Error("AE could not verify the current onboarding account.");
2339
+ }
2340
+ const key = createHash2("sha256").update(JSON.stringify([actor.issuer, actor.openId])).digest("hex");
2341
+ const store = new OnboardingStore(directory);
2342
+ const session = store.session(input.session_id, SESSION_HOST);
2343
+ if (session?.credential_key && session.credential_key !== key) {
2344
+ throw new Error("The current AE account does not match the onboarding session.");
2345
+ }
2346
+ const runtime = new OnboardingRuntime(store, {
2347
+ webConversation: true,
2348
+ activeHost: () => SESSION_HOST,
2349
+ authenticated: (scope) => scope === SESSION_HOST,
2350
+ credentialKey: (scope) => scope === SESSION_HOST ? key : void 0,
2351
+ machineLoginAllowed: () => false,
2352
+ compatibility: async () => void 0,
2353
+ approverOpenId: async () => actor.openId,
2354
+ open: () => false,
2355
+ capability(scope, id, params, requestSignal) {
2356
+ if (scope !== SESSION_HOST) throw new Error("The continuation does not belong to this AE conversation.");
2357
+ return executeCapability(host, id.startsWith("experiment.") ? "engage" : "analysis", id, params, { signal: requestSignal });
2358
+ }
2359
+ });
2360
+ const output = await runtime.invoke(action, input);
2361
+ if (output.host === SESSION_HOST) output.host = null;
2362
+ return output;
2363
+ }
2364
+ export {
2365
+ invokeOnboarding,
2366
+ webSessionDirectory
2367
+ };