@thinkingai/ae-cli 6.1.40 → 6.1.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/cli-installation-guide.md +17 -10
- package/dist/{ai-monitor-DST4NDOK.js → ai-monitor-OOOD4QDK.js} +5 -7
- package/dist/ai-monitor.js +6 -8
- package/dist/{auth-BD3NIY3T.js → auth-6BUUY5XS.js} +4 -4
- package/dist/{capability-3NJOQHZQ.js → capability-XXFCANX7.js} +8 -10
- package/dist/{chunk-FRJUB66C.js → chunk-5YQSCMGS.js} +2 -2
- package/dist/{chunk-KBJHBVO7.js → chunk-6W56UQPO.js} +1 -1
- package/dist/{chunk-RW6Z2NN3.js → chunk-BEVWMPCZ.js} +6 -6
- package/dist/{chunk-WRYXVIJP.js → chunk-DZRQGI2Z.js} +1 -1
- package/dist/{chunk-VXKKTUU2.js → chunk-EHH3ZF7D.js} +2 -2
- package/dist/{chunk-IY5G42YY.js → chunk-FPPCXG6K.js} +2 -2
- package/dist/{chunk-SQEK6S4X.js → chunk-I7H72CMN.js} +1182 -178
- package/dist/{chunk-24DCOJBJ.js → chunk-KDRE7SWM.js} +2 -2
- package/dist/{chunk-STHIGWWC.js → chunk-WG27BD67.js} +75 -4
- package/dist/{compat-check-7VBBE7KO.js → compat-check-AO3BFA3N.js} +2 -2
- package/dist/{config-LFRZBPH5.js → config-N5V4VNER.js} +4 -4
- package/dist/index.js +28 -31
- package/dist/{metadata-AR64J76Z.js → metadata-OUJPEMLD.js} +5 -7
- package/dist/{personal-semantic-preference-BCOSI4DO.js → personal-semantic-preference-WEAIZQXM.js} +4 -6
- package/dist/{project-semantic-DJLXAXLD.js → project-semantic-6VXUYU4A.js} +4 -6
- package/dist/{sync-4TUIQ2PZ.js → sync-BAV3UY46.js} +3 -3
- package/dist/{te-agent-EMDWA3M6.js → te-agent-QWZC36YS.js} +1 -3
- package/dist/{te-analysis-NJHSEKGW.js → te-analysis-43RCOPUA.js} +29 -14
- package/dist/{te-community-JSUSZEYH.js → te-community-ECNTP35Z.js} +5 -8
- package/dist/{te-dataops-I264BUTI.js → te-dataops-ISEKYRLZ.js} +3 -4
- package/dist/{te-engage-XNMQYO5N.js → te-engage-LBKIZXZO.js} +4 -6
- package/dist/{te-experiment-5SCHMYVO.js → te-experiment-5TPQKN6B.js} +4 -6
- package/dist/{te-kb-QQ53TNRZ.js → te-kb-SHL56BJ5.js} +4 -6
- package/dist/{te-team-V6BBI52R.js → te-team-EZ3TZTLV.js} +4 -6
- package/dist/{things-THHGDSEC.js → things-UBMLTY3S.js} +1 -3
- package/dist/{update-53ZUXWV5.js → update-WE7VNRKZ.js} +3 -3
- package/dist/{web-runtime-HIXOSNJ6.js → web-runtime-H53QKJS2.js} +338 -663
- package/package.json +1 -1
- package/skills/ae-onboarding/SKILL.md +44 -23
- package/skills/ae-onboarding/references/about-ae.md +68 -0
- package/skills/ae-onboarding/references/business-data.md +46 -0
- package/skills/ae-onboarding/references/business-sdk.md +1 -1
- package/skills/ae-onboarding/references/demo-journey.md +58 -0
- package/skills/ae-onboarding/references/demo-operations.md +45 -21
- package/skills/ae-onboarding/references/onboarding_experiment_launch.md +5 -4
- package/skills/ae-onboarding/references/onboarding_experiment_plan.md +9 -2
- package/skills/ae-onboarding/references/onboarding_growth.md +37 -5
- package/skills/ae-onboarding/references/onboarding_run.md +16 -2
- package/skills/ae-onboarding/references/onboarding_status.md +2 -0
- package/skills/ae-onboarding/references/presentation.md +79 -0
- package/skills/ae-onboarding/scripts/experiment-requests.mjs +9 -4
- package/skills/ae-onboarding/scripts/generate.mjs +5 -5
- package/skills/ae-onboarding/scripts/resolve-experiment-preset.mjs +5 -2
- package/skills/ae-onboarding/scripts/web-journey.mjs +39 -27
- package/dist/chunk-6E6HCTP2.js +0 -60
- package/dist/chunk-PUSFEC6B.js +0 -29
- package/dist/chunk-QOJXLXDJ.js +0 -55
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
|
+
CapabilityGatewayError,
|
|
3
4
|
getLocalCliPackageInfo
|
|
4
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-WG27BD67.js";
|
|
5
6
|
import {
|
|
6
7
|
internalCallSourceHeaders,
|
|
7
8
|
peekCliToken
|
|
@@ -10,7 +11,8 @@ import {
|
|
|
10
11
|
getActiveHost,
|
|
11
12
|
getConfigDir,
|
|
12
13
|
isAeSandboxRuntime,
|
|
13
|
-
readSandboxCliTokenEntry
|
|
14
|
+
readSandboxCliTokenEntry,
|
|
15
|
+
safeJsonParse
|
|
14
16
|
} from "./chunk-IGU3R2JD.js";
|
|
15
17
|
import {
|
|
16
18
|
externalCliTokenRequestOptions,
|
|
@@ -23,7 +25,7 @@ import {
|
|
|
23
25
|
|
|
24
26
|
// src/core/compat-check.ts
|
|
25
27
|
import fs10 from "fs";
|
|
26
|
-
import
|
|
28
|
+
import path11 from "path";
|
|
27
29
|
import { createHash as createHash3 } from "crypto";
|
|
28
30
|
import { Agent } from "undici";
|
|
29
31
|
|
|
@@ -314,24 +316,1050 @@ function formatCompatNotice(verdict) {
|
|
|
314
316
|
|
|
315
317
|
// src/core/version-sync.ts
|
|
316
318
|
import fs8 from "fs";
|
|
317
|
-
import
|
|
319
|
+
import path9 from "path";
|
|
320
|
+
|
|
321
|
+
// src/core/onboarding/contracts.ts
|
|
322
|
+
var DEMO_CONTEXT = "project.plg_demo.context";
|
|
323
|
+
var DEMO_ENSURE = "project.plg_demo.ensure";
|
|
324
|
+
var DEMO_STATUS = "project.plg_demo.status";
|
|
325
|
+
var RUN_BUDGET_MS = 45e3;
|
|
326
|
+
var NETWORK_BUDGET_MS = 35e3;
|
|
327
|
+
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
328
|
+
var DEMO_SAMPLE_IDS = ["star-island", "season-pass"];
|
|
329
|
+
var CHECKOUT_RECOVERY = "checkout-recovery";
|
|
330
|
+
var OVERSEAS_TEST_PRODUCT_HOSTNAME = "plg-test-overseas-web.thinkingai.io";
|
|
331
|
+
function onboardingDemoCurrency(host, region) {
|
|
332
|
+
const hostname = host ? new URL(host).hostname : void 0;
|
|
333
|
+
if (hostname === "ae-web-global.thinkingai.io" || hostname === OVERSEAS_TEST_PRODUCT_HOSTNAME) return "USD";
|
|
334
|
+
if (hostname?.endsWith(".thinkingai.cn") || hostname?.endsWith(".thinkingdata.cn")) return "CNY";
|
|
335
|
+
return region === "us" ? "USD" : "CNY";
|
|
336
|
+
}
|
|
337
|
+
function onboardingGrowthScenario(value) {
|
|
338
|
+
if (value === void 0 || value === "item-coupon") return "item-coupon";
|
|
339
|
+
if (value === CHECKOUT_RECOVERY) return CHECKOUT_RECOVERY;
|
|
340
|
+
throw new Error("Use --scenario item-coupon or checkout-recovery.");
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// src/core/onboarding/experiment-report-wait.ts
|
|
344
|
+
function replayReportDates(receipt) {
|
|
345
|
+
const zone = /^([+-])(\d{2}):(\d{2})$/.exec(receipt.timezone);
|
|
346
|
+
if (!zone || Number(zone[2]) > 14 || Number(zone[3]) > 59 || Number(zone[2]) === 14 && Number(zone[3]) !== 0) throw new Error("The replay reporting timezone is invalid.");
|
|
347
|
+
const offset = (Number(zone[2]) * 60 + Number(zone[3])) * 6e4 * (zone[1] === "-" ? -1 : 1);
|
|
348
|
+
const start = Date.parse(receipt.start);
|
|
349
|
+
const end = Date.parse(receipt.end);
|
|
350
|
+
if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) throw new Error("The replay interval is invalid.");
|
|
351
|
+
return {
|
|
352
|
+
start_time: new Date(start + offset).toISOString().slice(0, 10),
|
|
353
|
+
end_time: new Date(end + offset).toISOString().slice(0, 10)
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
function isReportPending(error, projectId) {
|
|
357
|
+
if (!(error instanceof CapabilityGatewayError) || error.type === "validation" || error.httpStatus === 401 || error.httpStatus === 403) return false;
|
|
358
|
+
const view = `hive.hermes.v_atlas_experiment_exposure_${projectId}`.replaceAll(".", "\\.");
|
|
359
|
+
return new RegExp("\\bTable\\s+['\"`]?" + view + "['\"`]?\\s+does not exist\\b", "i").test(error.message) || /^(atlas\.service\.error\.report\.data_unavailable|Report data is temporarily unavailable\.|报告数据暂不可用|レポートデータを一時的に利用できません|리포트 데이터를 일시적으로 사용할 수 없습니다)/.test(error.message);
|
|
360
|
+
}
|
|
361
|
+
async function waitForExperimentSampleSize(query, input, budgetMs = 25e3, delayMs = 5e3) {
|
|
362
|
+
const deadline = Date.now() + budgetMs;
|
|
363
|
+
let attempts = 0;
|
|
364
|
+
do {
|
|
365
|
+
attempts++;
|
|
366
|
+
try {
|
|
367
|
+
const response = await query(
|
|
368
|
+
{ ...input, force_refresh: true },
|
|
369
|
+
AbortSignal.timeout(Math.max(1, Math.min(NETWORK_BUDGET_MS, deadline - Date.now())))
|
|
370
|
+
);
|
|
371
|
+
if (!response || typeof response.report !== "object" || response.report === null) {
|
|
372
|
+
throw new Error("The sample-size query returned no report.");
|
|
373
|
+
}
|
|
374
|
+
if (response.report.has_data !== false) {
|
|
375
|
+
return { phase: "complete", next_action: "verify_experiment_results", report_dates: {
|
|
376
|
+
start_time: input.start_time,
|
|
377
|
+
end_time: input.end_time
|
|
378
|
+
}, sample_size_report: response.report, report_query_attempts: attempts };
|
|
379
|
+
}
|
|
380
|
+
} catch (error) {
|
|
381
|
+
if (!isReportPending(error, input.project_id) && !(error instanceof DOMException && ["TimeoutError", "AbortError"].includes(error.name))) throw error;
|
|
382
|
+
}
|
|
383
|
+
const remaining = deadline - Date.now();
|
|
384
|
+
if (remaining <= 0) break;
|
|
385
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(delayMs, remaining)));
|
|
386
|
+
} while (Date.now() < deadline);
|
|
387
|
+
return {
|
|
388
|
+
phase: "pending",
|
|
389
|
+
next_action: "wait_experiment_report",
|
|
390
|
+
poll_after_ms: delayMs,
|
|
391
|
+
report_dates: { start_time: input.start_time, end_time: input.end_time },
|
|
392
|
+
report_query_attempts: attempts
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// src/core/onboarding/growth.ts
|
|
397
|
+
import crypto from "crypto";
|
|
398
|
+
import path2 from "path";
|
|
399
|
+
|
|
400
|
+
// src/core/website-entry.ts
|
|
401
|
+
var LOGIN_PATHS = { jp: "/jp/experience-login/", kr: "/kr/experience-login/", us: "/en/experience-login/", cn: "/experience-login/" };
|
|
402
|
+
var WEBSITE_MARKETS = Object.keys(LOGIN_PATHS);
|
|
403
|
+
var OVERSEAS_TEST_MARKETS = WEBSITE_MARKETS.filter((market) => market !== "cn");
|
|
404
|
+
var OVERSEAS_TEST_WEBSITE_ORIGIN = "https://test.thinkingai.io";
|
|
405
|
+
var PRODUCTION_ISSUER = "https://thinkingai.io";
|
|
406
|
+
var PRODUCTION_BROWSER_ORIGIN = "https://www.thinkingai.io";
|
|
407
|
+
var CHINA_PRODUCTION_ORIGIN = "https://www.thinkingai.cn";
|
|
408
|
+
var UNSUPPORTED_MARKET = "Website onboarding is available in China, Japan, South Korea, and the United States. Use --region cn, jp, kr, or us.";
|
|
409
|
+
function isWebsiteMarket(market) {
|
|
410
|
+
return Object.hasOwn(LOGIN_PATHS, market);
|
|
411
|
+
}
|
|
412
|
+
function websiteEnvironment(value, env = process.env) {
|
|
413
|
+
const selected = value ?? env.AE_CLI_WEBSITE_ENV ?? "production";
|
|
414
|
+
if (selected !== "production" && selected !== "test") throw new Error("Choose website environment test or production.");
|
|
415
|
+
return selected;
|
|
416
|
+
}
|
|
417
|
+
function websiteOrigin(market, environment) {
|
|
418
|
+
websiteEnvironment(environment, {});
|
|
419
|
+
if (!isWebsiteMarket(market)) throw new Error(UNSUPPORTED_MARKET);
|
|
420
|
+
if (environment === "test") {
|
|
421
|
+
if (market === "cn") throw new Error("Overseas test website onboarding supports us, jp, and kr.");
|
|
422
|
+
return OVERSEAS_TEST_WEBSITE_ORIGIN;
|
|
423
|
+
}
|
|
424
|
+
return market === "cn" ? CHINA_PRODUCTION_ORIGIN : PRODUCTION_ISSUER;
|
|
425
|
+
}
|
|
426
|
+
function isProductionWebsiteOrigin(origin) {
|
|
427
|
+
return origin === PRODUCTION_ISSUER || origin === PRODUCTION_BROWSER_ORIGIN || origin === CHINA_PRODUCTION_ORIGIN;
|
|
428
|
+
}
|
|
429
|
+
function environmentForWebsiteOrigin(origin) {
|
|
430
|
+
if (origin === OVERSEAS_TEST_WEBSITE_ORIGIN) return "test";
|
|
431
|
+
if (isProductionWebsiteOrigin(origin)) return "production";
|
|
432
|
+
throw new Error("Untrusted onboarding website.");
|
|
433
|
+
}
|
|
434
|
+
function cliEntrySource(source, env = process.env) {
|
|
435
|
+
const selected = source ?? (UUID_PATTERN.test(env.CODEX_THREAD_ID ?? "") ? "codex" : "other");
|
|
436
|
+
if (!["codex", "cursor", "claude-code", "other"].includes(selected)) throw new Error("Unsupported local AI tool source.");
|
|
437
|
+
return selected;
|
|
438
|
+
}
|
|
439
|
+
function cliToolReference(source, env = process.env) {
|
|
440
|
+
return source === "codex" && UUID_PATTERN.test(env.CODEX_THREAD_ID ?? "") ? env.CODEX_THREAD_ID : void 0;
|
|
441
|
+
}
|
|
442
|
+
function withCliEntryContext(value, source, market, toolReference) {
|
|
443
|
+
const url = new URL(value);
|
|
444
|
+
if (url.protocol !== "https:" || url.username || url.password) throw new Error("Untrusted website continuation URL.");
|
|
445
|
+
if ([...url.searchParams.keys()].some((key) => /^(device_code|poll_token|access_token|refresh_token|cli[_-]token|token)$/i.test(key))) {
|
|
446
|
+
throw new Error("The website returned a private credential in its public continuation URL.");
|
|
447
|
+
}
|
|
448
|
+
const references = url.searchParams.getAll("tool_reference");
|
|
449
|
+
if (references.length > 1 || references.some((reference) => !UUID_PATTERN.test(reference))) throw new Error("Invalid AI tool continuation reference.");
|
|
450
|
+
url.searchParams.set("entry", "cli");
|
|
451
|
+
url.searchParams.set("source", cliEntrySource(source));
|
|
452
|
+
if (market && !url.searchParams.has("market")) url.searchParams.set("market", market);
|
|
453
|
+
if (toolReference) {
|
|
454
|
+
if (source !== "codex" || !UUID_PATTERN.test(toolReference)) throw new Error("Invalid AI tool continuation reference.");
|
|
455
|
+
if (references.length && references[0] !== toolReference) throw new Error("The website returned a mismatched AI tool continuation reference.");
|
|
456
|
+
if (!url.searchParams.has("tool_reference")) url.searchParams.set("tool_reference", toolReference);
|
|
457
|
+
}
|
|
458
|
+
return url.toString();
|
|
459
|
+
}
|
|
460
|
+
function websiteLoginUrl(market, environment, source, toolReference) {
|
|
461
|
+
if (!isWebsiteMarket(market)) throw new Error(UNSUPPORTED_MARKET);
|
|
462
|
+
const origin = websiteOrigin(market, environment);
|
|
463
|
+
const browserOrigin = origin === PRODUCTION_ISSUER ? PRODUCTION_BROWSER_ORIGIN : origin;
|
|
464
|
+
return withCliEntryContext(`${browserOrigin}${LOGIN_PATHS[market]}`, source, market, toolReference);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// src/core/onboarding/bootstrap-client.ts
|
|
468
|
+
var PATH = "/backend/demo/v1/experience/cli/bootstrap-intents";
|
|
469
|
+
var BootstrapRequestError = class extends Error {
|
|
470
|
+
constructor(websiteStatus) {
|
|
471
|
+
super(`The onboarding website request failed (HTTP ${websiteStatus}).`);
|
|
472
|
+
this.websiteStatus = websiteStatus;
|
|
473
|
+
}
|
|
474
|
+
websiteStatus;
|
|
475
|
+
};
|
|
476
|
+
function loginMode(value) {
|
|
477
|
+
if (value === void 0 || value === null) return void 0;
|
|
478
|
+
if (value === "website_login" || value === "device_confirmation") return value;
|
|
479
|
+
throw new Error("The website returned an invalid login mode.");
|
|
480
|
+
}
|
|
481
|
+
function authorizationStatus(value) {
|
|
482
|
+
if (value === void 0 || value === null) return void 0;
|
|
483
|
+
if (["pending", "authorizing", "approved", "claimed", "expired"].includes(String(value))) return value;
|
|
484
|
+
throw new Error("The website returned an invalid authorization status.");
|
|
485
|
+
}
|
|
486
|
+
function bootstrapOrigin(market, environment = websiteEnvironment()) {
|
|
487
|
+
return websiteOrigin(market, environment);
|
|
488
|
+
}
|
|
489
|
+
function trustedProductHost(value) {
|
|
490
|
+
const url = new URL(value);
|
|
491
|
+
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || !["", "/"].includes(url.pathname)) {
|
|
492
|
+
throw new Error("Onboarding requires a trusted HTTPS product origin.");
|
|
493
|
+
}
|
|
494
|
+
return url.origin;
|
|
495
|
+
}
|
|
496
|
+
function websiteUrl(value, origin) {
|
|
497
|
+
const url = new URL(value);
|
|
498
|
+
if (url.origin !== origin || url.username || url.password) throw new Error("The website returned an untrusted continuation URL.");
|
|
499
|
+
return url.toString();
|
|
500
|
+
}
|
|
501
|
+
async function request(origin, endpoint, init, signal) {
|
|
502
|
+
environmentForWebsiteOrigin(origin);
|
|
503
|
+
const response = await fetch(`${origin}${endpoint}`, {
|
|
504
|
+
...init,
|
|
505
|
+
redirect: "error",
|
|
506
|
+
signal,
|
|
507
|
+
headers: { Accept: "application/json", "Content-Type": "application/json", ...init.headers }
|
|
508
|
+
});
|
|
509
|
+
const body = safeJsonParse(await response.text());
|
|
510
|
+
if (!response.ok || body?.return_code !== 0 || !body.data || typeof body.data !== "object") {
|
|
511
|
+
throw new BootstrapRequestError(response.status);
|
|
512
|
+
}
|
|
513
|
+
return body.data;
|
|
514
|
+
}
|
|
515
|
+
async function createBootstrap(market, source, host, signal, toolReference, environment, language) {
|
|
516
|
+
const origin = bootstrapOrigin(market, environment);
|
|
517
|
+
const tool = cliEntrySource(source);
|
|
518
|
+
if (toolReference && (tool !== "codex" || !UUID_PATTERN.test(toolReference))) throw new Error("Invalid AI tool continuation reference.");
|
|
519
|
+
const data = await request(origin, PATH, { method: "POST", headers: {
|
|
520
|
+
"X-AE-CLI-Login-Mode": "website_login",
|
|
521
|
+
...language ? { "Accept-Language": language } : {}
|
|
522
|
+
}, body: JSON.stringify({
|
|
523
|
+
market,
|
|
524
|
+
source,
|
|
525
|
+
...host ? { requested_host: trustedProductHost(host) } : {},
|
|
526
|
+
...toolReference ? { tool_reference: toolReference } : {}
|
|
527
|
+
}) }, signal);
|
|
528
|
+
if (typeof data.intent_id !== "string" || !UUID_PATTERN.test(data.intent_id) || typeof data.poll_token !== "string" || data.poll_token.length < 16 || !Number.isFinite(Date.parse(data.expires_at))) {
|
|
529
|
+
throw new Error("The website returned an invalid bootstrap session.");
|
|
530
|
+
}
|
|
531
|
+
return { ...data, login_mode: loginMode(data.login_mode), login_url: withCliEntryContext(websiteUrl(data.login_url, origin), tool, market, toolReference) };
|
|
532
|
+
}
|
|
533
|
+
async function readBootstrap(origin, intentId, pollToken, signal, source, market) {
|
|
534
|
+
if (!UUID_PATTERN.test(intentId)) throw new Error("Invalid bootstrap continuation.");
|
|
535
|
+
const data = await request(origin, `${PATH}/${encodeURIComponent(intentId)}`, {
|
|
536
|
+
method: "GET",
|
|
537
|
+
headers: { "X-CLI-Bootstrap-Token": pollToken }
|
|
538
|
+
}, signal);
|
|
539
|
+
if (data.intent_id !== intentId || !["pending", "account_ready", "browser_ready", "expired"].includes(data.status)) throw new Error("Invalid bootstrap state.");
|
|
540
|
+
return {
|
|
541
|
+
...data,
|
|
542
|
+
login_mode: loginMode(data.login_mode),
|
|
543
|
+
authorization_status: authorizationStatus(data.authorization_status),
|
|
544
|
+
host: data.host ? trustedProductHost(data.host) : null,
|
|
545
|
+
ready_url: data.ready_url ? source ? withCliEntryContext(websiteUrl(data.ready_url, origin), cliEntrySource(source), market) : websiteUrl(data.ready_url, origin) : null
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
async function claimBootstrapDevice(origin, intentId, pollToken, signal) {
|
|
549
|
+
if (!UUID_PATTERN.test(intentId)) throw new Error("Invalid bootstrap continuation.");
|
|
550
|
+
const data = await request(origin, `${PATH}/${encodeURIComponent(intentId)}/device`, {
|
|
551
|
+
method: "POST",
|
|
552
|
+
body: "{}",
|
|
553
|
+
headers: { "X-CLI-Bootstrap-Token": pollToken }
|
|
554
|
+
}, signal).catch((error) => {
|
|
555
|
+
if (error instanceof BootstrapRequestError && error.websiteStatus === 410) {
|
|
556
|
+
return { login_mode: "website_login", authorization_status: "expired" };
|
|
557
|
+
}
|
|
558
|
+
throw error;
|
|
559
|
+
});
|
|
560
|
+
if (loginMode(data.login_mode) !== "website_login") throw new Error("The website did not confirm this login mode.");
|
|
561
|
+
const status = authorizationStatus(data.authorization_status);
|
|
562
|
+
if (!status) throw new Error("The website returned an invalid authorization status.");
|
|
563
|
+
if (status !== "approved" && status !== "claimed") return {
|
|
564
|
+
login_mode: "website_login",
|
|
565
|
+
authorization_status: status,
|
|
566
|
+
...Number.isFinite(data.poll_after_ms) ? { poll_after_ms: data.poll_after_ms } : {}
|
|
567
|
+
};
|
|
568
|
+
if (typeof data.device_code !== "string" || !/^uba_[A-Za-z0-9_-]{43}$/.test(data.device_code) || typeof data.user_code !== "string" || !/^[A-HJ-NP-Z2-9]{8}$/.test(data.user_code) || !Number.isFinite(Date.parse(data.expires_at)) || !Number.isFinite(data.interval) || data.interval < 1 || data.interval > 60 || typeof data.expected_login_name !== "string" || !data.expected_login_name.trim() || data.expected_login_name.length > 256 || !/^[1-9][0-9]*$/.test(String(data.expected_company_id)) || !Number.isSafeInteger(Number(data.expected_company_id))) throw new Error("The website returned an invalid device connection.");
|
|
569
|
+
return {
|
|
570
|
+
login_mode: "website_login",
|
|
571
|
+
authorization_status: status,
|
|
572
|
+
host: trustedProductHost(data.host),
|
|
573
|
+
device_code: data.device_code,
|
|
574
|
+
user_code: data.user_code,
|
|
575
|
+
expires_at: data.expires_at,
|
|
576
|
+
interval: data.interval,
|
|
577
|
+
expected_login_name: data.expected_login_name,
|
|
578
|
+
expected_company_id: String(data.expected_company_id)
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// src/core/resource-url.ts
|
|
583
|
+
var LOCAL_BACKEND_PORTS = /* @__PURE__ */ new Set(["8992", "8996"]);
|
|
584
|
+
function normalizeResourceUrlFields(node, host, sourceHost = host) {
|
|
585
|
+
if (!node || typeof node !== "object") return;
|
|
586
|
+
const obj = node;
|
|
587
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
588
|
+
if (typeof value === "string") {
|
|
589
|
+
if (/url|link/i.test(key) || value.includes("/#/")) {
|
|
590
|
+
obj[key] = normalizeResourceUrls(value, host, sourceHost);
|
|
591
|
+
}
|
|
592
|
+
} else if (value && typeof value === "object") {
|
|
593
|
+
normalizeResourceUrlFields(value, host, sourceHost);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function absolutizeRelativeUrls(s, host) {
|
|
598
|
+
return normalizeResourceUrls(s, host);
|
|
599
|
+
}
|
|
600
|
+
function normalizeResourceUrls(s, host, sourceHost = host) {
|
|
601
|
+
const base = host.replace(/\/+$/, "");
|
|
602
|
+
const sourceBase = sourceHost.replace(/\/+$/, "");
|
|
603
|
+
if (sourceBase && sourceBase !== base) {
|
|
604
|
+
s = s.replace(new RegExp(`${escapeRegExp(sourceBase)}/#`, "g"), `${base}/#`);
|
|
605
|
+
}
|
|
606
|
+
s = s.replace(/\]\((\/(?!\/)[^)]*)\)/g, `](${base}$1)`);
|
|
607
|
+
if (/^\/(?!\/)/.test(s)) s = base + s;
|
|
608
|
+
return s;
|
|
609
|
+
}
|
|
610
|
+
function resolvePublicWebHost(host) {
|
|
611
|
+
const override = process.env.AE_CLI_PUBLIC_WEB_URL || process.env.AE_CLI_WEB_HOST;
|
|
612
|
+
if (override?.trim()) {
|
|
613
|
+
return override.trim().replace(/\/+$/, "");
|
|
614
|
+
}
|
|
615
|
+
try {
|
|
616
|
+
const url = new URL(host);
|
|
617
|
+
if ((url.hostname === "127.0.0.1" || url.hostname === "localhost") && LOCAL_BACKEND_PORTS.has(url.port)) {
|
|
618
|
+
url.port = "10010";
|
|
619
|
+
return url.toString().replace(/\/+$/, "");
|
|
620
|
+
}
|
|
621
|
+
} catch {
|
|
622
|
+
}
|
|
623
|
+
return host.replace(/\/+$/, "");
|
|
624
|
+
}
|
|
625
|
+
function escapeRegExp(value) {
|
|
626
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// src/core/onboarding/interaction.ts
|
|
630
|
+
var interactions = {
|
|
631
|
+
complete_website_login: [
|
|
632
|
+
{ value: "login_done", label: "I finished signing in" },
|
|
633
|
+
{ value: "login_help", label: "Help me sign in" }
|
|
634
|
+
],
|
|
635
|
+
approve_device: [
|
|
636
|
+
{ value: "authorization_done", label: "CLI access approved" },
|
|
637
|
+
{ value: "authorization_help", label: "Help me approve CLI access" }
|
|
638
|
+
],
|
|
639
|
+
restart_website_login: [
|
|
640
|
+
{ value: "retry_login", label: "Reopen the sign-in page" },
|
|
641
|
+
{ value: "not_now", label: "Not now" }
|
|
642
|
+
],
|
|
643
|
+
choose_experience: [
|
|
644
|
+
{ value: "demo", label: "Start the demo" },
|
|
645
|
+
{ value: "business", label: "Connect my business data" }
|
|
646
|
+
],
|
|
647
|
+
demo_entry: [
|
|
648
|
+
{ value: "demo", label: "Try the sample data" },
|
|
649
|
+
{ value: "learn", label: "See what ThinkingAI can do" }
|
|
650
|
+
],
|
|
651
|
+
choose_data_source: [
|
|
652
|
+
{ value: "import_data", label: "Import a file or Feishu table" },
|
|
653
|
+
{ value: "sdk", label: "Connect an app SDK" },
|
|
654
|
+
{ value: "more_data_tools", label: "More integration tools" }
|
|
655
|
+
],
|
|
656
|
+
choose_data_tool: [
|
|
657
|
+
{ value: "datax", label: "Connect with DataX" },
|
|
658
|
+
{ value: "logbus2", label: "Configure LogBus2" },
|
|
659
|
+
{ value: "tracking_plan", label: "Create a tracking plan" },
|
|
660
|
+
{ value: "migrate_tracking", label: "Migrate existing tracking" },
|
|
661
|
+
{ value: "dimension_table", label: "Import a dimension table" },
|
|
662
|
+
{ value: "check_ingestion", label: "Check existing ingestion" }
|
|
663
|
+
],
|
|
664
|
+
confirm_business_project: [
|
|
665
|
+
{ value: "confirm_project", label: "Use this AE project" },
|
|
666
|
+
{ value: "not_now", label: "Not now" }
|
|
667
|
+
],
|
|
668
|
+
offer_growth_questions: [
|
|
669
|
+
{ value: "growth", label: "Find players worth following up with" },
|
|
670
|
+
{ value: "checkout_recovery", label: "Find players who left checkout" }
|
|
671
|
+
],
|
|
672
|
+
growth_ready: [
|
|
673
|
+
{ value: "follow_up", label: "See how to follow up" }
|
|
674
|
+
],
|
|
675
|
+
confirm_experiment: [
|
|
676
|
+
{ value: "launch", label: "Confirm and start the A/B experiment" }
|
|
677
|
+
],
|
|
678
|
+
review_experiment: [
|
|
679
|
+
{ value: "launch", label: "Approve and start the Demo test" },
|
|
680
|
+
{ value: "review_audience", label: "Why this audience?" },
|
|
681
|
+
{ value: "review_pilot", label: "How would a small pilot work?" },
|
|
682
|
+
{ value: "review_no_reward", label: "What can we test without rewards?" }
|
|
683
|
+
],
|
|
684
|
+
demo_overview: [
|
|
685
|
+
{ value: "growth", label: "Find players worth following up with" },
|
|
686
|
+
{ value: "diagnosis", label: "Investigate a business question" }
|
|
687
|
+
],
|
|
688
|
+
diagnosis_topics: [
|
|
689
|
+
{ value: "product_revisits", label: "Product revisits" },
|
|
690
|
+
{ value: "checkout_recovery", label: "Checkout without payment" },
|
|
691
|
+
{ value: "purchase_conversion", label: "Purchase conversion" }
|
|
692
|
+
],
|
|
693
|
+
reauthorize_cli: [
|
|
694
|
+
{ value: "reauthorize", label: "Reconnect the CLI" },
|
|
695
|
+
{ value: "not_now", label: "Not now" }
|
|
696
|
+
]
|
|
697
|
+
};
|
|
698
|
+
function onboardingDraftReviewInteraction(answered = []) {
|
|
699
|
+
return { step: "review_experiment", options: interactions.review_experiment.filter((option) => option.value === "launch" || !answered.includes(option.value)) };
|
|
700
|
+
}
|
|
701
|
+
function onboardingDemoOverview(sampleId, visit) {
|
|
702
|
+
const seasonPass = sampleId === "season-pass";
|
|
703
|
+
const themes = interactions.diagnosis_topics;
|
|
704
|
+
const questions = seasonPass ? [
|
|
705
|
+
"Which pass players could we win back?",
|
|
706
|
+
"Where did players leave the purchase funnel?",
|
|
707
|
+
"Which pass viewers came back without buying?"
|
|
708
|
+
] : [
|
|
709
|
+
"Which returning bundle viewers should we follow up with?",
|
|
710
|
+
"Which bundle players started checkout without buying?",
|
|
711
|
+
"Where did players leave the purchase funnel?"
|
|
712
|
+
];
|
|
713
|
+
const first = seasonPass ? 1 : 0;
|
|
714
|
+
const round = Math.max(0, visit - 1) % themes.length;
|
|
715
|
+
const index = (first + round) % themes.length;
|
|
716
|
+
const topicLabels = seasonPass ? ["Pass revisits", "Pass checkout drop-off", "Pass purchase funnel"] : ["Bundle revisits", "Bundle checkout drop-off", "Bundle purchase funnel"];
|
|
717
|
+
const sampleTopics = themes.map((topic, i) => ({ ...topic, label: topicLabels[i] }));
|
|
718
|
+
const topics = [...sampleTopics.slice(index), ...sampleTopics.slice(0, index)];
|
|
719
|
+
const growthLabels = seasonPass ? ["Find unpaid pass checkouts", "Find where pass buyers drop off", "Find returning pass viewers"] : ["Find repeat bundle viewers", "Find unpaid bundle checkouts", "Find where bundle buyers drop off"];
|
|
720
|
+
const [growth, diagnosis] = interactions.demo_overview;
|
|
721
|
+
return {
|
|
722
|
+
primary_metric: seasonPass ? "checkout_unpaid_rate" : "purchase_rate_by_viewing_days",
|
|
723
|
+
featured_topic: topics[0].value,
|
|
724
|
+
featured_question: questions[round],
|
|
725
|
+
interaction: { step: "demo_overview", options: [
|
|
726
|
+
{ ...growth, label: growthLabels[round] },
|
|
727
|
+
{ ...diagnosis, label: seasonPass ? "Investigate pass conversion" : "Investigate bundle purchases" }
|
|
728
|
+
] },
|
|
729
|
+
diagnosis: { step: "diagnosis_topics", options: topics }
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
function onboardingInteraction(step, web = false) {
|
|
733
|
+
if (!Object.hasOwn(interactions, step)) return void 0;
|
|
734
|
+
const options = web && step === "choose_experience" ? [interactions.choose_experience[0], interactions.demo_entry[1], { value: "not_now", label: "Not now" }] : interactions[step];
|
|
735
|
+
return { step, options };
|
|
736
|
+
}
|
|
737
|
+
function onboardingEvidenceLinks(evidence, projectId, host) {
|
|
738
|
+
if (!evidence || typeof evidence !== "object" || typeof projectId !== "number" || !Number.isSafeInteger(projectId) || projectId < 1) return void 0;
|
|
739
|
+
const paths = evidence;
|
|
740
|
+
const links = {};
|
|
741
|
+
const evidenceRoutes = {
|
|
742
|
+
dashboard_url: "panel/panel",
|
|
743
|
+
purchase_rate_report_url: "tga/ide",
|
|
744
|
+
funnel_report_url: "tga/funnel"
|
|
745
|
+
};
|
|
746
|
+
for (const [key, route] of Object.entries(evidenceRoutes)) {
|
|
747
|
+
const value = paths[key];
|
|
748
|
+
if (typeof value === "string" && new RegExp(`^/#/${route}/${projectId}_[1-9][0-9]*$`).test(value)) {
|
|
749
|
+
links[key] = host ? absolutizeRelativeUrls(value, host) : value;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
return Object.keys(links).length ? links : void 0;
|
|
753
|
+
}
|
|
754
|
+
function onboardingExperimentUrl(projectId, experimentId, host) {
|
|
755
|
+
const params = new URLSearchParams({ expId: experimentId, currentProjectId: String(projectId) });
|
|
756
|
+
const route = `/#/atlas/experiment/detail?${params}`;
|
|
757
|
+
return host ? absolutizeRelativeUrls(route, host) : route;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// src/core/onboarding/markdown-charts.ts
|
|
761
|
+
var barWidth = 12;
|
|
762
|
+
var ringMarks = ["\u2588", "\u2592"];
|
|
763
|
+
var stackedMarks = ["\u{1F7E6}", "\u{1F7EA}", "\u2B1C"];
|
|
764
|
+
function share(value, total) {
|
|
765
|
+
return total ? `${(value * 100 / total).toFixed(1)}%` : "\u2014";
|
|
766
|
+
}
|
|
767
|
+
function comparisonMarkdown(points, maximum, percent = false) {
|
|
768
|
+
const rows = points.map(({ label, value }) => {
|
|
769
|
+
const width = value === null || !maximum ? 0 : Math.round(value * barWidth / maximum);
|
|
770
|
+
const exact = value === null ? "\u2014" : percent ? `${value.toFixed(1)}%` : String(value);
|
|
771
|
+
return `| ${label} | ${exact} | ${"\u{1F7E6}".repeat(width)} |`;
|
|
772
|
+
});
|
|
773
|
+
return ["| Group | Value | Scale |", "| --- | ---: | --- |", ...rows].join("\n");
|
|
774
|
+
}
|
|
775
|
+
function compositionTable(points, total, marks) {
|
|
776
|
+
return ["| Group | Players | Share |", "| --- | ---: | ---: |", ...points.map(({ label, value }, index) => `| ${marks[index]} ${label} | ${value} | ${share(value, total)} |`)].join("\n");
|
|
777
|
+
}
|
|
778
|
+
function checkoutRingMarkdown(points) {
|
|
779
|
+
const total = points[0].value + points[1].value;
|
|
780
|
+
if (!total) return null;
|
|
781
|
+
const firstShare = points[0].value / total;
|
|
782
|
+
const rows = [];
|
|
783
|
+
for (let y = -4; y <= 4; y += 1) {
|
|
784
|
+
let row = "";
|
|
785
|
+
for (let x = -9; x <= 9; x += 1) {
|
|
786
|
+
const radius = Math.hypot(x / 2, y);
|
|
787
|
+
const angle = (Math.atan2(x / 2, -y) + 2 * Math.PI) % (2 * Math.PI);
|
|
788
|
+
row += radius < 2.7 || radius > 4.5 ? " " : ringMarks[angle / (2 * Math.PI) < firstShare ? 0 : 1];
|
|
789
|
+
}
|
|
790
|
+
rows.push(row.trimEnd());
|
|
791
|
+
}
|
|
792
|
+
return ["```text", ...rows, "```", "", compositionTable(points, total, ringMarks)].join("\n");
|
|
793
|
+
}
|
|
794
|
+
function audienceShareMarkdown(points) {
|
|
795
|
+
const total = points.reduce((sum, point) => sum + point.value, 0);
|
|
796
|
+
if (!total) return null;
|
|
797
|
+
const width = 20;
|
|
798
|
+
let cumulative = 0;
|
|
799
|
+
let previousBoundary = 0;
|
|
800
|
+
const marks = points.map(({ value }, index) => {
|
|
801
|
+
cumulative += value;
|
|
802
|
+
const boundary = Math.round(cumulative * width / total);
|
|
803
|
+
const segment = stackedMarks[index].repeat(boundary - previousBoundary);
|
|
804
|
+
previousBoundary = boundary;
|
|
805
|
+
return segment;
|
|
806
|
+
}).join("");
|
|
807
|
+
return `${marks}
|
|
808
|
+
|
|
809
|
+
${compositionTable(points, total, stackedMarks)}`;
|
|
810
|
+
}
|
|
811
|
+
function dailyTrendMarkdown(points) {
|
|
812
|
+
const levels = 6;
|
|
813
|
+
const counts = points.map((point) => point.value);
|
|
814
|
+
const minimum = Math.min(...counts);
|
|
815
|
+
const maximum = Math.max(...counts);
|
|
816
|
+
const step = Math.max(1, Math.ceil((maximum - minimum) / levels));
|
|
817
|
+
const baseline = Math.max(0, maximum - step * levels);
|
|
818
|
+
const spacing = 6;
|
|
819
|
+
const grid = Array.from({ length: levels + 1 }, () => Array((points.length - 1) * spacing + 1).fill(" "));
|
|
820
|
+
const heights = counts.map((value) => Math.round((value - baseline) / step));
|
|
821
|
+
for (let index = 1; index < heights.length; index += 1) {
|
|
822
|
+
const rise = heights[index] - heights[index - 1];
|
|
823
|
+
for (let offset = 1; offset < spacing; offset += 1) {
|
|
824
|
+
const height = Math.round(heights[index - 1] + rise * offset / spacing);
|
|
825
|
+
const before = Math.round(heights[index - 1] + rise * (offset - 1) / spacing);
|
|
826
|
+
const after = Math.round(heights[index - 1] + rise * (offset + 1) / spacing);
|
|
827
|
+
const stroke = before === after ? "\u2500" : rise > 0 ? "\u2571" : "\u2572";
|
|
828
|
+
grid[levels - height][(index - 1) * spacing + offset] = stroke;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
heights.forEach((height, index) => {
|
|
832
|
+
grid[levels - height][index * spacing] = "\u25CF";
|
|
833
|
+
});
|
|
834
|
+
const labelWidth = String(baseline + step * levels).length;
|
|
835
|
+
const dates = points.map((point) => point.label.slice(5).replace("-", "/"));
|
|
836
|
+
const axis = grid.map((row, index) => `${String(baseline + (levels - index) * step).padStart(labelWidth)} \u2502 ${row.join("")}`.trimEnd());
|
|
837
|
+
const table = [
|
|
838
|
+
`| Date | ${dates.join(" | ")} |`,
|
|
839
|
+
`| --- | ${dates.map(() => "---:").join(" | ")} |`,
|
|
840
|
+
`| Viewers | ${points.map((point) => point.value).join(" | ")} |`
|
|
841
|
+
];
|
|
842
|
+
return [
|
|
843
|
+
"```text",
|
|
844
|
+
...axis,
|
|
845
|
+
`${" ".repeat(labelWidth + 1)} \u2514${"\u2500".repeat(grid[0].length + 2)}`,
|
|
846
|
+
`${" ".repeat(labelWidth + 1)}${dates.join(" ")}`,
|
|
847
|
+
"```",
|
|
848
|
+
"",
|
|
849
|
+
...table
|
|
850
|
+
].join("\n");
|
|
851
|
+
}
|
|
852
|
+
function funnelMarkdown(points, transitions) {
|
|
853
|
+
const peak = points[0].value;
|
|
854
|
+
const rows = points.map(({ label, value }, index) => {
|
|
855
|
+
const width = peak ? Math.round(value * barWidth / peak) : 0;
|
|
856
|
+
const transition = transitions[index - 1];
|
|
857
|
+
const rate = transition?.conversion_rate;
|
|
858
|
+
return `| ${label} | ${value} | ${"\u2501".repeat(width)} | ${transition?.dropoff_accounts ?? "\u2014"} | ${rate == null ? "\u2014" : share(rate, 1)} |`;
|
|
859
|
+
});
|
|
860
|
+
return ["| Step | Players | Scale | Drop-off | Conversion |", "| --- | ---: | :---: | ---: | ---: |", ...rows].join("\n");
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
// src/core/onboarding/growth.ts
|
|
864
|
+
var GROWTH_VERSION = 2;
|
|
865
|
+
var CACHE_TTL_MS = 10 * 6e4;
|
|
866
|
+
var DAY_MS = 864e5;
|
|
867
|
+
var SAMPLE_DAYS = 7;
|
|
868
|
+
var VIEW = "item_detail_view";
|
|
869
|
+
var CHECKOUT = "checkout_start";
|
|
870
|
+
var PAYMENT = "payment_success";
|
|
871
|
+
var fields = [
|
|
872
|
+
"single_viewers",
|
|
873
|
+
"single_buyers",
|
|
874
|
+
"multi_viewers",
|
|
875
|
+
"multi_buyers",
|
|
876
|
+
"funnel_viewers",
|
|
877
|
+
"funnel_checkout",
|
|
878
|
+
"funnel_buyers",
|
|
879
|
+
"account_ids_json",
|
|
880
|
+
"checkout_unpaid",
|
|
881
|
+
"checkout_account_ids_json",
|
|
882
|
+
"unmapped_accounts"
|
|
883
|
+
];
|
|
884
|
+
function date(value) {
|
|
885
|
+
return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
|
|
886
|
+
}
|
|
887
|
+
function shiftDate(value, days) {
|
|
888
|
+
return new Date(Date.parse(value) + days * DAY_MS).toISOString().slice(0, 10);
|
|
889
|
+
}
|
|
890
|
+
function sampleDates(startDate) {
|
|
891
|
+
return Array.from({ length: SAMPLE_DAYS }, (_, index) => shiftDate(startDate, index));
|
|
892
|
+
}
|
|
893
|
+
function growthScope(session, demo) {
|
|
894
|
+
const { project_id, sample_id, item_id, start_date, end_date, zone_offset } = demo;
|
|
895
|
+
if (!session.host || !sample_id || sample_id !== session.sample_id || typeof project_id !== "number" || !Number.isSafeInteger(project_id) || project_id <= 0 || project_id === session.project_id || typeof item_id !== "string" || !item_id.trim() || item_id.length > 128 || !date(start_date) || !date(end_date) || Date.parse(end_date) - Date.parse(start_date) !== (SAMPLE_DAYS - 1) * DAY_MS || typeof zone_offset !== "number" || !Number.isFinite(zone_offset) || Math.abs(zone_offset) > 14) return void 0;
|
|
896
|
+
return {
|
|
897
|
+
sessionId: session.id,
|
|
898
|
+
host: trustedProductHost(session.host),
|
|
899
|
+
projectId: project_id,
|
|
900
|
+
sampleId: sample_id,
|
|
901
|
+
itemId: item_id,
|
|
902
|
+
startDate: start_date,
|
|
903
|
+
endDate: end_date,
|
|
904
|
+
zoneOffset: zone_offset
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
function evidenceFile(scope, credentialKey) {
|
|
908
|
+
const digest = crypto.createHash("sha256").update(JSON.stringify([GROWTH_VERSION, credentialKey, scope])).digest("hex");
|
|
909
|
+
return `growth-${digest}.json`;
|
|
910
|
+
}
|
|
911
|
+
function readGrowthEvidence(store, file, scope) {
|
|
912
|
+
const evidence = store.read(file);
|
|
913
|
+
if (evidence?.analysisVersion === GROWTH_VERSION && evidence.schemaVersion === 1 && Object.entries(scope).every(([key, value]) => evidence[key] === value) && Array.isArray(evidence.accountIds) && Array.isArray(evidence.checkoutAccountIds) && evidence.single_day && evidence.multi_day && evidence.funnel) return evidence;
|
|
914
|
+
}
|
|
915
|
+
function readCheckoutRecoveryCohort(store, session, demo) {
|
|
916
|
+
const scope = growthScope(session, demo);
|
|
917
|
+
if (!scope || !session.credential_key) return void 0;
|
|
918
|
+
const evidence = readGrowthEvidence(store, evidenceFile(scope, session.credential_key), scope);
|
|
919
|
+
if (!evidence) return void 0;
|
|
920
|
+
return { start_date: scope.startDate, end_date: scope.endDate, zone_offset: scope.zoneOffset, account_ids: evidence.checkoutAccountIds };
|
|
921
|
+
}
|
|
922
|
+
function sqlString(value) {
|
|
923
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
924
|
+
}
|
|
925
|
+
function verifiedTables(result2, type) {
|
|
926
|
+
return result2.items.filter((item) => item?.table_type === type && typeof item.sql_reference === "string" && /^(?:"(?:[^"\u0000-\u001f]|"")+"\.){2}"(?:[^"\u0000-\u001f]|"")+"$/.test(item.sql_reference)).map((item) => item.sql_reference);
|
|
927
|
+
}
|
|
928
|
+
async function resolveEventSource(call, projectId) {
|
|
929
|
+
let offset = 0;
|
|
930
|
+
const events = /* @__PURE__ */ new Set();
|
|
931
|
+
const users = /* @__PURE__ */ new Set();
|
|
932
|
+
const scope = { project_id: projectId, usage: "analysis" };
|
|
933
|
+
while (true) {
|
|
934
|
+
const page = await call("analysis.sql_table.list", { ...scope, limit: 200, offset });
|
|
935
|
+
if (!Array.isArray(page?.items) || typeof page.has_more !== "boolean") throw new Error("AE did not return the authorized SQL tables.");
|
|
936
|
+
verifiedTables(page, "eventView").forEach((name) => events.add(name));
|
|
937
|
+
verifiedTables(page, "userView").forEach((name) => users.add(name));
|
|
938
|
+
if (!page.has_more) break;
|
|
939
|
+
if (!Number.isSafeInteger(page.next_offset) || page.next_offset <= offset) throw new Error("AE returned an invalid SQL table continuation.");
|
|
940
|
+
offset = page.next_offset;
|
|
941
|
+
}
|
|
942
|
+
if (events.size !== 1) throw new Error("AE did not return exactly one authorized Demo event view.");
|
|
943
|
+
const event = [...events][0];
|
|
944
|
+
const readColumns = async (table_ref) => {
|
|
945
|
+
const result2 = await call("analysis.sql_table.columns", { ...scope, table_ref });
|
|
946
|
+
if (!Array.isArray(result2?.columns)) throw new Error("AE did not return the authorized Demo columns.");
|
|
947
|
+
return new Set(result2.columns.map((entry) => entry.column));
|
|
948
|
+
};
|
|
949
|
+
const columns = await readColumns(event);
|
|
950
|
+
if (!["#event_time", "$part_date", "$part_event", "plg_sample_id", "item_id", "plg_seed_event_id"].every((name) => columns.has(name))) {
|
|
951
|
+
throw new Error("The authorized Demo view is missing the fields required for growth analysis.");
|
|
952
|
+
}
|
|
953
|
+
if (columns.has("#account_id")) return { from: `${event} e`, account: 'e."#account_id"' };
|
|
954
|
+
if (!columns.has("#user_id") || users.size !== 1) throw new Error("AE did not expose a verified Demo account-ID mapping.");
|
|
955
|
+
const user = [...users][0];
|
|
956
|
+
const userColumns = await readColumns(user);
|
|
957
|
+
if (!userColumns.has("#user_id") || !userColumns.has("#account_id")) throw new Error("AE did not expose a verified Demo account-ID mapping.");
|
|
958
|
+
return { from: `${event} e LEFT JOIN ${user} u ON e."#user_id" = u."#user_id"`, account: 'u."#account_id"' };
|
|
959
|
+
}
|
|
960
|
+
function growthSql(scope, source) {
|
|
961
|
+
const dailyCounts = sampleDates(scope.startDate).map((day) => `count_if(contains(view_dates, DATE '${day}'))`);
|
|
962
|
+
return `WITH sample_events AS (
|
|
963
|
+
SELECT NULLIF(CAST(${source.account} AS varchar), '') AS account_id,
|
|
964
|
+
e."$part_event" AS event_name, e."#event_time" AS event_time
|
|
965
|
+
FROM ${source.from}
|
|
966
|
+
WHERE e."$part_date" BETWEEN '${shiftDate(scope.startDate, -1)}' AND '${shiftDate(scope.endDate, 1)}'
|
|
967
|
+
AND e."#event_time" >= TIMESTAMP '${scope.startDate} 00:00:00'
|
|
968
|
+
AND e."#event_time" < TIMESTAMP '${shiftDate(scope.endDate, 1)} 00:00:00'
|
|
969
|
+
AND e.plg_sample_id = ${sqlString(scope.sampleId)} AND e.item_id = ${sqlString(scope.itemId)}
|
|
970
|
+
AND e.plg_seed_event_id IS NOT NULL
|
|
971
|
+
AND e."$part_event" IN ('${VIEW}', '${CHECKOUT}', '${PAYMENT}')
|
|
972
|
+
), views AS (
|
|
973
|
+
SELECT *, min(CASE WHEN event_name = '${VIEW}' THEN event_time END) OVER (PARTITION BY account_id) AS first_view
|
|
974
|
+
FROM sample_events
|
|
975
|
+
), checkouts AS (
|
|
976
|
+
SELECT *, min(CASE WHEN event_name = '${CHECKOUT}' AND event_time > first_view THEN event_time END)
|
|
977
|
+
OVER (PARTITION BY account_id) AS first_checkout
|
|
978
|
+
FROM views
|
|
979
|
+
), activity AS (
|
|
980
|
+
SELECT account_id, array_agg(DISTINCT CAST(event_time AS date)) FILTER (WHERE event_name = '${VIEW}') AS view_dates,
|
|
981
|
+
count_if(event_name = '${PAYMENT}') > 0 AS bought,
|
|
982
|
+
count_if(first_checkout IS NOT NULL) > 0 AS checked_out,
|
|
983
|
+
count_if(event_name = '${PAYMENT}' AND event_time > first_checkout) > 0 AS paid_after_checkout
|
|
984
|
+
FROM checkouts GROUP BY account_id
|
|
985
|
+
), accounts AS (
|
|
986
|
+
SELECT *, COALESCE(cardinality(view_dates), 0) AS view_days FROM activity
|
|
987
|
+
)
|
|
988
|
+
SELECT count_if(view_days = 1) AS single_viewers, count_if(view_days = 1 AND bought) AS single_buyers,
|
|
989
|
+
count_if(view_days >= 2) AS multi_viewers, count_if(view_days >= 2 AND bought) AS multi_buyers,
|
|
990
|
+
count_if(view_days > 0) AS funnel_viewers, count_if(checked_out) AS funnel_checkout,
|
|
991
|
+
count_if(paid_after_checkout) AS funnel_buyers,
|
|
992
|
+
COALESCE(json_format(CAST(array_sort(array_agg(account_id) FILTER (WHERE view_days >= 2 AND NOT bought)) AS JSON)), '[]') AS account_ids_json,
|
|
993
|
+
count_if(checked_out AND NOT bought) AS checkout_unpaid,
|
|
994
|
+
COALESCE(json_format(CAST(array_sort(array_agg(account_id) FILTER (WHERE checked_out AND NOT bought)) AS JSON)), '[]') AS checkout_account_ids_json,
|
|
995
|
+
count_if(account_id IS NULL) AS unmapped_accounts,
|
|
996
|
+
json_format(CAST(ARRAY[${dailyCounts.join(", ")}] AS JSON)) AS daily_viewers_json
|
|
997
|
+
FROM accounts`;
|
|
998
|
+
}
|
|
999
|
+
function accountIds(value, expected) {
|
|
1000
|
+
let ids;
|
|
1001
|
+
try {
|
|
1002
|
+
ids = typeof value === "string" ? JSON.parse(value) : void 0;
|
|
1003
|
+
} catch {
|
|
1004
|
+
}
|
|
1005
|
+
if (!Array.isArray(ids) || ids.length !== expected || new Set(ids).size !== ids.length || !ids.every((id) => typeof id === "string" && id.length > 0 && id.length <= 256 && id === id.trim())) {
|
|
1006
|
+
throw new Error("AE returned incomplete or inconsistent Demo growth evidence.");
|
|
1007
|
+
}
|
|
1008
|
+
return ids;
|
|
1009
|
+
}
|
|
1010
|
+
function parseDailyViewers(value, viewers) {
|
|
1011
|
+
if (typeof value !== "string") return void 0;
|
|
1012
|
+
let counts;
|
|
1013
|
+
try {
|
|
1014
|
+
counts = JSON.parse(value);
|
|
1015
|
+
} catch {
|
|
1016
|
+
return void 0;
|
|
1017
|
+
}
|
|
1018
|
+
if (!Array.isArray(counts) || counts.length !== SAMPLE_DAYS || !counts.every((count) => Number.isSafeInteger(count) && count >= 0 && count <= viewers) || counts.reduce((sum, count) => sum + count, 0) < viewers) return void 0;
|
|
1019
|
+
return counts;
|
|
1020
|
+
}
|
|
1021
|
+
function parseGrowth(result2, scope, verifiedAt) {
|
|
1022
|
+
if (result2?.has_more !== false || result2.returned_rows !== 1 || result2.rows?.length !== 1 || !Array.isArray(result2.title) || !Array.isArray(result2.rows[0])) {
|
|
1023
|
+
throw new Error("AE did not return a complete Demo growth result.");
|
|
1024
|
+
}
|
|
1025
|
+
const row = Object.fromEntries(result2.title.map((name, index) => [name, result2.rows[0][index]]));
|
|
1026
|
+
if (!fields.every((field) => Object.hasOwn(row, field))) throw new Error("AE did not return the expected Demo growth fields.");
|
|
1027
|
+
const count = (field) => {
|
|
1028
|
+
const raw = row[field];
|
|
1029
|
+
const value = typeof raw === "string" && /^\d+$/.test(raw) ? Number(raw) : raw;
|
|
1030
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error("AE returned an invalid Demo growth count.");
|
|
1031
|
+
return value;
|
|
1032
|
+
};
|
|
1033
|
+
const single_day = { viewers: count("single_viewers"), buyers: count("single_buyers") };
|
|
1034
|
+
const multi_day = { viewers: count("multi_viewers"), buyers: count("multi_buyers") };
|
|
1035
|
+
const funnel = { viewers: count("funnel_viewers"), checkout: count("funnel_checkout"), buyers: count("funnel_buyers") };
|
|
1036
|
+
const checkoutUnpaid = count("checkout_unpaid");
|
|
1037
|
+
if (single_day.buyers > single_day.viewers || multi_day.buyers > multi_day.viewers || funnel.checkout > funnel.viewers || funnel.buyers + checkoutUnpaid > funnel.checkout || funnel.viewers !== single_day.viewers + multi_day.viewers || count("unmapped_accounts") !== 0 || funnel.viewers === 0) {
|
|
1038
|
+
throw new Error("AE returned incomplete or inconsistent Demo growth evidence.");
|
|
1039
|
+
}
|
|
1040
|
+
return {
|
|
1041
|
+
...scope,
|
|
1042
|
+
schemaVersion: 1,
|
|
1043
|
+
analysisVersion: GROWTH_VERSION,
|
|
1044
|
+
verifiedAt,
|
|
1045
|
+
single_day,
|
|
1046
|
+
multi_day,
|
|
1047
|
+
funnel,
|
|
1048
|
+
dailyViewers: parseDailyViewers(row.daily_viewers_json, funnel.viewers),
|
|
1049
|
+
accountIds: accountIds(row.account_ids_json, multi_day.viewers - multi_day.buyers),
|
|
1050
|
+
checkoutAccountIds: accountIds(row.checkout_account_ids_json, checkoutUnpaid)
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
async function runOnboardingGrowth(store, deps, input, preview) {
|
|
1054
|
+
const scenario = onboardingGrowthScenario(input.scenario);
|
|
1055
|
+
const sessionId = input.session_id;
|
|
1056
|
+
if (!sessionId || !UUID_PATTERN.test(sessionId)) throw new Error("A valid onboarding --session-id is required.");
|
|
1057
|
+
const explicitHost = input.host ? trustedProductHost(input.host) : void 0;
|
|
1058
|
+
const readSession = () => store.session(sessionId, explicitHost);
|
|
1059
|
+
if (preview) {
|
|
1060
|
+
const session = readSession();
|
|
1061
|
+
return {
|
|
1062
|
+
dry_run: true,
|
|
1063
|
+
session_id: sessionId,
|
|
1064
|
+
host: session.host ?? null,
|
|
1065
|
+
sample_id: session.sample_id ?? null,
|
|
1066
|
+
scenario,
|
|
1067
|
+
capabilities: [DEMO_STATUS, "analysis.sql_table.list", "analysis.sql_table.columns", "analysis.adhoc.run"]
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
const started = deps.now();
|
|
1071
|
+
const signal = AbortSignal.timeout(RUN_BUDGET_MS);
|
|
1072
|
+
return store.locked(`session:${sessionId}`, async () => {
|
|
1073
|
+
const session = readSession();
|
|
1074
|
+
const base = { session_id: sessionId, host: session.host ?? null, sample_id: session.sample_id ?? null, scenario };
|
|
1075
|
+
if (!session.host || !session.credential_key || session.requires_auth || deps.credentialKey(session.host) !== session.credential_key) {
|
|
1076
|
+
return {
|
|
1077
|
+
...base,
|
|
1078
|
+
phase: "action_required",
|
|
1079
|
+
next_action: "resume_onboarding",
|
|
1080
|
+
poll_after_ms: 0,
|
|
1081
|
+
message: "Resume onboarding with the signed-in account for this session."
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
const host = trustedProductHost(session.host);
|
|
1085
|
+
if (session.choice !== "demo" || !session.sample_id || !DEMO_SAMPLE_IDS.some((sample) => sample === session.sample_id)) {
|
|
1086
|
+
return {
|
|
1087
|
+
...base,
|
|
1088
|
+
phase: "action_required",
|
|
1089
|
+
next_action: "choose_demo",
|
|
1090
|
+
poll_after_ms: 0,
|
|
1091
|
+
message: "Select a supported Demo in this onboarding session."
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
const call = async (id, body) => {
|
|
1095
|
+
signal.throwIfAborted();
|
|
1096
|
+
const request2 = new AbortController();
|
|
1097
|
+
const abort = () => request2.abort();
|
|
1098
|
+
const timer = setTimeout(abort, NETWORK_BUDGET_MS);
|
|
1099
|
+
timer.unref();
|
|
1100
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
1101
|
+
try {
|
|
1102
|
+
const result2 = await deps.capability(host, id, body, request2.signal);
|
|
1103
|
+
request2.signal.throwIfAborted();
|
|
1104
|
+
return result2;
|
|
1105
|
+
} finally {
|
|
1106
|
+
signal.removeEventListener("abort", abort);
|
|
1107
|
+
clearTimeout(timer);
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
try {
|
|
1111
|
+
const demo = await call(DEMO_STATUS, { sample_id: session.sample_id });
|
|
1112
|
+
if (typeof demo?.status !== "string" || demo.sample_id !== session.sample_id) {
|
|
1113
|
+
throw new Error("AE did not confirm the selected Demo sample.");
|
|
1114
|
+
}
|
|
1115
|
+
if (demo.status !== "ready") {
|
|
1116
|
+
return demo.status === "action_required" ? {
|
|
1117
|
+
...base,
|
|
1118
|
+
phase: "action_required",
|
|
1119
|
+
next_action: "inspect_demo_preparation",
|
|
1120
|
+
poll_after_ms: 0,
|
|
1121
|
+
message: "Demo preparation needs attention before analysis can run."
|
|
1122
|
+
} : { ...base, phase: "pending", next_action: "poll_demo", poll_after_ms: 2e3 };
|
|
1123
|
+
}
|
|
1124
|
+
const scope = growthScope(session, demo);
|
|
1125
|
+
if (!scope) throw new Error("AE did not confirm the active Demo project and its seven-day sample scope.");
|
|
1126
|
+
const file = evidenceFile(scope, session.credential_key);
|
|
1127
|
+
let evidence = readGrowthEvidence(store, file, scope);
|
|
1128
|
+
const cached = evidence !== void 0 && deps.now() - evidence.verifiedAt >= 0 && deps.now() - evidence.verifiedAt < CACHE_TTL_MS;
|
|
1129
|
+
let queryMs = 0;
|
|
1130
|
+
if (!evidence || !cached) {
|
|
1131
|
+
const source = await resolveEventSource(call, scope.projectId);
|
|
1132
|
+
const queryStarted = deps.now();
|
|
1133
|
+
const rows = await call("analysis.adhoc.run", {
|
|
1134
|
+
project_id: scope.projectId,
|
|
1135
|
+
model_type: "sql",
|
|
1136
|
+
definition: { sql: growthSql(scope, source) },
|
|
1137
|
+
use_cache: false
|
|
1138
|
+
});
|
|
1139
|
+
queryMs = Math.max(0, deps.now() - queryStarted);
|
|
1140
|
+
evidence = parseGrowth(rows, scope, deps.now());
|
|
1141
|
+
}
|
|
1142
|
+
if (deps.credentialKey(host) !== session.credential_key) throw new Error("The active CLI account changed during Demo growth analysis.");
|
|
1143
|
+
if (!cached) store.write(file, evidence);
|
|
1144
|
+
const readyDemo = {
|
|
1145
|
+
sample_id: scope.sampleId,
|
|
1146
|
+
item_id: scope.itemId,
|
|
1147
|
+
project_id: scope.projectId,
|
|
1148
|
+
start_date: scope.startDate,
|
|
1149
|
+
end_date: scope.endDate,
|
|
1150
|
+
zone_offset: scope.zoneOffset
|
|
1151
|
+
};
|
|
1152
|
+
if (!Object.entries(readyDemo).every(([key, value]) => session.ready_demo?.[key] === value)) {
|
|
1153
|
+
session.ready_demo = readyDemo;
|
|
1154
|
+
store.save(session);
|
|
1155
|
+
}
|
|
1156
|
+
const singleRate = evidence.single_day.viewers ? evidence.single_day.buyers / evidence.single_day.viewers : null;
|
|
1157
|
+
const multiRate = evidence.multi_day.viewers ? evidence.multi_day.buyers / evidence.multi_day.viewers : null;
|
|
1158
|
+
const checkoutUnpaid = evidence.checkoutAccountIds.length;
|
|
1159
|
+
const checkoutAccounts = new Set(evidence.checkoutAccountIds);
|
|
1160
|
+
const overlappingAccounts = evidence.accountIds.filter((id) => checkoutAccounts.has(id)).length;
|
|
1161
|
+
const funnelSteps = [
|
|
1162
|
+
{ event: VIEW, accounts: evidence.funnel.viewers },
|
|
1163
|
+
{ event: CHECKOUT, accounts: evidence.funnel.checkout },
|
|
1164
|
+
{ event: PAYMENT, accounts: evidence.funnel.buyers }
|
|
1165
|
+
];
|
|
1166
|
+
const funnelTransitions = funnelSteps.slice(1).map((step, index) => {
|
|
1167
|
+
const previous = funnelSteps[index];
|
|
1168
|
+
return {
|
|
1169
|
+
from_event: previous.event,
|
|
1170
|
+
to_event: step.event,
|
|
1171
|
+
from_accounts: previous.accounts,
|
|
1172
|
+
to_accounts: step.accounts,
|
|
1173
|
+
dropoff_accounts: previous.accounts - step.accounts,
|
|
1174
|
+
conversion_rate: previous.accounts ? step.accounts / previous.accounts : null
|
|
1175
|
+
};
|
|
1176
|
+
});
|
|
1177
|
+
const followUpData = scenario === CHECKOUT_RECOVERY ? [
|
|
1178
|
+
{ label: "Started checkout", value: evidence.funnel.checkout },
|
|
1179
|
+
{ label: "Paid after checkout", value: evidence.funnel.buyers },
|
|
1180
|
+
{ label: "Checkout without payment", value: checkoutUnpaid }
|
|
1181
|
+
] : [
|
|
1182
|
+
{ label: "Multi-day viewers, unpaid", value: evidence.accountIds.length },
|
|
1183
|
+
{ label: "Single-day viewers, unpaid", value: evidence.single_day.viewers - evidence.single_day.buyers },
|
|
1184
|
+
{ label: "Paid viewers", value: evidence.single_day.buyers + evidence.multi_day.buyers }
|
|
1185
|
+
];
|
|
1186
|
+
const maxCount = Math.max(1, ...followUpData.map((row) => row.value));
|
|
1187
|
+
const followUpMarkdown = followUpData.map(({ label, value }) => {
|
|
1188
|
+
const width = value === 0 ? 0 : Math.max(1, Math.round(value * 10 / maxCount));
|
|
1189
|
+
return `- ${label} \xB7 ${width ? "\u2588".repeat(width) + " " : ""}**${value}**`;
|
|
1190
|
+
}).join("\n");
|
|
1191
|
+
const checkoutTotal = evidence.funnel.checkout;
|
|
1192
|
+
const checkoutOther = checkoutTotal - checkoutUnpaid;
|
|
1193
|
+
const checkoutShare = [
|
|
1194
|
+
{ label: "Started checkout without paying", value: checkoutUnpaid },
|
|
1195
|
+
{ label: checkoutOther === evidence.funnel.buyers ? "Paid after checkout" : "Other checkout starters", value: checkoutOther }
|
|
1196
|
+
];
|
|
1197
|
+
const audienceOverlap = [
|
|
1198
|
+
{ label: "Both signals", value: overlappingAccounts },
|
|
1199
|
+
{ label: "Started checkout only", value: checkoutUnpaid - overlappingAccounts },
|
|
1200
|
+
{ label: "Viewed on multiple days only", value: evidence.accountIds.length - overlappingAccounts }
|
|
1201
|
+
];
|
|
1202
|
+
const purchaseRateData = [
|
|
1203
|
+
...singleRate === null ? [] : [{ label: "Single-day viewers", value: Math.round(singleRate * 1e3) / 10 }],
|
|
1204
|
+
...multiRate === null ? [] : [{ label: "Multi-day viewers", value: Math.round(multiRate * 1e3) / 10 }]
|
|
1205
|
+
];
|
|
1206
|
+
const funnelData = [
|
|
1207
|
+
{ label: "Viewed", value: evidence.funnel.viewers },
|
|
1208
|
+
{ label: "Started checkout", value: checkoutTotal },
|
|
1209
|
+
{ label: "Paid", value: evidence.funnel.buyers }
|
|
1210
|
+
];
|
|
1211
|
+
const dailyViewers = evidence.dailyViewers;
|
|
1212
|
+
const dailyData = dailyViewers && sampleDates(scope.startDate).map((label, index) => ({ label, value: dailyViewers[index] }));
|
|
1213
|
+
return {
|
|
1214
|
+
...base,
|
|
1215
|
+
phase: "ready",
|
|
1216
|
+
demo_project_id: scope.projectId,
|
|
1217
|
+
item_id: scope.itemId,
|
|
1218
|
+
start_date: scope.startDate,
|
|
1219
|
+
end_date: scope.endDate,
|
|
1220
|
+
zone_offset: scope.zoneOffset,
|
|
1221
|
+
analysis_version: GROWTH_VERSION,
|
|
1222
|
+
single_day: evidence.single_day,
|
|
1223
|
+
multi_day: evidence.multi_day,
|
|
1224
|
+
funnel: evidence.funnel,
|
|
1225
|
+
purchase_rates: {
|
|
1226
|
+
single_day: singleRate,
|
|
1227
|
+
multi_day: multiRate,
|
|
1228
|
+
difference_pp: singleRate === null || multiRate === null ? null : (multiRate - singleRate) * 100
|
|
1229
|
+
},
|
|
1230
|
+
data_basis: { source: "demo_seed_events", counting_unit: "distinct_accounts", funnel_transitions: funnelTransitions },
|
|
1231
|
+
charts: {
|
|
1232
|
+
purchase_rate: { type: "bar", data: purchaseRateData },
|
|
1233
|
+
funnel: { type: "bar", data: funnelData },
|
|
1234
|
+
...dailyData ? { daily_viewers: { type: "line", data: dailyData } } : {}
|
|
1235
|
+
},
|
|
1236
|
+
visuals: {
|
|
1237
|
+
overview: scope.sampleId === "season-pass" ? "checkout_share" : "purchase_rate",
|
|
1238
|
+
checkout_share: checkoutTotal > 0 ? { type: "pie", data: checkoutShare } : null,
|
|
1239
|
+
audience_overlap: { type: "pie", data: audienceOverlap }
|
|
1240
|
+
},
|
|
1241
|
+
markdown_charts: {
|
|
1242
|
+
purchase_rate: comparisonMarkdown([
|
|
1243
|
+
{ label: "Single-day viewers", value: singleRate === null ? null : singleRate * 100 },
|
|
1244
|
+
{ label: "Multi-day viewers", value: multiRate === null ? null : multiRate * 100 }
|
|
1245
|
+
], 100, true),
|
|
1246
|
+
checkout_share: checkoutRingMarkdown(checkoutShare),
|
|
1247
|
+
audience_overlap: audienceShareMarkdown(audienceOverlap),
|
|
1248
|
+
purchase_funnel: funnelMarkdown(funnelData, funnelTransitions),
|
|
1249
|
+
follow_up: comparisonMarkdown(followUpData, maxCount),
|
|
1250
|
+
...dailyData ? { daily_viewers: dailyTrendMarkdown(dailyData) } : {}
|
|
1251
|
+
},
|
|
1252
|
+
follow_up_chart: { type: "bar", data: followUpData, markdown: followUpMarkdown },
|
|
1253
|
+
follow_up_count: scenario === CHECKOUT_RECOVERY ? checkoutUnpaid : evidence.accountIds.length,
|
|
1254
|
+
checkout_recovery: { unpaid_count: checkoutUnpaid, unpaid_rate: evidence.funnel.checkout ? checkoutUnpaid / evidence.funnel.checkout : null },
|
|
1255
|
+
candidate_cohorts: {
|
|
1256
|
+
multi_day_unpaid: evidence.accountIds.length,
|
|
1257
|
+
checkout_unpaid: checkoutUnpaid,
|
|
1258
|
+
overlap: overlappingAccounts,
|
|
1259
|
+
total_distinct: evidence.accountIds.length + checkoutUnpaid - overlappingAccounts
|
|
1260
|
+
},
|
|
1261
|
+
cohort_path: path2.resolve(store.directory, file),
|
|
1262
|
+
evidence: onboardingEvidenceLinks(demo.evidence, scope.projectId, deps.webConversation ? void 0 : host),
|
|
1263
|
+
interaction: onboardingInteraction(scenario === CHECKOUT_RECOVERY && checkoutUnpaid < 2 ? "offer_growth_questions" : "growth_ready"),
|
|
1264
|
+
cached,
|
|
1265
|
+
query_ms: queryMs,
|
|
1266
|
+
elapsed_ms: Math.max(0, deps.now() - started),
|
|
1267
|
+
poll_after_ms: 0
|
|
1268
|
+
};
|
|
1269
|
+
} catch (error) {
|
|
1270
|
+
if (signal.aborted || error instanceof Error && ["AbortError", "TimeoutError"].includes(error.name)) {
|
|
1271
|
+
return { ...base, phase: "pending", next_action: "retry_growth", poll_after_ms: 2e3 };
|
|
1272
|
+
}
|
|
1273
|
+
throw error;
|
|
1274
|
+
}
|
|
1275
|
+
});
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
// src/core/onboarding/progress.ts
|
|
1279
|
+
var PROGRESS = "analysis.plg_onboarding.progress";
|
|
1280
|
+
var progressOrigins = /* @__PURE__ */ new Set([
|
|
1281
|
+
"https://ae-web.thinkingai.cn",
|
|
1282
|
+
"https://ae-web-global.thinkingai.io",
|
|
1283
|
+
`https://${OVERSEAS_TEST_PRODUCT_HOSTNAME}`
|
|
1284
|
+
]);
|
|
1285
|
+
function isOnboardingProgressHost(host) {
|
|
1286
|
+
if (!host) return false;
|
|
1287
|
+
try {
|
|
1288
|
+
return progressOrigins.has(new URL(host).origin);
|
|
1289
|
+
} catch {
|
|
1290
|
+
return false;
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
function writeProgress(deps, host, action, input) {
|
|
1294
|
+
return deps.capability(host, PROGRESS, { action, ...input }, AbortSignal.timeout(5e3));
|
|
1295
|
+
}
|
|
1296
|
+
async function readProgress(deps, host) {
|
|
1297
|
+
try {
|
|
1298
|
+
const result2 = await writeProgress(deps, host, "status", {});
|
|
1299
|
+
if (["disabled", "unavailable", "not_started", "in_progress", "completed"].includes(result2?.state)) return result2;
|
|
1300
|
+
return { state: "unavailable" };
|
|
1301
|
+
} catch (error) {
|
|
1302
|
+
return { state: error?.httpStatus === 404 || error?.code === "CAPABILITY_NOT_FOUND" ? "disabled" : "unavailable" };
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
async function verifyAndCompleteProgress(deps, host, runId) {
|
|
1306
|
+
const progress = await readProgress(deps, host);
|
|
1307
|
+
if (progress.state !== "in_progress") return progress;
|
|
1308
|
+
const { receipt, experiment_id, journey_id, demo_project_id } = progress;
|
|
1309
|
+
if (progress.run_id !== runId || !receipt || !experiment_id || !journey_id || !demo_project_id) {
|
|
1310
|
+
throw new Error("The current Demo replay checkpoint is not ready. Resume the experiment in the session that started it.");
|
|
1311
|
+
}
|
|
1312
|
+
const call = (id, input) => deps.capability(host, id, input, AbortSignal.timeout(1e4));
|
|
1313
|
+
const source = await resolveEventSource(call, demo_project_id);
|
|
1314
|
+
const dates = replayReportDates(receipt);
|
|
1315
|
+
const shiftDate2 = (date2, days) => new Date(Date.parse(date2) + days * 864e5).toISOString().slice(0, 10);
|
|
1316
|
+
const expected = /* @__PURE__ */ new Set();
|
|
1317
|
+
const key = (event, group, account) => JSON.stringify([event, group, account]);
|
|
1318
|
+
for (const arm of Object.values(receipt.arms)) {
|
|
1319
|
+
for (const account of arm.exposed_account_ids) expected.add(key("te_experiment_exposure", arm.group_id, account));
|
|
1320
|
+
for (const account of arm.coupon_claim_account_ids) expected.add(key("demo_coupon_claim", "", account));
|
|
1321
|
+
for (const account of arm.paid_account_ids) expected.add(key("payment_success", "", account));
|
|
1322
|
+
}
|
|
1323
|
+
if (!expected.size) throw new Error("The Demo replay checkpoint contains no events.");
|
|
1324
|
+
const sql = `SELECT DISTINCT e."$part_event", CAST(${source.account} AS varchar),
|
|
1325
|
+
CASE WHEN e."$part_event" = 'te_experiment_exposure' THEN CAST(e.experiment_group_id AS varchar) ELSE '' END
|
|
1326
|
+
FROM ${source.from}
|
|
1327
|
+
WHERE e."$part_date" BETWEEN ${sqlString(shiftDate2(dates.start_time, -1))} AND ${sqlString(shiftDate2(dates.end_time, 1))}
|
|
1328
|
+
AND ((e."$part_event" = 'te_experiment_exposure' AND CAST(e.experiment_id AS varchar) = ${sqlString(experiment_id)})
|
|
1329
|
+
OR (e.demo_run_id = ${sqlString(runId)} AND e.plg_sample_id = ${sqlString(receipt.sample_id)}
|
|
1330
|
+
AND e.item_id = ${sqlString(receipt.item_id)}
|
|
1331
|
+
AND (e."$part_event" = 'demo_coupon_claim'
|
|
1332
|
+
OR (e."$part_event" = 'payment_success' AND e.currency = ${sqlString(receipt.currency)}))))`;
|
|
1333
|
+
const rows = await call("analysis.adhoc.run", {
|
|
1334
|
+
project_id: demo_project_id,
|
|
1335
|
+
model_type: "sql",
|
|
1336
|
+
definition: { sql },
|
|
1337
|
+
use_cache: false
|
|
1338
|
+
});
|
|
1339
|
+
if (rows?.has_more !== false || !Array.isArray(rows.rows)) {
|
|
1340
|
+
throw new Error("The Demo event query did not return a complete result.");
|
|
1341
|
+
}
|
|
1342
|
+
const found = new Set(rows.rows.map(([event, account, group]) => key(event, group, account)));
|
|
1343
|
+
if (found.size !== expected.size || [...expected].some((event) => !found.has(event))) return progress;
|
|
1344
|
+
return writeProgress(deps, host, "complete", { journey_id, run_id: runId, demo_project_id, experiment_id });
|
|
1345
|
+
}
|
|
318
1346
|
|
|
319
1347
|
// src/core/installation.ts
|
|
320
1348
|
import fs7 from "fs";
|
|
321
|
-
import
|
|
322
|
-
import
|
|
1349
|
+
import path8 from "path";
|
|
1350
|
+
import crypto4 from "crypto";
|
|
323
1351
|
|
|
324
1352
|
// src/core/skills-install.ts
|
|
325
1353
|
import fs2 from "fs";
|
|
326
1354
|
import os from "os";
|
|
327
|
-
import
|
|
1355
|
+
import path3 from "path";
|
|
328
1356
|
import { parseDocument } from "yaml";
|
|
329
1357
|
var ON_DEMAND_SKILLS = /* @__PURE__ */ new Set(["ae-onboarding"]);
|
|
330
1358
|
function readInstallableSkills(directory, select) {
|
|
331
1359
|
return readBundledSkills(directory, (name) => !ON_DEMAND_SKILLS.has(name) && (!select || select(name)));
|
|
332
1360
|
}
|
|
333
1361
|
function globalSkillsDirectory() {
|
|
334
|
-
return
|
|
1362
|
+
return path3.join(os.homedir(), ".agents", "skills");
|
|
335
1363
|
}
|
|
336
1364
|
function skillName(content) {
|
|
337
1365
|
const frontmatter = content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
|
|
@@ -343,12 +1371,12 @@ function skillName(content) {
|
|
|
343
1371
|
return data.name;
|
|
344
1372
|
}
|
|
345
1373
|
function readFiles(root, prefix = "", files = /* @__PURE__ */ new Map()) {
|
|
346
|
-
for (const entry of fs2.readdirSync(
|
|
1374
|
+
for (const entry of fs2.readdirSync(path3.join(root, prefix), { withFileTypes: true })) {
|
|
347
1375
|
if (entry.name.startsWith(".") || ["metadata.json", "__pycache__", "__pypackages__"].includes(entry.name)) continue;
|
|
348
|
-
const relative =
|
|
1376
|
+
const relative = path3.join(prefix, entry.name);
|
|
349
1377
|
if (entry.isSymbolicLink()) throw new Error("Bundled Skills must contain regular files.");
|
|
350
1378
|
if (entry.isDirectory()) readFiles(root, relative, files);
|
|
351
|
-
else if (entry.isFile()) files.set(relative, fs2.readFileSync(
|
|
1379
|
+
else if (entry.isFile()) files.set(relative, fs2.readFileSync(path3.join(root, relative)));
|
|
352
1380
|
}
|
|
353
1381
|
return files;
|
|
354
1382
|
}
|
|
@@ -359,14 +1387,14 @@ function readBundledSkills(directory, select) {
|
|
|
359
1387
|
try {
|
|
360
1388
|
let selectedName;
|
|
361
1389
|
if (select) {
|
|
362
|
-
const header =
|
|
1390
|
+
const header = path3.join(directory, entry.name, "SKILL.md");
|
|
363
1391
|
if (!fs2.lstatSync(header).isFile()) throw new Error("Bundled Skill metadata must be a regular file.");
|
|
364
1392
|
selectedName = skillName(fs2.readFileSync(header, "utf8"));
|
|
365
1393
|
if (names.has(selectedName)) throw new Error("Duplicate bundled Skill name.");
|
|
366
1394
|
names.add(selectedName);
|
|
367
1395
|
if (!select(selectedName)) return [];
|
|
368
1396
|
}
|
|
369
|
-
const files = readFiles(
|
|
1397
|
+
const files = readFiles(path3.join(directory, entry.name));
|
|
370
1398
|
const name = skillName(files.get("SKILL.md").toString("utf8"));
|
|
371
1399
|
if (selectedName !== void 0 && selectedName !== name) throw new Error("Bundled Skill metadata changed.");
|
|
372
1400
|
return [{ name, files }];
|
|
@@ -384,12 +1412,12 @@ function verifyGlobalSkills(skills, directory) {
|
|
|
384
1412
|
return skills.flatMap((skill) => {
|
|
385
1413
|
let reason = "";
|
|
386
1414
|
try {
|
|
387
|
-
const target =
|
|
388
|
-
if (skillName(fs2.readFileSync(
|
|
1415
|
+
const target = path3.join(directory, skill.name);
|
|
1416
|
+
if (skillName(fs2.readFileSync(path3.join(target, "SKILL.md"), "utf8")) !== skill.name) {
|
|
389
1417
|
reason = "Installed Skill name does not match the bundled Skill.";
|
|
390
1418
|
} else {
|
|
391
1419
|
for (const [file, expected] of skill.files) {
|
|
392
|
-
if (!fs2.readFileSync(
|
|
1420
|
+
if (!fs2.readFileSync(path3.join(target, file)).equals(expected)) {
|
|
393
1421
|
reason = "Installed files do not match the CLI package version.";
|
|
394
1422
|
break;
|
|
395
1423
|
}
|
|
@@ -402,81 +1430,6 @@ function verifyGlobalSkills(skills, directory) {
|
|
|
402
1430
|
});
|
|
403
1431
|
}
|
|
404
1432
|
|
|
405
|
-
// src/core/onboarding/contracts.ts
|
|
406
|
-
var DEMO_CONTEXT = "project.plg_demo.context";
|
|
407
|
-
var DEMO_ENSURE = "project.plg_demo.ensure";
|
|
408
|
-
var DEMO_STATUS = "project.plg_demo.status";
|
|
409
|
-
var RUN_BUDGET_MS = 45e3;
|
|
410
|
-
var NETWORK_BUDGET_MS = 35e3;
|
|
411
|
-
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
412
|
-
var DEMO_SAMPLE_IDS = ["star-island", "season-pass"];
|
|
413
|
-
var CHECKOUT_RECOVERY = "checkout-recovery";
|
|
414
|
-
function onboardingGrowthScenario(value) {
|
|
415
|
-
if (value === void 0 || value === "item-coupon") return "item-coupon";
|
|
416
|
-
if (value === CHECKOUT_RECOVERY) return CHECKOUT_RECOVERY;
|
|
417
|
-
throw new Error("Use --scenario item-coupon or checkout-recovery.");
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
// src/core/website-entry.ts
|
|
421
|
-
var LOGIN_PATHS = { jp: "/jp/experience-login/", kr: "/kr/experience-login/", us: "/en/experience-login/", cn: "/experience-login/" };
|
|
422
|
-
var WEBSITE_MARKETS = Object.keys(LOGIN_PATHS);
|
|
423
|
-
var PRODUCTION_ISSUER = "https://thinkingai.io";
|
|
424
|
-
var PRODUCTION_BROWSER_ORIGIN = "https://www.thinkingai.io";
|
|
425
|
-
var CHINA_PRODUCTION_ORIGIN = "https://www.thinkingai.cn";
|
|
426
|
-
var UNSUPPORTED_MARKET = "Website onboarding is available in China, Japan, South Korea, and the United States. Use --region cn, jp, kr, or us.";
|
|
427
|
-
function isWebsiteMarket(market) {
|
|
428
|
-
return Object.hasOwn(LOGIN_PATHS, market);
|
|
429
|
-
}
|
|
430
|
-
function websiteEnvironment(value, env = process.env) {
|
|
431
|
-
const selected = value ?? env.AE_CLI_WEBSITE_ENV ?? "production";
|
|
432
|
-
if (selected !== "production") throw new Error("Website onboarding supports only the production environment.");
|
|
433
|
-
return "production";
|
|
434
|
-
}
|
|
435
|
-
function websiteOrigin(market, environment) {
|
|
436
|
-
websiteEnvironment(environment, {});
|
|
437
|
-
if (!isWebsiteMarket(market)) throw new Error(UNSUPPORTED_MARKET);
|
|
438
|
-
return market === "cn" ? CHINA_PRODUCTION_ORIGIN : PRODUCTION_ISSUER;
|
|
439
|
-
}
|
|
440
|
-
function isProductionWebsiteOrigin(origin) {
|
|
441
|
-
return origin === PRODUCTION_ISSUER || origin === PRODUCTION_BROWSER_ORIGIN || origin === CHINA_PRODUCTION_ORIGIN;
|
|
442
|
-
}
|
|
443
|
-
function environmentForWebsiteOrigin(origin) {
|
|
444
|
-
if (isProductionWebsiteOrigin(origin)) return "production";
|
|
445
|
-
throw new Error("Untrusted onboarding website.");
|
|
446
|
-
}
|
|
447
|
-
function cliEntrySource(source, env = process.env) {
|
|
448
|
-
const selected = source ?? (UUID_PATTERN.test(env.CODEX_THREAD_ID ?? "") ? "codex" : "other");
|
|
449
|
-
if (!["codex", "cursor", "claude-code", "other"].includes(selected)) throw new Error("Unsupported local AI tool source.");
|
|
450
|
-
return selected;
|
|
451
|
-
}
|
|
452
|
-
function cliToolReference(source, env = process.env) {
|
|
453
|
-
return source === "codex" && UUID_PATTERN.test(env.CODEX_THREAD_ID ?? "") ? env.CODEX_THREAD_ID : void 0;
|
|
454
|
-
}
|
|
455
|
-
function withCliEntryContext(value, source, market, toolReference) {
|
|
456
|
-
const url = new URL(value);
|
|
457
|
-
if (url.protocol !== "https:" || url.username || url.password) throw new Error("Untrusted website continuation URL.");
|
|
458
|
-
if ([...url.searchParams.keys()].some((key) => /^(device_code|poll_token|access_token|refresh_token|cli[_-]token|token)$/i.test(key))) {
|
|
459
|
-
throw new Error("The website returned a private credential in its public continuation URL.");
|
|
460
|
-
}
|
|
461
|
-
const references = url.searchParams.getAll("tool_reference");
|
|
462
|
-
if (references.length > 1 || references.some((reference) => !UUID_PATTERN.test(reference))) throw new Error("Invalid AI tool continuation reference.");
|
|
463
|
-
url.searchParams.set("entry", "cli");
|
|
464
|
-
url.searchParams.set("source", cliEntrySource(source));
|
|
465
|
-
if (market && !url.searchParams.has("market")) url.searchParams.set("market", market);
|
|
466
|
-
if (toolReference) {
|
|
467
|
-
if (source !== "codex" || !UUID_PATTERN.test(toolReference)) throw new Error("Invalid AI tool continuation reference.");
|
|
468
|
-
if (references.length && references[0] !== toolReference) throw new Error("The website returned a mismatched AI tool continuation reference.");
|
|
469
|
-
if (!url.searchParams.has("tool_reference")) url.searchParams.set("tool_reference", toolReference);
|
|
470
|
-
}
|
|
471
|
-
return url.toString();
|
|
472
|
-
}
|
|
473
|
-
function websiteLoginUrl(market, environment, source, toolReference) {
|
|
474
|
-
websiteEnvironment(environment, {});
|
|
475
|
-
if (!isWebsiteMarket(market)) throw new Error(UNSUPPORTED_MARKET);
|
|
476
|
-
const origin = market === "cn" ? CHINA_PRODUCTION_ORIGIN : PRODUCTION_BROWSER_ORIGIN;
|
|
477
|
-
return withCliEntryContext(`${origin}${LOGIN_PATHS[market]}`, source, market, toolReference);
|
|
478
|
-
}
|
|
479
|
-
|
|
480
1433
|
// src/core/host-guidance.ts
|
|
481
1434
|
function normalizeRegistrationLanguage(value) {
|
|
482
1435
|
const language = value.trim().toLowerCase().split(/[_.:@-]/)[0];
|
|
@@ -488,6 +1441,9 @@ function normalizeRegistrationLanguage(value) {
|
|
|
488
1441
|
function localRegistrationLanguage(env = process.env) {
|
|
489
1442
|
return normalizeRegistrationLanguage(env.AE_LANG || env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE || "");
|
|
490
1443
|
}
|
|
1444
|
+
function onboardingDeviceMarket(env = process.env) {
|
|
1445
|
+
return localRegistrationLanguage(env) === "zh-CN" ? "cn" : "us";
|
|
1446
|
+
}
|
|
491
1447
|
function registrationLanguage(language, env = process.env) {
|
|
492
1448
|
return (language ? normalizeRegistrationLanguage(language) : localRegistrationLanguage(env)) ?? "en-US";
|
|
493
1449
|
}
|
|
@@ -522,9 +1478,9 @@ function missingAeHostGuidance() {
|
|
|
522
1478
|
}
|
|
523
1479
|
|
|
524
1480
|
// src/core/business-config.ts
|
|
525
|
-
import
|
|
1481
|
+
import crypto3 from "crypto";
|
|
526
1482
|
import fs6 from "fs";
|
|
527
|
-
import
|
|
1483
|
+
import path7 from "path";
|
|
528
1484
|
|
|
529
1485
|
// src/core/skill-businesses.json
|
|
530
1486
|
var skill_businesses_default = {
|
|
@@ -709,20 +1665,20 @@ function canManageGlobalSkills() {
|
|
|
709
1665
|
}
|
|
710
1666
|
|
|
711
1667
|
// src/core/business-skill-refresh.ts
|
|
712
|
-
import
|
|
1668
|
+
import crypto2 from "crypto";
|
|
713
1669
|
import fs5 from "fs";
|
|
714
|
-
import
|
|
1670
|
+
import path6 from "path";
|
|
715
1671
|
|
|
716
1672
|
// src/core/business-skill-sync.ts
|
|
717
1673
|
import fs4 from "fs";
|
|
718
1674
|
import os3 from "os";
|
|
719
|
-
import
|
|
1675
|
+
import path5 from "path";
|
|
720
1676
|
import { createHash as createHash2, randomUUID } from "crypto";
|
|
721
1677
|
|
|
722
1678
|
// src/core/skills-tool.ts
|
|
723
1679
|
import fs3 from "fs";
|
|
724
1680
|
import os2 from "os";
|
|
725
|
-
import
|
|
1681
|
+
import path4 from "path";
|
|
726
1682
|
import { createHash } from "crypto";
|
|
727
1683
|
import { createRequire, isBuiltin } from "module";
|
|
728
1684
|
import { pathToFileURL } from "url";
|
|
@@ -748,25 +1704,25 @@ function realSkillPath(file) {
|
|
|
748
1704
|
return fs3.realpathSync(file);
|
|
749
1705
|
} catch (error) {
|
|
750
1706
|
if (error.code !== "ENOENT") throw error;
|
|
751
|
-
const parent =
|
|
1707
|
+
const parent = path4.dirname(file);
|
|
752
1708
|
if (parent === file) throw error;
|
|
753
|
-
return
|
|
1709
|
+
return path4.join(realSkillPath(parent), path4.basename(file));
|
|
754
1710
|
}
|
|
755
1711
|
}
|
|
756
1712
|
function skillPathProblem(targetDirectory, skill, sourceRoot) {
|
|
757
1713
|
try {
|
|
758
|
-
const target = realSkillPath(
|
|
759
|
-
const source = realSkillPath(
|
|
760
|
-
const overlaps = (a, b) => a === b || a.startsWith(b +
|
|
1714
|
+
const target = realSkillPath(path4.resolve(targetDirectory, skill));
|
|
1715
|
+
const source = realSkillPath(path4.resolve(sourceRoot));
|
|
1716
|
+
const overlaps = (a, b) => a === b || a.startsWith(b + path4.sep);
|
|
761
1717
|
if (overlaps(target, source) || overlaps(source, target)) return "package_source_overlap";
|
|
762
|
-
let parent =
|
|
1718
|
+
let parent = path4.resolve(targetDirectory);
|
|
763
1719
|
while (true) {
|
|
764
1720
|
try {
|
|
765
1721
|
if (fs3.lstatSync(parent).isSymbolicLink()) return "copy_parent_linked";
|
|
766
1722
|
} catch (error) {
|
|
767
1723
|
if (error.code !== "ENOENT") throw error;
|
|
768
1724
|
}
|
|
769
|
-
const next =
|
|
1725
|
+
const next = path4.dirname(parent);
|
|
770
1726
|
if (next === parent) return null;
|
|
771
1727
|
parent = next;
|
|
772
1728
|
}
|
|
@@ -783,13 +1739,13 @@ function skillCopyHash(directory, source = false) {
|
|
|
783
1739
|
}
|
|
784
1740
|
const hash = createHash("sha256");
|
|
785
1741
|
const visit = (relative) => {
|
|
786
|
-
for (const name of fs3.readdirSync(
|
|
1742
|
+
for (const name of fs3.readdirSync(path4.join(directory, relative)).sort()) {
|
|
787
1743
|
if (name === ".DS_Store") continue;
|
|
788
|
-
const child =
|
|
789
|
-
const absolute =
|
|
1744
|
+
const child = path4.join(relative, name);
|
|
1745
|
+
const absolute = path4.join(directory, child);
|
|
790
1746
|
const stat = fs3.lstatSync(absolute);
|
|
791
1747
|
if (source && (name === "metadata.json" || stat.isDirectory() && [".git", "__pycache__", "__pypackages__"].includes(name))) continue;
|
|
792
|
-
const normalized = child.split(
|
|
1748
|
+
const normalized = child.split(path4.sep).join("/");
|
|
793
1749
|
if (stat.isSymbolicLink()) throw new Error("Symbolic links are not managed Skill copies.");
|
|
794
1750
|
if (stat.isDirectory()) {
|
|
795
1751
|
hash.update(`directory:${normalized}\0`);
|
|
@@ -853,7 +1809,7 @@ function adaptedToolSource(source, entry) {
|
|
|
853
1809
|
);
|
|
854
1810
|
source = replaceOnce(source, "main().finally(() => flushTelemetry().then(() => process.exit(0)));", "");
|
|
855
1811
|
const require2 = createRequire(entry);
|
|
856
|
-
const resolveImport = (specifier) => isBuiltin(specifier) ? specifier : pathToFileURL(specifier.startsWith(".") ?
|
|
1812
|
+
const resolveImport = (specifier) => isBuiltin(specifier) ? specifier : pathToFileURL(specifier.startsWith(".") ? path4.resolve(path4.dirname(entry), specifier) : require2.resolve(specifier)).href;
|
|
857
1813
|
source = source.replace(
|
|
858
1814
|
/\bfrom (['"])([^'"]+)\1/g,
|
|
859
1815
|
(_match, quote, specifier) => `from ${quote}${resolveImport(specifier)}${quote}`
|
|
@@ -1063,21 +2019,21 @@ catch { process.stdout.write(JSON.stringify({ ok: false })); process.exitCode =
|
|
|
1063
2019
|
`;
|
|
1064
2020
|
function createPinnedSkillsTool(options = {}) {
|
|
1065
2021
|
const require2 = createRequire(import.meta.url);
|
|
1066
|
-
const packageFile = options.entry ?
|
|
1067
|
-
const entry = options.entry ??
|
|
2022
|
+
const packageFile = options.entry ? path4.join(path4.dirname(options.entry), "..", "package.json") : require2.resolve("skills/package.json");
|
|
2023
|
+
const entry = options.entry ?? path4.join(path4.dirname(packageFile), "dist", "cli.mjs");
|
|
1068
2024
|
const metadata = JSON.parse(fs3.readFileSync(packageFile, "utf8"));
|
|
1069
2025
|
const source = fs3.readFileSync(entry, "utf8");
|
|
1070
2026
|
if (metadata.version !== MANAGED_SKILLS_TOOL_VERSION || createHash("sha256").update(source).digest("hex") !== TOOL_SOURCE_SHA256) {
|
|
1071
2027
|
throw new Error("Managed Skill synchronization requires the verified skills@1.5.12 package.");
|
|
1072
2028
|
}
|
|
1073
2029
|
const script = adaptedToolSource(source, entry);
|
|
1074
|
-
const run = (
|
|
1075
|
-
const directory = fs3.mkdtempSync(
|
|
1076
|
-
const worker =
|
|
2030
|
+
const run = (request2) => {
|
|
2031
|
+
const directory = fs3.mkdtempSync(path4.join(os2.tmpdir(), "ae-cli-skills-tool-"));
|
|
2032
|
+
const worker = path4.join(directory, "adapter.mjs");
|
|
1077
2033
|
try {
|
|
1078
2034
|
fs3.writeFileSync(worker, script, { mode: 384 });
|
|
1079
2035
|
const result2 = spawn2.sync(process.execPath, [worker], {
|
|
1080
|
-
input: JSON.stringify(
|
|
2036
|
+
input: JSON.stringify(request2),
|
|
1081
2037
|
encoding: "utf8",
|
|
1082
2038
|
maxBuffer: 8 * 1024 * 1024,
|
|
1083
2039
|
timeout: options.timeoutMs ?? 12e4,
|
|
@@ -1109,17 +2065,17 @@ var POLICY_HASH = createHash2("sha256").update(JSON.stringify({ removal_policy:
|
|
|
1109
2065
|
function historicalCliSkills(options) {
|
|
1110
2066
|
const env = options.env ?? process.env;
|
|
1111
2067
|
const home = env.HOME || env.USERPROFILE || os3.homedir();
|
|
1112
|
-
const file = env.XDG_STATE_HOME ?
|
|
2068
|
+
const file = env.XDG_STATE_HOME ? path5.join(env.XDG_STATE_HOME, "skills", ".skill-lock.json") : path5.join(home, ".agents", ".skill-lock.json");
|
|
1113
2069
|
const names = /* @__PURE__ */ new Set();
|
|
1114
2070
|
let content = "";
|
|
1115
2071
|
const isCliSource = (value, type) => {
|
|
1116
2072
|
if (typeof value !== "string") return false;
|
|
1117
|
-
if (type === "local" &&
|
|
1118
|
-
const source2 =
|
|
1119
|
-
if (source2 ===
|
|
1120
|
-
if (
|
|
2073
|
+
if (type === "local" && path5.isAbsolute(value)) {
|
|
2074
|
+
const source2 = path5.resolve(value);
|
|
2075
|
+
if (source2 === path5.resolve(options.skillsDirectory)) return true;
|
|
2076
|
+
if (path5.basename(source2) !== "skills") return false;
|
|
1121
2077
|
try {
|
|
1122
|
-
const pkg = JSON.parse(fs4.readFileSync(
|
|
2078
|
+
const pkg = JSON.parse(fs4.readFileSync(path5.join(source2, "..", "package.json"), "utf8"));
|
|
1123
2079
|
return ["@tant/ae-cli", "@thinkingai/ae-cli"].includes(pkg.name) && typeof pkg.bin?.["ae-cli"] === "string";
|
|
1124
2080
|
} catch {
|
|
1125
2081
|
return false;
|
|
@@ -1180,7 +2136,7 @@ function reserveBusinessSkillContext(options) {
|
|
|
1180
2136
|
const directory = options.stateDirectory ?? getConfigDir();
|
|
1181
2137
|
fs4.mkdirSync(directory, { recursive: true, mode: 448 });
|
|
1182
2138
|
const generation = randomUUID();
|
|
1183
|
-
writeJson(
|
|
2139
|
+
writeJson(path5.join(directory, CONTEXT_FILE), { ...contextIdentity(options), generation });
|
|
1184
2140
|
return generation;
|
|
1185
2141
|
}
|
|
1186
2142
|
function currentContext(options, file, generation) {
|
|
@@ -1194,7 +2150,7 @@ function currentContext(options, file, generation) {
|
|
|
1194
2150
|
}
|
|
1195
2151
|
}
|
|
1196
2152
|
function isBusinessSkillContextCurrent(options) {
|
|
1197
|
-
return currentContext(options,
|
|
2153
|
+
return currentContext(options, path5.join(options.stateDirectory ?? getConfigDir(), CONTEXT_FILE), options.generation);
|
|
1198
2154
|
}
|
|
1199
2155
|
function takeLock(file) {
|
|
1200
2156
|
const owner = randomUUID();
|
|
@@ -1210,7 +2166,7 @@ function takeLock(file) {
|
|
|
1210
2166
|
};
|
|
1211
2167
|
try {
|
|
1212
2168
|
fs4.chmodSync(candidate, 448);
|
|
1213
|
-
fs4.writeFileSync(
|
|
2169
|
+
fs4.writeFileSync(path5.join(candidate, ownerName), JSON.stringify({ pid: process.pid, owner }), { mode: 384 });
|
|
1214
2170
|
for (let attempt = 0; attempt < 4; attempt++) {
|
|
1215
2171
|
try {
|
|
1216
2172
|
fs4.renameSync(candidate, file);
|
|
@@ -1220,7 +2176,7 @@ function takeLock(file) {
|
|
|
1220
2176
|
}
|
|
1221
2177
|
return () => {
|
|
1222
2178
|
try {
|
|
1223
|
-
fs4.unlinkSync(
|
|
2179
|
+
fs4.unlinkSync(path5.join(file, ownerName));
|
|
1224
2180
|
} catch {
|
|
1225
2181
|
}
|
|
1226
2182
|
try {
|
|
@@ -1265,7 +2221,7 @@ function takeLock(file) {
|
|
|
1265
2221
|
}
|
|
1266
2222
|
for (const name of names) {
|
|
1267
2223
|
try {
|
|
1268
|
-
fs4.unlinkSync(
|
|
2224
|
+
fs4.unlinkSync(path5.join(file, name));
|
|
1269
2225
|
} catch (cause) {
|
|
1270
2226
|
if (cause.code !== "ENOENT") throw cause;
|
|
1271
2227
|
}
|
|
@@ -1294,12 +2250,12 @@ function readLedger(file) {
|
|
|
1294
2250
|
throw new Error("Managed Skill ledger has an unsupported format.");
|
|
1295
2251
|
}
|
|
1296
2252
|
for (const [filePath, copy] of Object.entries(value.copies)) {
|
|
1297
|
-
if (!
|
|
2253
|
+
if (!path5.isAbsolute(filePath) || !copy || typeof copy.skill !== "string" || typeof copy.agent !== "string" || !/^[a-f0-9]{64}$/.test(copy.hash) || typeof copy.package_version !== "string") throw new Error("Managed Skill ledger has an invalid copy.");
|
|
1298
2254
|
}
|
|
1299
2255
|
return value;
|
|
1300
2256
|
}
|
|
1301
2257
|
function result(skill, target, reason) {
|
|
1302
|
-
return { skill, agent: target.agent, path:
|
|
2258
|
+
return { skill, agent: target.agent, path: path5.join(target.directory, skill), ...reason ? { reason } : {} };
|
|
1303
2259
|
}
|
|
1304
2260
|
function directInstallerLink(file, target, text) {
|
|
1305
2261
|
if (typeof text !== "string") return false;
|
|
@@ -1307,14 +2263,14 @@ function directInstallerLink(file, target, text) {
|
|
|
1307
2263
|
if (process.platform === "win32") {
|
|
1308
2264
|
if (value.toUpperCase().startsWith("\\\\?\\UNC\\")) value = "\\\\" + value.slice(8);
|
|
1309
2265
|
else if (value.startsWith("\\\\?\\") || value.startsWith("\\??\\")) value = value.slice(4);
|
|
1310
|
-
return [target,
|
|
2266
|
+
return [target, path5.relative(path5.dirname(file), target)].some((expected) => value.toLowerCase() === expected.toLowerCase());
|
|
1311
2267
|
}
|
|
1312
|
-
return value === target || value ===
|
|
2268
|
+
return value === target || value === path5.relative(path5.dirname(file), target);
|
|
1313
2269
|
}
|
|
1314
2270
|
function legacySkillLink(file, skill, sourceRoot, sourceHash, targets, ledger, removing = false) {
|
|
1315
2271
|
const canonical = targets.find((target2) => target2.agent === "universal");
|
|
1316
2272
|
if (!canonical) return;
|
|
1317
|
-
const target =
|
|
2273
|
+
const target = path5.join(canonical.directory, skill);
|
|
1318
2274
|
const managed = ledger.copies[target];
|
|
1319
2275
|
if (!managed || managed.skill !== skill || managed.agent !== canonical.agent || !removing && managed.hash !== sourceHash || skillPathProblem(canonical.directory, skill, sourceRoot)) return;
|
|
1320
2276
|
try {
|
|
@@ -1338,7 +2294,7 @@ function syncBusinessSkills(options) {
|
|
|
1338
2294
|
managed_count: 0
|
|
1339
2295
|
};
|
|
1340
2296
|
const directory = options.stateDirectory ?? getConfigDir();
|
|
1341
|
-
const contextFile =
|
|
2297
|
+
const contextFile = path5.join(directory, CONTEXT_FILE);
|
|
1342
2298
|
let unlock = null;
|
|
1343
2299
|
try {
|
|
1344
2300
|
if (options.isCurrentContext && !options.isCurrentContext()) {
|
|
@@ -1351,7 +2307,7 @@ function syncBusinessSkills(options) {
|
|
|
1351
2307
|
report.status = "stale";
|
|
1352
2308
|
return report;
|
|
1353
2309
|
}
|
|
1354
|
-
unlock = takeLock(
|
|
2310
|
+
unlock = takeLock(path5.join(directory, LOCK_FILE));
|
|
1355
2311
|
if (!unlock) {
|
|
1356
2312
|
report.status = "busy";
|
|
1357
2313
|
return report;
|
|
@@ -1360,7 +2316,7 @@ function syncBusinessSkills(options) {
|
|
|
1360
2316
|
report.status = "stale";
|
|
1361
2317
|
return report;
|
|
1362
2318
|
}
|
|
1363
|
-
const ledgerFile =
|
|
2319
|
+
const ledgerFile = path5.join(directory, LEDGER_FILE);
|
|
1364
2320
|
const ledger = readLedger(ledgerFile);
|
|
1365
2321
|
const packageVersion = options.packageVersion ?? "unknown";
|
|
1366
2322
|
const history = historicalCliSkills(options);
|
|
@@ -1414,7 +2370,7 @@ function syncBusinessSkills(options) {
|
|
|
1414
2370
|
for (const name of skills) {
|
|
1415
2371
|
const state = getSkillBusinessState(name, options.businesses);
|
|
1416
2372
|
if (options.mode !== "adopt" && state === void 0) continue;
|
|
1417
|
-
const source =
|
|
2373
|
+
const source = path5.join(options.skillsDirectory, name);
|
|
1418
2374
|
const sourceHash = bundled.some((skill) => skill.name === name) ? skillCopyHash(source, true) : null;
|
|
1419
2375
|
if (!sourceHash && options.mode === "adopt") throw new Error("Complete package Skill source is missing.");
|
|
1420
2376
|
for (const target of targets) {
|
|
@@ -1439,7 +2395,7 @@ function syncBusinessSkills(options) {
|
|
|
1439
2395
|
}
|
|
1440
2396
|
const legacyLink2 = node.type === "symlink" ? legacySkillLink(item.path, name, options.skillsDirectory, sourceHash ?? "", targets, ledger, true) : void 0;
|
|
1441
2397
|
const canonical = targets.find((copy) => copy.agent === "universal");
|
|
1442
|
-
const historicalLink = node.type === "symlink" && canonical && directInstallerLink(item.path,
|
|
2398
|
+
const historicalLink = node.type === "symlink" && canonical && directInstallerLink(item.path, path5.join(canonical.directory, name), node.link);
|
|
1443
2399
|
const historicalCopy = history.names.has(name) && (target.agent === "universal" && node.type !== "symlink" || historicalLink);
|
|
1444
2400
|
if (!managed && (legacyLink2 || historicalCopy)) {
|
|
1445
2401
|
ledger.copies[item.path] = {
|
|
@@ -1587,7 +2543,7 @@ function beginBusinessSkillRefresh(host, token, enabled = true) {
|
|
|
1587
2543
|
}
|
|
1588
2544
|
};
|
|
1589
2545
|
if (!isCurrentContext()) return void 0;
|
|
1590
|
-
const identity = { host: normalized, tokenFingerprint:
|
|
2546
|
+
const identity = { host: normalized, tokenFingerprint: crypto2.createHash("sha256").update(token).digest("hex") };
|
|
1591
2547
|
return { ...identity, generation: reserveBusinessSkillContext(identity), isCurrentContext };
|
|
1592
2548
|
} catch {
|
|
1593
2549
|
return void 0;
|
|
@@ -1602,8 +2558,8 @@ function syncRefreshedBusinessSkills(refresh, businesses) {
|
|
|
1602
2558
|
if (!Object.keys(states).length) return;
|
|
1603
2559
|
try {
|
|
1604
2560
|
const pkg = getLocalCliPackageInfo();
|
|
1605
|
-
const options = { ...refresh, skillsDirectory:
|
|
1606
|
-
if (!fs5.existsSync(
|
|
2561
|
+
const options = { ...refresh, skillsDirectory: path6.join(pkg.root, "skills"), businesses: states, packageVersion: pkg.version };
|
|
2562
|
+
if (!fs5.existsSync(path6.join(getConfigDir(), "business-skills.json"))) {
|
|
1607
2563
|
const adoption = syncBusinessSkills({ ...options, mode: "adopt" });
|
|
1608
2564
|
if (["failed", "busy", "stale"].includes(adoption.status)) {
|
|
1609
2565
|
if (adoption.status !== "stale") process.stderr.write("[ae-cli] Skills could not be synchronized. Retry: ae-cli config refresh\n");
|
|
@@ -1623,10 +2579,10 @@ function syncRefreshedBusinessSkills(refresh, businesses) {
|
|
|
1623
2579
|
var BUSINESS_CONFIG_TTL_MS = 10 * 60 * 1e3;
|
|
1624
2580
|
var UNAVAILABLE_TTL_MS = 5 * 60 * 1e3;
|
|
1625
2581
|
function cachePath() {
|
|
1626
|
-
return
|
|
2582
|
+
return path7.join(getConfigDir(), "business-config.json");
|
|
1627
2583
|
}
|
|
1628
2584
|
function cacheKey(host, token) {
|
|
1629
|
-
return `${normalizeUrl(host)}#${
|
|
2585
|
+
return `${normalizeUrl(host)}#${crypto3.createHash("sha256").update(token).digest("hex")}`;
|
|
1630
2586
|
}
|
|
1631
2587
|
function readStore() {
|
|
1632
2588
|
try {
|
|
@@ -1640,9 +2596,9 @@ function remember(host, token, entry) {
|
|
|
1640
2596
|
const store = readStore();
|
|
1641
2597
|
store.entries[cacheKey(host, token)] = entry;
|
|
1642
2598
|
const target = cachePath();
|
|
1643
|
-
const temporary = `${target}.${process.pid}.${
|
|
2599
|
+
const temporary = `${target}.${process.pid}.${crypto3.randomBytes(6).toString("hex")}.tmp`;
|
|
1644
2600
|
try {
|
|
1645
|
-
fs6.mkdirSync(
|
|
2601
|
+
fs6.mkdirSync(path7.dirname(target), { recursive: true });
|
|
1646
2602
|
fs6.writeFileSync(temporary, JSON.stringify(store), { encoding: "utf8", mode: 384 });
|
|
1647
2603
|
fs6.renameSync(temporary, target);
|
|
1648
2604
|
fs6.chmodSync(target, 384);
|
|
@@ -1717,7 +2673,7 @@ async function readBusinessConfigForExecution(hostOverride, synchronizeSkills =
|
|
|
1717
2673
|
const token = peekCliToken(host);
|
|
1718
2674
|
if (!token) return {};
|
|
1719
2675
|
return await resolveBusinessConfig(host, token, async () => {
|
|
1720
|
-
const { fetchCliConfig: fetchCliConfig2 } = await import("./compat-check-
|
|
2676
|
+
const { fetchCliConfig: fetchCliConfig2 } = await import("./compat-check-AO3BFA3N.js");
|
|
1721
2677
|
return fetchCliConfig2(host, token);
|
|
1722
2678
|
}, Date.now(), synchronizeSkills);
|
|
1723
2679
|
} catch {
|
|
@@ -1731,6 +2687,14 @@ async function assertBusinessEnabled(business, hostOverride, synchronizeSkills =
|
|
|
1731
2687
|
}
|
|
1732
2688
|
|
|
1733
2689
|
// src/core/installation.ts
|
|
2690
|
+
var accountChoice = {
|
|
2691
|
+
step: "choose_account",
|
|
2692
|
+
question: "How would you like to connect to AE?",
|
|
2693
|
+
options: [
|
|
2694
|
+
{ value: "create_account", label: "Create an AE account" },
|
|
2695
|
+
{ value: "existing_account", label: "Sign in to my existing AE account" }
|
|
2696
|
+
]
|
|
2697
|
+
};
|
|
1734
2698
|
function distribution(packageName) {
|
|
1735
2699
|
if (packageName === "@thinkingai/ae-cli") return { registry: "https://registry.npmjs.org", repository: "ThinkingAIAgenticEngine/ae-cli" };
|
|
1736
2700
|
if (packageName === "@tant/ae-cli") return { registry: "https://npm.thinkingdata.cn:3443", repository: "http://10.27.249.150:8888/te-ai/te-cli.git" };
|
|
@@ -1740,6 +2704,9 @@ function newInstallationReport(packageName, version, dryRun = false) {
|
|
|
1740
2704
|
return {
|
|
1741
2705
|
ok: false,
|
|
1742
2706
|
dry_run: dryRun,
|
|
2707
|
+
// Keep the next interaction visible before detailed Skill synchronization output.
|
|
2708
|
+
next_action: void 0,
|
|
2709
|
+
interaction: void 0,
|
|
1743
2710
|
cli: { package: packageName, version, path: null, entrypoint: null, verified: false, action: "pending", warnings: [] },
|
|
1744
2711
|
skills: {
|
|
1745
2712
|
directory: globalSkillsDirectory(),
|
|
@@ -1765,7 +2732,7 @@ function failInstallation(report, stage, message, cause = "validation") {
|
|
|
1765
2732
|
function installPlan(packageName, version, root = "<npm-root>") {
|
|
1766
2733
|
const config = distribution(packageName);
|
|
1767
2734
|
const target = exactVersion(version);
|
|
1768
|
-
const executable =
|
|
2735
|
+
const executable = path8.join(root, packageName, "bin", "ae-cli.js");
|
|
1769
2736
|
return [
|
|
1770
2737
|
`npm install -g ${packageName}@${target} --registry=${config.registry}`,
|
|
1771
2738
|
`node ${JSON.stringify(executable)} install`
|
|
@@ -1774,7 +2741,7 @@ function installPlan(packageName, version, root = "<npm-root>") {
|
|
|
1774
2741
|
function currentSkillIdentity() {
|
|
1775
2742
|
const host = getActiveHost();
|
|
1776
2743
|
const token = host ? peekCliToken(host) : void 0;
|
|
1777
|
-
return { host, tokenFingerprint: token ?
|
|
2744
|
+
return { host, tokenFingerprint: token ? crypto4.createHash("sha256").update(token).digest("hex") : "" };
|
|
1778
2745
|
}
|
|
1779
2746
|
function skipGlobalSkillReason() {
|
|
1780
2747
|
try {
|
|
@@ -1785,7 +2752,7 @@ function skipGlobalSkillReason() {
|
|
|
1785
2752
|
}
|
|
1786
2753
|
function readPackage(root) {
|
|
1787
2754
|
try {
|
|
1788
|
-
return JSON.parse(fs7.readFileSync(
|
|
2755
|
+
return JSON.parse(fs7.readFileSync(path8.join(root, "package.json"), "utf8"));
|
|
1789
2756
|
} catch {
|
|
1790
2757
|
return null;
|
|
1791
2758
|
}
|
|
@@ -1798,13 +2765,13 @@ function linked(root) {
|
|
|
1798
2765
|
}
|
|
1799
2766
|
}
|
|
1800
2767
|
function cliBinBelongsToPackage(bin, packageRoot, platform) {
|
|
1801
|
-
const entry = fs7.realpathSync(
|
|
2768
|
+
const entry = fs7.realpathSync(path8.join(packageRoot, "bin", "ae-cli.js"));
|
|
1802
2769
|
if (platform !== "win32") return fs7.realpathSync(bin) === entry;
|
|
1803
2770
|
const shim = fs7.readFileSync(bin, "utf8");
|
|
1804
2771
|
const targets = [...shim.matchAll(/"%(?:dp0%|~dp0)[\\/]([^"\r\n]+)"/gi)];
|
|
1805
2772
|
return targets.some(([, relative]) => {
|
|
1806
2773
|
try {
|
|
1807
|
-
const target =
|
|
2774
|
+
const target = path8.resolve(path8.dirname(bin), relative.replace(/\\/g, path8.sep));
|
|
1808
2775
|
return fs7.realpathSync(target).toLowerCase() === entry.toLowerCase();
|
|
1809
2776
|
} catch {
|
|
1810
2777
|
return false;
|
|
@@ -1846,9 +2813,9 @@ function runInstallation(options = {}) {
|
|
|
1846
2813
|
const prefixResult = runner(npm, ["prefix", "-g"], 15e3);
|
|
1847
2814
|
const globalRoot = rootResult.stdout.trim();
|
|
1848
2815
|
const prefix = prefixResult.stdout.trim();
|
|
1849
|
-
if (!commandSucceeded(rootResult) || !commandSucceeded(prefixResult) || !
|
|
1850
|
-
const packageRoot =
|
|
1851
|
-
const bin = platform === "win32" ?
|
|
2816
|
+
if (!commandSucceeded(rootResult) || !commandSucceeded(prefixResult) || !path8.isAbsolute(globalRoot) || !path8.isAbsolute(prefix) || /[\r\n]/.test(globalRoot + prefix)) return failInstallation(report, stage, "Cannot resolve npm global root and prefix. Check npm configuration.");
|
|
2817
|
+
const packageRoot = path8.join(globalRoot, packageName);
|
|
2818
|
+
const bin = platform === "win32" ? path8.join(prefix, "ae-cli.cmd") : path8.join(prefix, "bin", "ae-cli");
|
|
1852
2819
|
report.cli.path = bin;
|
|
1853
2820
|
const env = options.env ?? process.env;
|
|
1854
2821
|
const installedBefore = readPackage(packageRoot);
|
|
@@ -1871,8 +2838,8 @@ function runInstallation(options = {}) {
|
|
|
1871
2838
|
};
|
|
1872
2839
|
const generation = reserveBusinessSkillContext({ ...identity, stateDirectory });
|
|
1873
2840
|
context = { ...identity, stateDirectory, generation, isCurrentContext };
|
|
1874
|
-
if (!fs7.existsSync(
|
|
1875
|
-
const previousSkills =
|
|
2841
|
+
if (!fs7.existsSync(path8.join(stateDirectory, "business-skills.json")) && installedBefore?.name === packageName) {
|
|
2842
|
+
const previousSkills = path8.join(packageRoot, "skills");
|
|
1876
2843
|
try {
|
|
1877
2844
|
readInstallableSkills(previousSkills);
|
|
1878
2845
|
syncSkills({ ...context, skillsDirectory: previousSkills, businesses: {}, mode: "adopt", packageVersion: installedBefore.version });
|
|
@@ -1901,12 +2868,12 @@ function runInstallation(options = {}) {
|
|
|
1901
2868
|
if (!cliBinBelongsToPackage(bin, packageRoot, platform)) return failInstallation(report, stage, "The global executable does not belong to the installed CLI package.");
|
|
1902
2869
|
const versionResult = runner(bin, ["--version"], 15e3);
|
|
1903
2870
|
if (!commandSucceeded(versionResult) || versionResult.stdout.trim() !== target) return failInstallation(report, stage, "ae-cli --version did not return the requested version. Refresh the shell command cache and check npm bin links.");
|
|
1904
|
-
report.cli.entrypoint = fs7.realpathSync(
|
|
2871
|
+
report.cli.entrypoint = fs7.realpathSync(path8.join(packageRoot, "bin", "ae-cli.js"));
|
|
1905
2872
|
report.cli.verified = true;
|
|
1906
2873
|
const pathKey = platform === "win32" ? Object.keys(env).find((key) => key.toLowerCase() === "path") : "PATH";
|
|
1907
|
-
const installedPathBin = (env[pathKey ?? "PATH"] ?? "").split(platform === "win32" ? ";" :
|
|
2874
|
+
const installedPathBin = (env[pathKey ?? "PATH"] ?? "").split(platform === "win32" ? ";" : path8.delimiter).filter(Boolean).map((dir) => path8.join(dir.replace(/^"(.*)"$/, "$1"), platform === "win32" ? "ae-cli.cmd" : "ae-cli")).find((file) => fs7.existsSync(file) && !file.includes(`${path8.sep}_npx${path8.sep}`));
|
|
1908
2875
|
if (!installedPathBin || fs7.realpathSync(installedPathBin) !== fs7.realpathSync(bin)) {
|
|
1909
|
-
report.cli.warnings.push(`Add ${
|
|
2876
|
+
report.cli.warnings.push(`Add ${path8.dirname(bin)} to the front of PATH and refresh the shell command cache. The absolute executable was verified.`);
|
|
1910
2877
|
report.next_steps.push(`Use the verified executable at ${bin}, or correct PATH before invoking ae-cli.`);
|
|
1911
2878
|
}
|
|
1912
2879
|
if (skipSkills) {
|
|
@@ -1915,7 +2882,7 @@ function runInstallation(options = {}) {
|
|
|
1915
2882
|
progress(`[ae-cli] [3/4] ${skipSkills}`);
|
|
1916
2883
|
} else if (context) {
|
|
1917
2884
|
stage = "skills_local";
|
|
1918
|
-
const skillsPath =
|
|
2885
|
+
const skillsPath = path8.join(packageRoot, "skills");
|
|
1919
2886
|
const skills = readInstallableSkills(skillsPath);
|
|
1920
2887
|
if (!isBusinessSkillContextCurrent(context)) {
|
|
1921
2888
|
return failInstallation(report, stage, "The active environment changed during CLI installation. Re-run install or update to synchronize its Skills.");
|
|
@@ -1973,33 +2940,45 @@ function runInstallation(options = {}) {
|
|
|
1973
2940
|
}
|
|
1974
2941
|
const localLanguage = localRegistrationLanguage(env);
|
|
1975
2942
|
const language = localLanguage ?? "en-US";
|
|
1976
|
-
const
|
|
2943
|
+
const deviceMarket = onboardingDeviceMarket(env);
|
|
1977
2944
|
if (guideAccountSetup) {
|
|
1978
2945
|
if (localLanguage) report.local_language = localLanguage;
|
|
1979
|
-
report.
|
|
1980
|
-
|
|
1981
|
-
|
|
2946
|
+
report.onboarding_market = deviceMarket;
|
|
2947
|
+
const onboardingSkillPath = path8.join(packageRoot, "skills", "ae-onboarding", "SKILL.md");
|
|
2948
|
+
if (fs7.existsSync(onboardingSkillPath)) report.onboarding_skill_path = onboardingSkillPath;
|
|
2949
|
+
if (report.auth.authenticated === true) {
|
|
2950
|
+
report.next_action = isOnboardingProgressHost(report.auth.host ?? void 0) ? "check_onboarding" : "continue_using_ae";
|
|
2951
|
+
} else if (report.auth.warnings.length > 0) report.next_action = "check_authentication";
|
|
1982
2952
|
else report.next_action = "choose_account";
|
|
1983
2953
|
}
|
|
1984
2954
|
if (report.auth.authenticated === true) {
|
|
1985
|
-
report.
|
|
2955
|
+
if (report.next_action === "check_onboarding") {
|
|
2956
|
+
report.next_steps.push("Check the signed-in account with ae-cli analysis onboarding progress --format json. Offer the current Demo only for not_started or in_progress. Continue the user\u2019s specific AE task first when one was requested.");
|
|
2957
|
+
} else {
|
|
2958
|
+
report.next_steps.push("You are signed in. Continue your AE task in this AI tool using the existing environment.");
|
|
2959
|
+
}
|
|
1986
2960
|
} else if (report.next_action === "check_authentication") {
|
|
1987
2961
|
const hostOption = report.auth.host ? ` --host ${report.auth.host}` : "";
|
|
1988
2962
|
report.next_steps.push(`Check the configured AE environment with ae-cli auth status${hostOption} --format json. If it still cannot be verified, confirm the intended environment before starting signup or login.`);
|
|
1989
2963
|
} else {
|
|
1990
2964
|
const chooseAccount = report.next_action === "choose_account";
|
|
1991
2965
|
if (chooseAccount) {
|
|
1992
|
-
report.
|
|
2966
|
+
report.interaction = accountChoice;
|
|
2967
|
+
report.next_steps.push(
|
|
2968
|
+
"After verifying a fresh install, when the user has left the account route open, offer \u201CCreate an AE account\u201D and \u201CSign in to my existing AE account\u201D in the user\u2019s language. In an AI Agent, show these options in the same turn using the native choice dialog, even for a request that only asks to install. Keep the turn open until the user chooses or dismisses the dialog. If the dialog is unavailable or fails, ask with the same options in chat. A supplied host only identifies the environment. Wait for the account choice before starting signup or device authorization. For an explicit existing-account login request, use the original AE environment."
|
|
2969
|
+
);
|
|
2970
|
+
report.next_steps.push("For an explicit onboarding or walkthrough that needs a new account, show \u201CCreate an AE account\u201D and \u201CLearn about AE\u201D using the localized labels from references/about-ae.md next to onboarding_skill_path. If they choose \u201CLearn about AE\u201D, show the localized introduction and available product resources from that reference. Offer \u201CCreate an AE account\u201D and wait for their choice.");
|
|
1993
2971
|
}
|
|
1994
2972
|
if (chooseAccount || !report.auth.host) {
|
|
1995
2973
|
const source = cliEntrySource(void 0, env);
|
|
1996
|
-
const registration = aeRegistrationUrl(language, env, source);
|
|
2974
|
+
const registration = aeRegistrationUrl(chooseAccount ? deviceMarket === "cn" ? "zh-CN" : "en-US" : language, env, source);
|
|
1997
2975
|
if (chooseAccount) {
|
|
1998
|
-
report.next_steps.push(`
|
|
2976
|
+
report.next_steps.push(`After the user confirms signup in the overseas test environment, run ae-cli analysis onboarding run --website-env test --region us --source ${source} --browser system --format json. Use jp or kr for the corresponding requested test market and keep the returned session_id.`);
|
|
2977
|
+
report.next_steps.push(`For a production market, when the user chooses \u201CCreate an AE account\u201D or directly asks to sign up, run ae-cli analysis onboarding run --region ${deviceMarket} --source ${source} --browser system --format json. Honor an explicitly requested market and pass --language for the display preference. The CLI opens the system default browser. If it cannot open the page, share the returned login_url for that browser. Read the returned skill_path and continue with its session_id after the user confirms sign-in. For manual signup outside the guided session, use ${registration}.`);
|
|
1999
2978
|
} else {
|
|
2000
2979
|
report.next_steps.push(`New or returning website users: for guided website verification, run ae-cli analysis onboarding run --language ${language} --source ${source} --browser system. For manual registration or sign-in, use ${registration} in the system default browser.`);
|
|
2001
2980
|
}
|
|
2002
|
-
report.next_steps.push(`
|
|
2981
|
+
if (chooseAccount) report.next_steps.push(`Chinese device locales, including Traditional Chinese, default to China. Other device locales default to the United States. The current default is ${deviceMarket}. Explicit --region cn|jp|kr|us still selects the requested market. Display language changes presentation only.`);
|
|
2003
2982
|
}
|
|
2004
2983
|
if (chooseAccount) report.next_steps.push("Existing AE users: confirm their original AE environment URL and use it for login. Ask for that URL if it is unknown.");
|
|
2005
2984
|
else if (!report.auth.host) report.next_steps.push("Existing AE users: use your original environment URL, or ask your administrator.");
|
|
@@ -2021,10 +3000,10 @@ var LOCK_STALE_MS = 10 * 60 * 1e3;
|
|
|
2021
3000
|
var SYNC_STATE_FILE = "version-sync.json";
|
|
2022
3001
|
var SYNC_LOCK_FILE = "version-sync.lock";
|
|
2023
3002
|
function syncStatePath() {
|
|
2024
|
-
return
|
|
3003
|
+
return path9.join(getConfigDir(), SYNC_STATE_FILE);
|
|
2025
3004
|
}
|
|
2026
3005
|
function syncLockPath() {
|
|
2027
|
-
return
|
|
3006
|
+
return path9.join(getConfigDir(), SYNC_LOCK_FILE);
|
|
2028
3007
|
}
|
|
2029
3008
|
function readSyncStore() {
|
|
2030
3009
|
try {
|
|
@@ -2231,16 +3210,16 @@ function autoSyncDirection(current, expected) {
|
|
|
2231
3210
|
}
|
|
2232
3211
|
|
|
2233
3212
|
// src/core/feature-config.ts
|
|
2234
|
-
import
|
|
3213
|
+
import crypto5 from "crypto";
|
|
2235
3214
|
import fs9 from "fs";
|
|
2236
|
-
import
|
|
3215
|
+
import path10 from "path";
|
|
2237
3216
|
var FEATURE_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
2238
3217
|
var UNAVAILABLE_TTL_MS2 = 5 * 60 * 1e3;
|
|
2239
3218
|
function cachePath2() {
|
|
2240
|
-
return
|
|
3219
|
+
return path10.join(getConfigDir(), "feature-config.json");
|
|
2241
3220
|
}
|
|
2242
3221
|
function cacheKey2(host, token) {
|
|
2243
|
-
const fingerprint =
|
|
3222
|
+
const fingerprint = crypto5.createHash("sha256").update(token).digest("hex");
|
|
2244
3223
|
return `${normalizeUrl(host)}#${fingerprint}`;
|
|
2245
3224
|
}
|
|
2246
3225
|
function readStore2() {
|
|
@@ -2253,9 +3232,9 @@ function readStore2() {
|
|
|
2253
3232
|
}
|
|
2254
3233
|
function writeStore(store) {
|
|
2255
3234
|
const target = cachePath2();
|
|
2256
|
-
const temp = `${target}.${process.pid}.${
|
|
3235
|
+
const temp = `${target}.${process.pid}.${crypto5.randomBytes(6).toString("hex")}.tmp`;
|
|
2257
3236
|
try {
|
|
2258
|
-
fs9.mkdirSync(
|
|
3237
|
+
fs9.mkdirSync(path10.dirname(target), { recursive: true });
|
|
2259
3238
|
fs9.writeFileSync(temp, JSON.stringify(store), { encoding: "utf8", mode: 384 });
|
|
2260
3239
|
fs9.renameSync(temp, target);
|
|
2261
3240
|
fs9.chmodSync(target, 384);
|
|
@@ -2308,7 +3287,7 @@ var NOTIFY_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
|
2308
3287
|
var FETCH_TIMEOUT_MS = 3e3;
|
|
2309
3288
|
var CLI_CONFIG_PATH = "/v1/ta/cli/config";
|
|
2310
3289
|
function cacheFilePath() {
|
|
2311
|
-
return
|
|
3290
|
+
return path11.join(getConfigDir(), "compat-check.json");
|
|
2312
3291
|
}
|
|
2313
3292
|
function readStore3() {
|
|
2314
3293
|
try {
|
|
@@ -2667,15 +3646,40 @@ export {
|
|
|
2667
3646
|
UUID_PATTERN,
|
|
2668
3647
|
DEMO_SAMPLE_IDS,
|
|
2669
3648
|
CHECKOUT_RECOVERY,
|
|
3649
|
+
OVERSEAS_TEST_PRODUCT_HOSTNAME,
|
|
3650
|
+
onboardingDemoCurrency,
|
|
2670
3651
|
onboardingGrowthScenario,
|
|
3652
|
+
replayReportDates,
|
|
3653
|
+
waitForExperimentSampleSize,
|
|
2671
3654
|
WEBSITE_MARKETS,
|
|
3655
|
+
OVERSEAS_TEST_MARKETS,
|
|
3656
|
+
OVERSEAS_TEST_WEBSITE_ORIGIN,
|
|
3657
|
+
isWebsiteMarket,
|
|
2672
3658
|
websiteEnvironment,
|
|
2673
3659
|
websiteOrigin,
|
|
2674
3660
|
isProductionWebsiteOrigin,
|
|
2675
|
-
environmentForWebsiteOrigin,
|
|
2676
3661
|
cliEntrySource,
|
|
2677
|
-
|
|
3662
|
+
bootstrapOrigin,
|
|
3663
|
+
trustedProductHost,
|
|
3664
|
+
createBootstrap,
|
|
3665
|
+
readBootstrap,
|
|
3666
|
+
claimBootstrapDevice,
|
|
3667
|
+
normalizeResourceUrlFields,
|
|
3668
|
+
normalizeResourceUrls,
|
|
3669
|
+
resolvePublicWebHost,
|
|
3670
|
+
onboardingDraftReviewInteraction,
|
|
3671
|
+
onboardingDemoOverview,
|
|
3672
|
+
onboardingInteraction,
|
|
3673
|
+
onboardingEvidenceLinks,
|
|
3674
|
+
onboardingExperimentUrl,
|
|
3675
|
+
readCheckoutRecoveryCohort,
|
|
3676
|
+
runOnboardingGrowth,
|
|
3677
|
+
isOnboardingProgressHost,
|
|
3678
|
+
writeProgress,
|
|
3679
|
+
readProgress,
|
|
3680
|
+
verifyAndCompleteProgress,
|
|
2678
3681
|
normalizeRegistrationLanguage,
|
|
3682
|
+
onboardingDeviceMarket,
|
|
2679
3683
|
registrationLanguage,
|
|
2680
3684
|
registrationMarket,
|
|
2681
3685
|
aeRegistrationUrl,
|