@posthog/wizard 2.14.3 → 2.16.0
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 +43 -1
- package/dist/{TextBlock-DEHERFec.js → TextBlock-DJVhBkr3.js} +4 -4
- package/dist/TextBlock-DJVhBkr3.js.map +1 -0
- package/dist/{add-mcp-server-to-clients-B48J7VVO.js → add-mcp-server-to-clients-9jQjc-CO.js} +5 -5
- package/dist/{add-mcp-server-to-clients-B48J7VVO.js.map → add-mcp-server-to-clients-9jQjc-CO.js.map} +1 -1
- package/dist/{agent-interface-cEdS_bNo.js → agent-interface-pBnqJL8P.js} +106 -21
- package/dist/agent-interface-pBnqJL8P.js.map +1 -0
- package/dist/{agent-runner-CK5r-zQF.js → agent-runner-H1FP6XTc.js} +12 -9
- package/dist/agent-runner-H1FP6XTc.js.map +1 -0
- package/dist/{analytics-DaDpDus8.js → analytics-DZaUgJte.js} +2 -2
- package/dist/{analytics-DaDpDus8.js.map → analytics-DZaUgJte.js.map} +1 -1
- package/dist/analytics-DqeW7XYt.js +2 -0
- package/dist/bin.js +965 -83
- package/dist/bin.js.map +1 -1
- package/dist/{debug-B_PK52GI.js → debug-B6rX6xye.js} +1 -1
- package/dist/{debug-BOogNcWX.js → debug-C4jRuzny.js} +57 -46
- package/dist/debug-C4jRuzny.js.map +1 -0
- package/dist/{defaults-DgKAzsD1.js → defaults-GbLPuHxj.js} +1 -1
- package/dist/{defaults-DgKAzsD1.js.map → defaults-GbLPuHxj.js.map} +1 -1
- package/dist/{detection-OCF8fpfp.js → detection-4eukp9HD.js} +3 -3
- package/dist/{detection-OCF8fpfp.js.map → detection-4eukp9HD.js.map} +1 -1
- package/dist/{env-api-key-D5G2PrXW.js → env-api-key-DU8uIEvo.js} +1 -1
- package/dist/{env-api-key-D5G2PrXW.js.map → env-api-key-DU8uIEvo.js.map} +1 -1
- package/dist/{file-utils-DPmgn9Vm.js → file-utils-DnTSiTJw.js} +1 -1
- package/dist/file-utils-DnTSiTJw.js.map +1 -0
- package/dist/mcp-prompt-streaming-DKiaymMt.js +200 -0
- package/dist/mcp-prompt-streaming-DKiaymMt.js.map +1 -0
- package/dist/package-json-Cttzi3C8.js +2 -0
- package/dist/package-json-v_g2YlN1.js +35 -0
- package/dist/package-json-v_g2YlN1.js.map +1 -0
- package/dist/{package-manager-CmMJAD-V.js → package-manager-DLt75bit.js} +2 -2
- package/dist/package-manager-DLt75bit.js.map +1 -0
- package/dist/posthog-7B92c2Ed.js +120 -0
- package/dist/posthog-7B92c2Ed.js.map +1 -0
- package/dist/{posthog-integration-By5930Gz.js → posthog-integration-CukaeYil.js} +13 -12
- package/dist/{posthog-integration-By5930Gz.js.map → posthog-integration-CukaeYil.js.map} +1 -1
- package/dist/{provisioning-BHa8VWaa.js → provisioning-C_ETLiZE.js} +3 -3
- package/dist/{provisioning-BHa8VWaa.js.map → provisioning-C_ETLiZE.js.map} +1 -1
- package/dist/provisioning-Ch6i8dRV.js +2 -0
- package/dist/{registry-DpROZPnl.js → registry-DqbwO5EL.js} +31 -31
- package/dist/registry-DqbwO5EL.js.map +1 -0
- package/dist/setup-utils-C5uZ9g60.js +2 -0
- package/dist/{setup-utils-Mzpk1vqG.js → setup-utils-DdAdxUTV.js} +170 -60
- package/dist/setup-utils-DdAdxUTV.js.map +1 -0
- package/dist/{slides-BtDXEXdn.js → slides-Dpj4j0w_.js} +580 -27
- package/dist/slides-Dpj4j0w_.js.map +1 -0
- package/dist/smoke-test-ci.sh +5 -2
- package/dist/smoke-test.sh +43 -0
- package/dist/{start-playground-zZL5y9id.js → start-playground-B40O4tye.js} +288 -6
- package/dist/start-playground-B40O4tye.js.map +1 -0
- package/dist/{start-tui-Cz7RZSn_.js → start-tui-CH_ZzQXx.js} +628 -26
- package/dist/start-tui-CH_ZzQXx.js.map +1 -0
- package/dist/{steps-C2XEzN79.js → steps-0d9XqvI6.js} +6 -6
- package/dist/{steps-C2XEzN79.js.map → steps-0d9XqvI6.js.map} +1 -1
- package/dist/task-stream-CoEsidgG.js +195 -0
- package/dist/task-stream-CoEsidgG.js.map +1 -0
- package/dist/{telemetry-BG2bOwCp.js → telemetry-jn2Daxl2.js} +2 -2
- package/dist/{telemetry-BG2bOwCp.js.map → telemetry-jn2Daxl2.js.map} +1 -1
- package/dist/{wizard-abort-BmT-F0Vr.js → wizard-abort-BjLIgu2s.js} +3 -3
- package/dist/{wizard-abort-BmT-F0Vr.js.map → wizard-abort-BjLIgu2s.js.map} +1 -1
- package/dist/{wizard-abort-CYW83OG5.js → wizard-abort-BlYGA1Jk.js} +1 -1
- package/dist/{wizard-session-CsI33S4_.js → wizard-session-Bi95IYca.js} +19 -2
- package/dist/wizard-session-Bi95IYca.js.map +1 -0
- package/dist/wizard-session-DPGTaJ4W.js +2 -0
- package/dist/wizard-ui-YdGFRyu_.js.map +1 -1
- package/package.json +3 -2
- package/dist/TextBlock-DEHERFec.js.map +0 -1
- package/dist/agent-interface-cEdS_bNo.js.map +0 -1
- package/dist/agent-runner-CK5r-zQF.js.map +0 -1
- package/dist/analytics-Bw8E-yhX.js +0 -2
- package/dist/craft-pre-release.sh +0 -10
- package/dist/debug-BOogNcWX.js.map +0 -1
- package/dist/file-BKbKreWF.js +0 -16
- package/dist/file-BKbKreWF.js.map +0 -1
- package/dist/file-utils-DPmgn9Vm.js.map +0 -1
- package/dist/package-json-DZpnf6vU.js +0 -23
- package/dist/package-json-DZpnf6vU.js.map +0 -1
- package/dist/package-json-_4PEss19.js +0 -2
- package/dist/package-manager-CmMJAD-V.js.map +0 -1
- package/dist/paths-DJS47p5x.js +0 -26
- package/dist/paths-DJS47p5x.js.map +0 -1
- package/dist/posthog-BbQf_Hzq.js +0 -11
- package/dist/posthog-BbQf_Hzq.js.map +0 -1
- package/dist/provisioning-gHqu_MXL.js +0 -2
- package/dist/registry-DpROZPnl.js.map +0 -1
- package/dist/setup-utils-Mzpk1vqG.js.map +0 -1
- package/dist/setup-utils-ptemIB6g.js +0 -2
- package/dist/slides-BtDXEXdn.js.map +0 -1
- package/dist/start-playground-zZL5y9id.js.map +0 -1
- package/dist/start-tui-Cz7RZSn_.js.map +0 -1
- package/dist/task-stream-DUpUZmFQ.js +0 -61
- package/dist/task-stream-DUpUZmFQ.js.map +0 -1
- package/dist/wizard-session-CPhhll4P.js +0 -2
- package/dist/wizard-session-CsI33S4_.js.map +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as analytics } from "./analytics-
|
|
3
|
-
import { t as withProgress } from "./telemetry-
|
|
4
|
-
import "./setup-utils-
|
|
5
|
-
import "./add-mcp-server-to-clients-
|
|
1
|
+
import { p as getUI } from "./debug-C4jRuzny.js";
|
|
2
|
+
import { n as analytics } from "./analytics-DZaUgJte.js";
|
|
3
|
+
import { t as withProgress } from "./telemetry-jn2Daxl2.js";
|
|
4
|
+
import "./setup-utils-DdAdxUTV.js";
|
|
5
|
+
import "./add-mcp-server-to-clients-9jQjc-CO.js";
|
|
6
6
|
import * as fs$1 from "fs";
|
|
7
7
|
import * as path$1 from "path";
|
|
8
8
|
import "path";
|
|
@@ -143,4 +143,4 @@ const uploadEnvironmentVariablesStep = async (envVars, { integration, session })
|
|
|
143
143
|
//#endregion
|
|
144
144
|
export { uploadEnvironmentVariablesStep };
|
|
145
145
|
|
|
146
|
-
//# sourceMappingURL=steps-
|
|
146
|
+
//# sourceMappingURL=steps-0d9XqvI6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"steps-
|
|
1
|
+
{"version":3,"file":"steps-0d9XqvI6.js","names":["path","fs","spawnSync","spawn"],"sources":["../src/steps/upload-environment-variables/EnvironmentProvider.ts","../src/steps/upload-environment-variables/providers/vercel.ts","../src/steps/upload-environment-variables/index.ts"],"sourcesContent":["export abstract class EnvironmentProvider {\n protected options: { installDir: string };\n\n name: string;\n\n constructor(options: { installDir: string }) {\n this.options = options;\n }\n\n abstract detect(): Promise<boolean>;\n\n abstract uploadEnvVars(\n vars: Record<string, string>,\n ): Promise<Record<string, boolean>>;\n}\n","import { execSync, spawn, spawnSync } from 'child_process';\nimport { EnvironmentProvider } from '@steps/upload-environment-variables/EnvironmentProvider';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { getUI } from '@ui';\nimport { analytics } from '@utils/analytics';\n\nexport class VercelEnvironmentProvider extends EnvironmentProvider {\n name = 'Vercel';\n environments = ['production', 'preview', 'development'];\n\n constructor(options: { installDir: string }) {\n super(options);\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await\n async detect(): Promise<boolean> {\n const vercelDetected =\n this.hasVercelCli() && this.isProjectLinked() && this.isAuthenticated();\n\n analytics.setTag('vercel-detected', vercelDetected);\n\n return vercelDetected;\n }\n\n hasDotVercelDir(): boolean {\n const dotVercelDir = path.join(this.options.installDir, '.vercel');\n return fs.existsSync(dotVercelDir);\n }\n\n hasVercelCli(): boolean {\n try {\n execSync('vercel --version', { stdio: 'ignore' });\n analytics.setTag('vercel-cli-installed', true);\n return true;\n } catch {\n analytics.setTag('vercel-cli-installed', false);\n return false;\n }\n }\n\n isProjectLinked(): boolean {\n const isProjectLinked = fs.existsSync(\n path.join(this.options.installDir, '.vercel', 'project.json'),\n );\n\n analytics.setTag('vercel-project-linked', isProjectLinked);\n\n return isProjectLinked;\n }\n\n isAuthenticated(): boolean {\n const result = spawnSync('vercel', ['whoami'], {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'], // suppress prompts\n env: {\n ...process.env,\n FORCE_COLOR: '0', // avoid ANSI formatting\n CI: '1', // hint to CLI that it's a non-interactive env\n },\n });\n\n const output = (\n String(result.stdout) + String(result.stderr)\n ).toLowerCase();\n\n if (\n output.includes('log in to vercel') ||\n output.includes('vercel login') ||\n result.status !== 0\n ) {\n analytics.setTag('vercel-authenticated', false);\n return false;\n }\n\n analytics.setTag('vercel-authenticated', true);\n\n return true;\n }\n\n async uploadEnvironmentVariable(\n key: string,\n value: string,\n environment: string,\n ): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n const proc = spawn('vercel', ['env', 'add', key, environment], {\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n let stderr = '';\n proc.stderr.on('data', (data) => {\n stderr += data.toString();\n });\n\n proc.stdin.write(value);\n proc.stdin.end();\n\n proc.on('close', (code) => {\n if (\n stderr.includes('already exists') ||\n stderr.includes('already been added') ||\n stderr.includes('vercel env rm')\n ) {\n reject(\n new Error(\n `❌ Environment variable ${key} already exists in ${this.name}. Please upload it manually.`,\n ),\n );\n } else if (code === 0) {\n resolve();\n } else {\n reject(\n new Error(\n `❌ Failed to upload environment variable ${key} to ${this.name}. Please upload it manually.`,\n ),\n );\n }\n });\n });\n }\n\n async uploadEnvVars(\n vars: Record<string, string>,\n ): Promise<Record<string, boolean>> {\n const results: Record<string, boolean> = {};\n\n for (const [key, value] of Object.entries(vars)) {\n const spinner = getUI().spinner();\n\n spinner.start(`Uploading ${key} to ${this.name}...`);\n await Promise.all(\n this.environments.map((environment) =>\n this.uploadEnvironmentVariable(key, value, environment),\n ),\n )\n .then(() => {\n spinner.stop(`✅ Uploaded ${key} to ${this.name}`);\n results[key] = true;\n })\n .catch((err) => {\n spinner.stop(\n err instanceof Error\n ? err.message\n : `❌ Failed to upload environment variables to ${this.name}. Please upload it manually.`,\n );\n results[key] = false;\n });\n }\n\n return results;\n }\n}\n","import type { Integration } from '@lib/constants';\nimport { withProgress } from '../../telemetry';\nimport { analytics } from '@utils/analytics';\nimport { getUI } from '@ui';\nimport type { WizardSession } from '@lib/wizard-session';\nimport { EnvironmentProvider } from './EnvironmentProvider';\nimport { VercelEnvironmentProvider } from './providers/vercel';\n\nexport const uploadEnvironmentVariablesStep = async (\n envVars: Record<string, string>,\n {\n integration,\n session,\n }: {\n integration: Integration;\n session: WizardSession;\n },\n): Promise<string[]> => {\n const providers: EnvironmentProvider[] = [\n new VercelEnvironmentProvider({ installDir: session.installDir }),\n ];\n\n let provider: EnvironmentProvider | null = null;\n\n for (const p of providers) {\n if (await p.detect()) {\n provider = p;\n break;\n }\n }\n\n if (!provider) {\n analytics.wizardCapture('env upload skipped', {\n reason: 'no environment provider found',\n integration,\n });\n return [];\n }\n\n // Auto-accept — the agent already wrote env vars via MCP tools\n getUI().log.info(`Uploading environment variables to ${provider.name}...`);\n\n const results = await withProgress(\n 'uploading environment variables',\n async () => {\n return await provider.uploadEnvVars(envVars);\n },\n );\n\n analytics.wizardCapture('env uploaded', {\n provider: provider.name,\n integration,\n });\n\n return Object.keys(results).filter((key) => results[key]);\n};\n"],"mappings":";;;;;;;;;;AAAA,IAAsB,sBAAtB,MAA0C;CACxC;CAEA;CAEA,YAAY,SAAiC;AAC3C,OAAK,UAAU;;;;;ACCnB,IAAa,4BAAb,cAA+C,oBAAoB;CACjE,OAAO;CACP,eAAe;EAAC;EAAc;EAAW;EAAc;CAEvD,YAAY,SAAiC;AAC3C,QAAM,QAAQ;;CAIhB,MAAM,SAA2B;EAC/B,MAAM,iBACJ,KAAK,cAAc,IAAI,KAAK,iBAAiB,IAAI,KAAK,iBAAiB;AAEzE,YAAU,OAAO,mBAAmB,eAAe;AAEnD,SAAO;;CAGT,kBAA2B;EACzB,MAAM,eAAeA,OAAK,KAAK,KAAK,QAAQ,YAAY,UAAU;AAClE,SAAOC,KAAG,WAAW,aAAa;;CAGpC,eAAwB;AACtB,MAAI;AACF,cAAS,oBAAoB,EAAE,OAAO,UAAU,CAAC;AACjD,aAAU,OAAO,wBAAwB,KAAK;AAC9C,UAAO;UACD;AACN,aAAU,OAAO,wBAAwB,MAAM;AAC/C,UAAO;;;CAIX,kBAA2B;EACzB,MAAM,kBAAkBA,KAAG,WACzBD,OAAK,KAAK,KAAK,QAAQ,YAAY,WAAW,eAAe,CAC9D;AAED,YAAU,OAAO,yBAAyB,gBAAgB;AAE1D,SAAO;;CAGT,kBAA2B;EACzB,MAAM,SAASE,YAAU,UAAU,CAAC,SAAS,EAAE;GAC7C,UAAU;GACV,OAAO;IAAC;IAAQ;IAAQ;IA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CACF,CACE,WAAW;AACV,YAAQ,KAAK,cAAc,IAAI,MAAM,KAAK,OAAO;AACjD,YAAQ,OAAO;KACf,CACD,OAAO,QAAQ;AACd,YAAQ,KACN,eAAe,QACX,IAAI,UACJ,+CAA+C,KAAK,KAAK,8BAC9D;AACD,YAAQ,OAAO;KACf;;AAGN,SAAO;;;;;AC9IX,MAAa,iCAAiC,OAC5C,SACA,EACE,aACA,cAKoB;CACtB,MAAM,YAAmC,CACvC,IAAI,0BAA0B,EAAE,YAAY,QAAQ,YAAY,CAAC,CAClE;CAED,IAAI,WAAuC;AAE3C,MAAK,MAAM,KAAK,UACd,KAAI,MAAM,EAAE,QAAQ,EAAE;AACpB,aAAW;AACX;;AAIJ,KAAI,CAAC,UAAU;AACb,YAAU,cAAc,sBAAsB;GAC5C,QAAQ;GACR;GACD,CAAC;AACF,SAAO,EAAE;;AAIX,QAAO,CAAC,IAAI,KAAK,sCAAsC,SAAS,KAAK,KAAK;CAE1E,MAAM,UAAU,MAAM,aACpB,mCACA,YAAY;AACV,SAAO,MAAM,SAAS,cAAc,QAAQ;GAE/C;AAED,WAAU,cAAc,gBAAgB;EACtC,UAAU,SAAS;EACnB;EACD,CAAC;AAEF,QAAO,OAAO,KAAK,QAAQ,CAAC,QAAQ,QAAQ,QAAQ,KAAK"}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import "./wizard-ui-YdGFRyu_.js";
|
|
2
|
+
import "./wizard-session-Bi95IYca.js";
|
|
3
|
+
import "./posthog-7B92c2Ed.js";
|
|
4
|
+
//#region src/lib/task-stream/task-stream-push.ts
|
|
5
|
+
/** Trailing-edge debounce window for non-phase-change emits. */
|
|
6
|
+
const DEBOUNCE_MS = 250;
|
|
7
|
+
/** Default shutdown timeout for the final terminal flush. */
|
|
8
|
+
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 2e3;
|
|
9
|
+
const STATUS_MAP = {
|
|
10
|
+
["pending"]: "pending",
|
|
11
|
+
["in_progress"]: "in_progress",
|
|
12
|
+
["completed"]: "completed"
|
|
13
|
+
};
|
|
14
|
+
function buildTasks(items) {
|
|
15
|
+
return items.map((item, i) => ({
|
|
16
|
+
id: String(i),
|
|
17
|
+
title: item.label,
|
|
18
|
+
status: STATUS_MAP[item.status] ?? "pending"
|
|
19
|
+
}));
|
|
20
|
+
}
|
|
21
|
+
/** Drop ".SSSZ" → "Z" so session_id segments stay routing-safe. */
|
|
22
|
+
function secondPrecisionIso(d) {
|
|
23
|
+
return d.toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* `workflow_id` and `skill_id` end up unescaped in Redis pub/sub
|
|
27
|
+
* channel names, so the backend rejects anything outside
|
|
28
|
+
* `^[A-Za-z0-9_.-]{1,255}$` with a 400. All current values already
|
|
29
|
+
* comply; this is defence in depth in case a future caller passes
|
|
30
|
+
* something with `:`, spaces, or other separators.
|
|
31
|
+
*/
|
|
32
|
+
function sanitizeChannelId(value) {
|
|
33
|
+
return value.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 255);
|
|
34
|
+
}
|
|
35
|
+
function buildError(phase, outroData) {
|
|
36
|
+
if (phase !== "error") return void 0;
|
|
37
|
+
if (outroData?.kind === "error") return {
|
|
38
|
+
type: "wizard_error",
|
|
39
|
+
message: outroData.message ?? outroData.body ?? "Wizard run failed"
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
type: "wizard_error",
|
|
43
|
+
message: "Wizard run failed"
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
var TaskStreamPush = class {
|
|
47
|
+
store;
|
|
48
|
+
destinations;
|
|
49
|
+
startedAt;
|
|
50
|
+
programId;
|
|
51
|
+
sessionId;
|
|
52
|
+
enabled;
|
|
53
|
+
created = false;
|
|
54
|
+
lastPushedPhase = null;
|
|
55
|
+
unsubscribe = null;
|
|
56
|
+
debounceTimer = null;
|
|
57
|
+
inFlight = null;
|
|
58
|
+
needsAnotherPush = false;
|
|
59
|
+
shuttingDown = false;
|
|
60
|
+
constructor(opts) {
|
|
61
|
+
this.store = opts.store;
|
|
62
|
+
this.programId = sanitizeChannelId(opts.programId);
|
|
63
|
+
this.destinations = opts.destinations;
|
|
64
|
+
this.enabled = opts.enabled ?? true;
|
|
65
|
+
this.startedAt = secondPrecisionIso(/* @__PURE__ */ new Date());
|
|
66
|
+
const skillId = sanitizeChannelId(this.store.session.skillId ?? this.programId);
|
|
67
|
+
this.sessionId = `${this.programId}-${skillId}-${this.startedAt}`;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Subscribe to store changes. No-op when `enabled === false`.
|
|
71
|
+
* Idempotent — repeat calls are ignored.
|
|
72
|
+
*/
|
|
73
|
+
attach(store) {
|
|
74
|
+
if (!this.enabled) return;
|
|
75
|
+
if (this.unsubscribe) return;
|
|
76
|
+
const target = store ?? this.store;
|
|
77
|
+
this.unsubscribe = target.subscribe(() => this.onStoreChange());
|
|
78
|
+
}
|
|
79
|
+
/** Stop subscribing. Does not flush. */
|
|
80
|
+
detach() {
|
|
81
|
+
if (this.unsubscribe) {
|
|
82
|
+
this.unsubscribe();
|
|
83
|
+
this.unsubscribe = null;
|
|
84
|
+
}
|
|
85
|
+
if (this.debounceTimer) {
|
|
86
|
+
clearTimeout(this.debounceTimer);
|
|
87
|
+
this.debounceTimer = null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Cancel pending debounce, flush one final push if the current
|
|
92
|
+
* phase is terminal, and resolve. Never throws. Bounded by
|
|
93
|
+
* `timeoutMs` — if a destination hangs, this returns anyway.
|
|
94
|
+
*/
|
|
95
|
+
async shutdown(timeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS) {
|
|
96
|
+
this.shuttingDown = true;
|
|
97
|
+
if (this.debounceTimer) {
|
|
98
|
+
clearTimeout(this.debounceTimer);
|
|
99
|
+
this.debounceTimer = null;
|
|
100
|
+
}
|
|
101
|
+
this.detach();
|
|
102
|
+
if (!this.enabled) return;
|
|
103
|
+
const phase = this.store.session.runPhase;
|
|
104
|
+
if (!(phase === "completed" || phase === "error")) return;
|
|
105
|
+
const flush = this.flush();
|
|
106
|
+
if (timeoutMs <= 0) return;
|
|
107
|
+
await Promise.race([flush, new Promise((resolve) => setTimeout(resolve, timeoutMs))]);
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Imperative push — fires immediately regardless of phase. Kept as
|
|
111
|
+
* the building block for both subscription-driven and direct calls.
|
|
112
|
+
*/
|
|
113
|
+
async push() {
|
|
114
|
+
await this.flush();
|
|
115
|
+
}
|
|
116
|
+
onStoreChange() {
|
|
117
|
+
if (!this.enabled || this.shuttingDown) return;
|
|
118
|
+
const phase = this.store.session.runPhase;
|
|
119
|
+
if (phase === "idle") return;
|
|
120
|
+
if (this.inFlight) {
|
|
121
|
+
if (this.debounceTimer) {
|
|
122
|
+
clearTimeout(this.debounceTimer);
|
|
123
|
+
this.debounceTimer = null;
|
|
124
|
+
}
|
|
125
|
+
this.needsAnotherPush = true;
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (phase !== this.lastPushedPhase) {
|
|
129
|
+
if (this.debounceTimer) {
|
|
130
|
+
clearTimeout(this.debounceTimer);
|
|
131
|
+
this.debounceTimer = null;
|
|
132
|
+
}
|
|
133
|
+
this.flush();
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (this.debounceTimer) return;
|
|
137
|
+
this.debounceTimer = setTimeout(() => {
|
|
138
|
+
this.debounceTimer = null;
|
|
139
|
+
this.flush();
|
|
140
|
+
}, DEBOUNCE_MS);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Fan out the current state to every destination. Serialized — if
|
|
144
|
+
* a flush is already running, mark "needs another" and let the
|
|
145
|
+
* in-flight one schedule the follow-up when it settles.
|
|
146
|
+
*/
|
|
147
|
+
flush() {
|
|
148
|
+
if (this.inFlight) {
|
|
149
|
+
this.needsAnotherPush = true;
|
|
150
|
+
return this.inFlight;
|
|
151
|
+
}
|
|
152
|
+
const run = async () => {
|
|
153
|
+
try {
|
|
154
|
+
await this.sendOnce();
|
|
155
|
+
} finally {
|
|
156
|
+
this.inFlight = null;
|
|
157
|
+
if (this.needsAnotherPush) {
|
|
158
|
+
this.needsAnotherPush = false;
|
|
159
|
+
await this.flush();
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
this.inFlight = run();
|
|
164
|
+
return this.inFlight;
|
|
165
|
+
}
|
|
166
|
+
async sendOnce() {
|
|
167
|
+
const { session, tasks, eventPlan } = this.store;
|
|
168
|
+
const skillId = sanitizeChannelId(session.skillId ?? this.programId);
|
|
169
|
+
const phase = session.runPhase;
|
|
170
|
+
const payload = {
|
|
171
|
+
session_id: this.sessionId,
|
|
172
|
+
workflow_id: this.programId,
|
|
173
|
+
skill_id: skillId,
|
|
174
|
+
started_at: this.startedAt,
|
|
175
|
+
run_phase: phase,
|
|
176
|
+
tasks: buildTasks(tasks),
|
|
177
|
+
event_plan: eventPlan.length > 0 ? { events: eventPlan } : void 0,
|
|
178
|
+
error: buildError(phase, session.outroData),
|
|
179
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
180
|
+
};
|
|
181
|
+
let event;
|
|
182
|
+
if (!this.created) {
|
|
183
|
+
this.created = true;
|
|
184
|
+
event = "CREATE";
|
|
185
|
+
} else if (phase === "completed") event = "COMPLETE";
|
|
186
|
+
else if (phase === "error") event = "ERROR";
|
|
187
|
+
else event = "UPDATE";
|
|
188
|
+
this.lastPushedPhase = phase;
|
|
189
|
+
await Promise.all(this.destinations.map((d) => d.send(event, payload).catch(() => {})));
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
//#endregion
|
|
193
|
+
export { TaskStreamPush };
|
|
194
|
+
|
|
195
|
+
//# sourceMappingURL=task-stream-CoEsidgG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"task-stream-CoEsidgG.js","names":[],"sources":["../src/lib/task-stream/task-stream-push.ts"],"sourcesContent":["/**\n * Task-stream push — subscribes to WizardStore, builds payloads,\n * and fans out async to all registered destinations.\n *\n * Behaviour:\n * - `attach(store)` subscribe to store changes\n * - task updates debounced 250ms (trailing edge)\n * - phase transitions flush immediately, bypass debounce\n * - RunPhase.Idle skipped (no push)\n * - enabled === false attach is a no-op\n * - shutdown(timeoutMs) cancel pending, flush terminal phase\n * with timeout, never throw\n *\n * Concurrency: only one fan-out at a time. Emits during an in-flight\n * push are coalesced — at most one follow-up push fires with the\n * latest state once the current one settles.\n */\n\nimport type { WizardStore, TaskItem } from '@ui/tui/store';\nimport { TaskStatus } from '@ui/wizard-ui';\nimport { RunPhase, OutroKind, type OutroData } from '@lib/wizard-session';\nimport {\n type TaskStreamDestination,\n type TaskStreamUpdate,\n type StreamTask,\n type TaskStreamError,\n StreamTaskStatus,\n StreamEvent,\n} from './types';\n\n/** Trailing-edge debounce window for non-phase-change emits. */\nconst DEBOUNCE_MS = 250;\n/** Default shutdown timeout for the final terminal flush. */\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 2000;\n\nconst STATUS_MAP: Record<TaskStatus, StreamTaskStatus> = {\n [TaskStatus.Pending]: StreamTaskStatus.Pending,\n [TaskStatus.InProgress]: StreamTaskStatus.InProgress,\n [TaskStatus.Completed]: StreamTaskStatus.Completed,\n};\n\nfunction buildTasks(items: TaskItem[]): StreamTask[] {\n return items.map((item, i) => ({\n id: String(i),\n title: item.label,\n status: STATUS_MAP[item.status] ?? StreamTaskStatus.Pending,\n }));\n}\n\n/** Drop \".SSSZ\" → \"Z\" so session_id segments stay routing-safe. */\nfunction secondPrecisionIso(d: Date): string {\n return d.toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n}\n\n/**\n * `workflow_id` and `skill_id` end up unescaped in Redis pub/sub\n * channel names, so the backend rejects anything outside\n * `^[A-Za-z0-9_.-]{1,255}$` with a 400. All current values already\n * comply; this is defence in depth in case a future caller passes\n * something with `:`, spaces, or other separators.\n */\nfunction sanitizeChannelId(value: string): string {\n return value.replace(/[^A-Za-z0-9_.-]/g, '-').slice(0, 255);\n}\n\nfunction buildError(\n phase: RunPhase,\n outroData: OutroData | null,\n): TaskStreamError | undefined {\n if (phase !== RunPhase.Error) return undefined;\n if (outroData?.kind === OutroKind.Error) {\n const message = outroData.message ?? outroData.body ?? 'Wizard run failed';\n return { type: 'wizard_error', message };\n }\n return { type: 'wizard_error', message: 'Wizard run failed' };\n}\n\nexport interface TaskStreamPushOptions {\n store: WizardStore;\n programId: string;\n destinations: TaskStreamDestination[];\n /** When false, `attach` is a no-op and no destination ever fires. */\n enabled?: boolean;\n}\n\nexport class TaskStreamPush {\n private readonly store: WizardStore;\n private readonly destinations: TaskStreamDestination[];\n private readonly startedAt: string;\n private readonly programId: string;\n private readonly sessionId: string;\n\n private enabled: boolean;\n private created = false;\n private lastPushedPhase: RunPhase | null = null;\n\n private unsubscribe: (() => void) | null = null;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private inFlight: Promise<void> | null = null;\n private needsAnotherPush = false;\n private shuttingDown = false;\n\n constructor(opts: TaskStreamPushOptions) {\n this.store = opts.store;\n this.programId = sanitizeChannelId(opts.programId);\n this.destinations = opts.destinations;\n this.enabled = opts.enabled ?? true;\n this.startedAt = secondPrecisionIso(new Date());\n // skillId may not be set yet — fall back to programId so the\n // session_id is stable for the whole run regardless of when the\n // program metadata is populated.\n const skillId = sanitizeChannelId(\n this.store.session.skillId ?? this.programId,\n );\n this.sessionId = `${this.programId}-${skillId}-${this.startedAt}`;\n }\n\n /**\n * Subscribe to store changes. No-op when `enabled === false`.\n * Idempotent — repeat calls are ignored.\n */\n attach(store?: WizardStore): void {\n if (!this.enabled) return;\n if (this.unsubscribe) return;\n const target = store ?? this.store;\n this.unsubscribe = target.subscribe(() => this.onStoreChange());\n }\n\n /** Stop subscribing. Does not flush. */\n detach(): void {\n if (this.unsubscribe) {\n this.unsubscribe();\n this.unsubscribe = null;\n }\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n }\n\n /**\n * Cancel pending debounce, flush one final push if the current\n * phase is terminal, and resolve. Never throws. Bounded by\n * `timeoutMs` — if a destination hangs, this returns anyway.\n */\n async shutdown(\n timeoutMs: number = DEFAULT_SHUTDOWN_TIMEOUT_MS,\n ): Promise<void> {\n this.shuttingDown = true;\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n this.detach();\n if (!this.enabled) return;\n\n const phase = this.store.session.runPhase;\n const isTerminal = phase === RunPhase.Completed || phase === RunPhase.Error;\n if (!isTerminal) return;\n\n const flush = this.flush();\n if (timeoutMs <= 0) return;\n await Promise.race([\n flush,\n new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),\n ]);\n }\n\n /**\n * Imperative push — fires immediately regardless of phase. Kept as\n * the building block for both subscription-driven and direct calls.\n */\n async push(): Promise<void> {\n await this.flush();\n }\n\n // ── Internal ────────────────────────────────────────────────────\n\n private onStoreChange(): void {\n if (!this.enabled || this.shuttingDown) return;\n const phase = this.store.session.runPhase;\n if (phase === RunPhase.Idle) return;\n\n // A push is already in flight — coalesce. The in-flight push's\n // settle handler will trigger one follow-up with the latest state.\n if (this.inFlight) {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n this.needsAnotherPush = true;\n return;\n }\n\n const phaseChanged = phase !== this.lastPushedPhase;\n if (phaseChanged) {\n // Phase transitions bypass the debounce: the web app needs to\n // see Running → Completed as soon as it lands.\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n void this.flush();\n return;\n }\n\n // Task updates can arrive faster than we want to push. Debounce\n // them — the last update in a burst wins.\n if (this.debounceTimer) return;\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n void this.flush();\n }, DEBOUNCE_MS);\n }\n\n /**\n * Fan out the current state to every destination. Serialized — if\n * a flush is already running, mark \"needs another\" and let the\n * in-flight one schedule the follow-up when it settles.\n */\n private flush(): Promise<void> {\n if (this.inFlight) {\n this.needsAnotherPush = true;\n return this.inFlight;\n }\n\n const run = async (): Promise<void> => {\n try {\n await this.sendOnce();\n } finally {\n this.inFlight = null;\n if (this.needsAnotherPush) {\n this.needsAnotherPush = false;\n // Re-enter to push the latest snapshot.\n await this.flush();\n }\n }\n };\n\n this.inFlight = run();\n return this.inFlight;\n }\n\n private async sendOnce(): Promise<void> {\n const { session, tasks, eventPlan } = this.store;\n const skillId = sanitizeChannelId(session.skillId ?? this.programId);\n const phase = session.runPhase;\n\n const payload: TaskStreamUpdate = {\n session_id: this.sessionId,\n workflow_id: this.programId,\n skill_id: skillId,\n started_at: this.startedAt,\n run_phase: phase,\n tasks: buildTasks(tasks),\n event_plan: eventPlan.length > 0 ? { events: eventPlan } : undefined,\n error: buildError(phase, session.outroData),\n timestamp: new Date().toISOString(),\n };\n\n let event: StreamEvent;\n if (!this.created) {\n this.created = true;\n event = StreamEvent.Create;\n } else if (phase === RunPhase.Completed) {\n event = StreamEvent.Complete;\n } else if (phase === RunPhase.Error) {\n event = StreamEvent.Error;\n } else {\n event = StreamEvent.Update;\n }\n\n this.lastPushedPhase = phase;\n\n await Promise.all(\n this.destinations.map((d) =>\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n d.send(event, payload).catch(() => {}),\n ),\n );\n }\n}\n"],"mappings":";;;;;AA+BA,MAAM,cAAc;;AAEpB,MAAM,8BAA8B;AAEpC,MAAM,aAAmD;;;;CAIxD;AAED,SAAS,WAAW,OAAiC;AACnD,QAAO,MAAM,KAAK,MAAM,OAAO;EAC7B,IAAI,OAAO,EAAE;EACb,OAAO,KAAK;EACZ,QAAQ,WAAW,KAAK,WAAA;EACzB,EAAE;;;AAIL,SAAS,mBAAmB,GAAiB;AAC3C,QAAO,EAAE,aAAa,CAAC,QAAQ,aAAa,IAAI;;;;;;;;;AAUlD,SAAS,kBAAkB,OAA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aAAa,KAAK;GAClB,UAAU;GACV,YAAY,KAAK;GACjB,WAAW;GACX,OAAO,WAAW,MAAM;GACxB,YAAY,UAAU,SAAS,IAAI,EAAE,QAAQ,WAAW,GAAG,KAAA;GAC3D,OAAO,WAAW,OAAO,QAAQ,UAAU;GAC3C,4BAAW,IAAI,MAAM,EAAC,aAAa;GACpC;EAED,IAAI;AACJ,MAAI,CAAC,KAAK,SAAS;AACjB,QAAK,UAAU;AACf,WAAA;aACS,UAAA,YACT,SAAA;WACS,UAAA,QACT,SAAA;MAEA,SAAA;AAGF,OAAK,kBAAkB;AAEvB,QAAM,QAAQ,IACZ,KAAK,aAAa,KAAK,MAErB,EAAE,KAAK,OAAO,QAAQ,CAAC,YAAY,GAAG,CACvC,CACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as analytics } from "./analytics-
|
|
1
|
+
import { n as analytics } from "./analytics-DZaUgJte.js";
|
|
2
2
|
//#region src/telemetry.ts
|
|
3
3
|
function withProgress(step, callback) {
|
|
4
4
|
updateProgress(step);
|
|
@@ -10,4 +10,4 @@ function updateProgress(step) {
|
|
|
10
10
|
//#endregion
|
|
11
11
|
export { withProgress as t };
|
|
12
12
|
|
|
13
|
-
//# sourceMappingURL=telemetry-
|
|
13
|
+
//# sourceMappingURL=telemetry-jn2Daxl2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"telemetry-
|
|
1
|
+
{"version":3,"file":"telemetry-jn2Daxl2.js","names":[],"sources":["../src/telemetry.ts"],"sourcesContent":["import { analytics } from '@utils/analytics';\n\nexport function withProgress<T>(step: string, callback: () => T): T {\n updateProgress(step);\n return callback();\n}\n\nexport function updateProgress(step: string) {\n analytics.setTag('progress', step);\n}\n"],"mappings":";;AAEA,SAAgB,aAAgB,MAAc,UAAsB;AAClE,gBAAe,KAAK;AACpB,QAAO,UAAU;;AAGnB,SAAgB,eAAe,MAAc;AAC3C,WAAU,OAAO,YAAY,KAAK"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as analytics } from "./analytics-
|
|
1
|
+
import { p as getUI } from "./debug-C4jRuzny.js";
|
|
2
|
+
import { n as analytics } from "./analytics-DZaUgJte.js";
|
|
3
3
|
//#region src/utils/wizard-abort.ts
|
|
4
4
|
/**
|
|
5
5
|
* Single exit point for the wizard. Use instead of process.exit() directly.
|
|
@@ -38,4 +38,4 @@ async function wizardAbort(options) {
|
|
|
38
38
|
//#endregion
|
|
39
39
|
export { registerCleanup as n, wizardAbort as r, WizardError as t };
|
|
40
40
|
|
|
41
|
-
//# sourceMappingURL=wizard-abort-
|
|
41
|
+
//# sourceMappingURL=wizard-abort-BjLIgu2s.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wizard-abort-
|
|
1
|
+
{"version":3,"file":"wizard-abort-BjLIgu2s.js","names":[],"sources":["../src/utils/wizard-abort.ts"],"sourcesContent":["/**\n * Single exit point for the wizard. Use instead of process.exit() directly.\n *\n * Sequence: cleanup -> error capture (optional) -> analytics shutdown -> outro -> process.exit\n *\n * WizardError is a data carrier passed to wizardAbort() for analytics context, never thrown.\n * The legacy abort() in setup-utils.ts delegates here.\n */\nimport { analytics } from './analytics';\nimport { getUI } from '@ui';\nimport { OutroKind, type OutroData } from '@lib/wizard-session';\n\nexport class WizardError extends Error {\n constructor(\n message: string,\n public readonly context?: Record<string, unknown>,\n ) {\n super(message);\n this.name = 'WizardError';\n }\n}\n\ninterface WizardAbortOptions {\n message?: string;\n /** Structured error data. Renders via `outroError` instead of `outro`. */\n outroData?: OutroData;\n error?: Error | WizardError;\n exitCode?: number;\n}\n\nconst cleanupFns: Array<() => void> = [];\n\nexport function registerCleanup(fn: () => void): void {\n cleanupFns.push(fn);\n}\n\nexport function clearCleanup(): void {\n cleanupFns.length = 0;\n}\n\nexport async function wizardAbort(\n options?: WizardAbortOptions,\n): Promise<never> {\n const {\n message = 'Wizard setup cancelled.',\n outroData,\n error,\n exitCode = 1,\n } = options ?? {};\n\n // 1. Run registered cleanup functions\n for (const fn of cleanupFns) {\n try {\n fn();\n } catch {\n /* cleanup should not prevent exit */\n }\n }\n\n // 2. Capture error in analytics (if provided)\n if (error) {\n analytics.captureException(error, {\n ...((error instanceof WizardError && error.context) || {}),\n });\n }\n\n // 3. Shutdown analytics\n await analytics.shutdown(error ? 'error' : 'cancelled');\n\n // 4. Render the error outro. Synthesize OutroData from `message`\n // when the caller didn't provide structured data.\n const ui = getUI();\n ui.outroError(outroData ?? { kind: OutroKind.Error, message });\n\n // 5. Wait for the user to dismiss the outro screen. In a TUI this gives\n // them time to read the error; in non-TUI environments it resolves\n // immediately.\n await ui.waitForOutroDismissed();\n\n // 6. Exit (fires 'exit' event so TUI cleanup runs)\n return process.exit(exitCode);\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAa,cAAb,cAAiC,MAAM;CACrC,YACE,SACA,SACA;AACA,QAAM,QAAQ;AAFE,OAAA,UAAA;AAGhB,OAAK,OAAO;;;AAYhB,MAAM,aAAgC,EAAE;AAExC,SAAgB,gBAAgB,IAAsB;AACpD,YAAW,KAAK,GAAG;;AAOrB,eAAsB,YACpB,SACgB;CAChB,MAAM,EACJ,UAAU,2BACV,WACA,OACA,WAAW,MACT,WAAW,EAAE;AAGjB,MAAK,MAAM,MAAM,WACf,KAAI;AACF,MAAI;SACE;AAMV,KAAI,MACF,WAAU,iBAAiB,OAAO,EAChC,GAAK,iBAAiB,eAAe,MAAM,WAAY,EAAE,EAC1D,CAAC;AAIJ,OAAM,UAAU,SAAS,QAAQ,UAAU,YAAY;CAIvD,MAAM,KAAK,OAAO;AAClB,IAAG,WAAW,aAAa;EAAE,MAAA;EAAuB;EAAS,CAAC;AAK9D,OAAM,GAAG,uBAAuB;AAGhC,QAAO,QAAQ,KAAK,SAAS"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { r as wizardAbort, t as WizardError } from "./wizard-abort-
|
|
1
|
+
import { r as wizardAbort, t as WizardError } from "./wizard-abort-BjLIgu2s.js";
|
|
2
2
|
export { WizardError, wizardAbort };
|
|
@@ -4,6 +4,18 @@ function parseProjectIdArg(value) {
|
|
|
4
4
|
const n = Number(value);
|
|
5
5
|
return Number.isInteger(n) && n > 0 ? n : void 0;
|
|
6
6
|
}
|
|
7
|
+
/** Lifecycle phase of the main work (agent run, MCP install, etc.) */
|
|
8
|
+
let RunPhase = /* @__PURE__ */ function(RunPhase) {
|
|
9
|
+
/** Still gathering input (intro, setup screens) */
|
|
10
|
+
RunPhase["Idle"] = "idle";
|
|
11
|
+
/** Main work is in progress */
|
|
12
|
+
RunPhase["Running"] = "running";
|
|
13
|
+
/** Main work finished successfully */
|
|
14
|
+
RunPhase["Completed"] = "completed";
|
|
15
|
+
/** Main work finished with an error */
|
|
16
|
+
RunPhase["Error"] = "error";
|
|
17
|
+
return RunPhase;
|
|
18
|
+
}({});
|
|
7
19
|
/** Human-readable labels for additional features (used in TUI progress) */
|
|
8
20
|
const ADDITIONAL_FEATURE_LABELS = { ["llm"]: "LLM analytics" };
|
|
9
21
|
/** Agent prompts for each additional feature, injected via the stop hook */
|
|
@@ -27,6 +39,7 @@ function buildSession(args) {
|
|
|
27
39
|
benchmark: args.benchmark ?? false,
|
|
28
40
|
yaraReport: args.yaraReport ?? false,
|
|
29
41
|
projectId: parseProjectIdArg(args.projectId),
|
|
42
|
+
noTelemetry: args.noTelemetry ?? false,
|
|
30
43
|
setupConfirmed: false,
|
|
31
44
|
integration: args.integration ?? null,
|
|
32
45
|
frameworkContext: {},
|
|
@@ -40,10 +53,14 @@ function buildSession(args) {
|
|
|
40
53
|
mcpComplete: false,
|
|
41
54
|
mcpOutcome: null,
|
|
42
55
|
mcpInstalledClients: [],
|
|
56
|
+
mcpSuggestedPromptsDismissed: false,
|
|
43
57
|
skillsComplete: false,
|
|
44
58
|
outroDismissed: false,
|
|
45
59
|
loginUrl: null,
|
|
60
|
+
authorizeUrl: null,
|
|
46
61
|
credentials: null,
|
|
62
|
+
roleAtOrganization: null,
|
|
63
|
+
apiUser: null,
|
|
47
64
|
readinessResult: null,
|
|
48
65
|
outageDismissed: false,
|
|
49
66
|
settingsOverrideKeys: null,
|
|
@@ -60,6 +77,6 @@ function buildSession(args) {
|
|
|
60
77
|
};
|
|
61
78
|
}
|
|
62
79
|
//#endregion
|
|
63
|
-
export { ADDITIONAL_FEATURE_PROMPTS as n,
|
|
80
|
+
export { buildSession as i, ADDITIONAL_FEATURE_PROMPTS as n, RunPhase as r, ADDITIONAL_FEATURE_LABELS as t };
|
|
64
81
|
|
|
65
|
-
//# sourceMappingURL=wizard-session-
|
|
82
|
+
//# sourceMappingURL=wizard-session-Bi95IYca.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wizard-session-Bi95IYca.js","names":[],"sources":["../src/lib/wizard-session.ts"],"sourcesContent":["/**\n * WizardSession — single source of truth for every decision the wizard needs.\n *\n * Populated in layers:\n * CLI args / env vars → populate fields directly\n * Auto-detection → framework, typescript, package manager\n * TUI screens → region, framework disambiguation, etc.\n * OAuth → credentials\n *\n * Business logic reads from the session. Never calls a prompt.\n */\n\nimport type { Integration } from './constants';\nimport type { FrameworkConfig } from './framework-config';\nimport type { WizardReadinessResult } from './health-checks/readiness';\nimport type { SettingsConflict } from './agent/agent-interface';\nimport type { ApiUser } from './api';\n\nexport interface Credentials {\n accessToken: string;\n projectApiKey: string;\n host: string;\n projectId: number;\n}\n\nfunction parseProjectIdArg(value: string | undefined): number | undefined {\n if (value === undefined || value === '') return undefined;\n const n = Number(value);\n return Number.isInteger(n) && n > 0 ? n : undefined;\n}\n\nexport type CloudRegion = 'us' | 'eu';\n\n/** Lifecycle phase of the main work (agent run, MCP install, etc.) */\nexport enum RunPhase {\n /** Still gathering input (intro, setup screens) */\n Idle = 'idle',\n /** Main work is in progress */\n Running = 'running',\n /** Main work finished successfully */\n Completed = 'completed',\n /** Main work finished with an error */\n Error = 'error',\n}\n\n/** Features discovered by the feature-discovery subagent */\nexport enum DiscoveredFeature {\n Stripe = 'stripe',\n LLM = 'llm',\n}\n\n/** Additional features the agent can integrate after the main setup */\nexport enum AdditionalFeature {\n LLM = 'llm',\n}\n\n/** Human-readable labels for additional features (used in TUI progress) */\nexport const ADDITIONAL_FEATURE_LABELS: Record<AdditionalFeature, string> = {\n [AdditionalFeature.LLM]: 'LLM analytics',\n};\n\n/** Agent prompts for each additional feature, injected via the stop hook */\nexport const ADDITIONAL_FEATURE_PROMPTS: Record<AdditionalFeature, string> = {\n [AdditionalFeature.LLM]: `Now integrate LLM analytics with PostHog. Use the PostHog MCP server to find the appropriate LLM analytics skill, install it, and follow its workflow. PostHog basics are already installed. Update the setup report markdown file when complete with additions from this task. `,\n};\n\n/** Outcome of the MCP server installation step */\nexport enum McpOutcome {\n NoClients = 'no_clients',\n Skipped = 'skipped',\n Installed = 'installed',\n Failed = 'failed',\n}\n\n/** Outcome kind for the outro screen */\nexport enum OutroKind {\n Success = 'success',\n Error = 'error',\n Cancel = 'cancel',\n}\n\nexport interface OutroData {\n kind: OutroKind;\n /** Main headline (green check for Success, red X for Error, etc.) */\n message?: string;\n /** Free-form body text shown under the headline. Use \\n for paragraph breaks. */\n body?: string;\n /** Success-only: bulleted list of \"what the agent did\" */\n changes?: string[];\n docsUrl?: string;\n continueUrl?: string;\n /** Report file the agent wrote (e.g. \"posthog-setup-report.md\") */\n reportFile?: string;\n /** PostHog dashboard URL the program created on the user's behalf. */\n dashboardUrl?: string;\n}\n\n/** A single question rendered by the WizardAsk overlay. */\nexport interface AskQuestion {\n /** Key for the response map */\n id: string;\n prompt: string;\n /** text = single-line free input; single/multi = picker */\n kind: 'single' | 'multi' | 'text';\n /** Required for `single` and `multi`. Ignored for `text`. */\n options?: { label: string; value: string }[];\n /** Defaults to true */\n required?: boolean;\n /**\n * Only meaningful for kind='text'. When true, the wizard-tools `wizard_ask`\n * tool stores the user's answer in the session secret vault and returns\n * `{ secretRef }` to the agent instead of the plain string — so the value\n * never enters the LLM conversation. The TUI may also mask input\n * accordingly. See `secret-vault.ts`.\n */\n sensitive?: boolean;\n}\n\n/** Map of question id → answer (string for single/text, string[] for multi). */\nexport type AskAnswers = Record<string, string | string[]>;\n\n/** A pending wizard_ask request held by the store. */\nexport interface PendingQuestion {\n id: string;\n questions: AskQuestion[];\n /** Skill id of the caller. Set by the wizard from session.skillId. */\n source: string;\n}\n\n/**\n * PostHog dashboard URL emitted by the agent during a program run.\n * Populated via the `[DASHBOARD_URL]` text marker in agent assistant messages\n * — see `handleSDKMessage` in `agent/agent-interface.ts`. Read by programs\n * (e.g. events-audit) inside `buildOutroData` to surface a dashboard link\n * the agent actually created.\n */\n\nexport interface WizardSession {\n // From CLI args\n debug: boolean;\n forceInstall: boolean;\n installDir: string;\n ci: boolean;\n signup: boolean;\n localMcp: boolean;\n mcpFeatures?: string[];\n apiKey?: string;\n email?: string;\n region?: CloudRegion;\n menu: boolean;\n benchmark: boolean;\n yaraReport: boolean;\n projectId?: number;\n noTelemetry: boolean;\n\n // From detection + screens\n setupConfirmed: boolean;\n integration: Integration | null;\n frameworkContext: Record<string, unknown>;\n typescript: boolean;\n\n /** Human-readable label for the detected framework variant (e.g., \"Django with Wagtail CMS\") */\n detectedFrameworkLabel: string | null;\n\n /** True once framework detection has run (whether it found something or not) */\n detectionComplete: boolean;\n\n /** Set when the detected framework version is too old for the wizard */\n unsupportedVersion: {\n current: string;\n minimum: string;\n docsUrl: string;\n } | null;\n\n // From OAuth\n credentials: Credentials | null;\n\n /**\n * `role_at_organization` from `/api/users/@me/`. Null when the upstream\n * value is missing (older accounts, fresh signups before onboarding).\n * Drives role-tailored MCP prompt suggestions on the McpSuggestedPromptsScreen.\n *\n * Mirrors `apiUser?.role_at_organization` — kept as a top-level convenience\n * because it has dedicated UI semantics (role-tailored kits) and pre-dates\n * the broader `apiUser` plumbing.\n */\n roleAtOrganization: string | null;\n\n /**\n * Full user payload from `/api/users/@me/` — identifiers, profile,\n * current team + organization, preferences, etc. Null until OAuth /\n * CI-key auth populates it. Schema lives in `src/lib/api.ts` and\n * passes through unknown upstream fields so downstream features can\n * read account context (plan, org name, email, etc.) without\n * re-fetching.\n */\n apiUser: ApiUser | null;\n\n // Lifecycle\n runPhase: RunPhase;\n loginUrl: string | null;\n // Direct PostHog authorize URL, shown in the manual-paste modal for\n // headless/remote shells (the localhost loginUrl is unreachable there).\n authorizeUrl: string | null;\n\n // Feature discovery\n discoveredFeatures: DiscoveredFeature[];\n llmOptIn: boolean;\n\n // ScreenId completion\n mcpComplete: boolean;\n mcpOutcome: McpOutcome | null;\n mcpInstalledClients: string[];\n mcpSuggestedPromptsDismissed: boolean;\n skillsComplete: boolean;\n outroDismissed: boolean;\n\n // Runtime\n readinessResult: WizardReadinessResult | null;\n outageDismissed: boolean;\n settingsOverrideKeys: string[] | null;\n settingsConflicts: SettingsConflict[] | null;\n authErrorDetail: {\n hasSettingsConflict: boolean;\n logFilePath: string;\n } | null;\n portConflictProcess: {\n command: string;\n pid: string;\n port: number;\n user: string;\n } | null;\n outroData: OutroData | null;\n dashboardUrl: string | null;\n\n // Additional features queue (drained via stop hook after main integration)\n additionalFeatureQueue: AdditionalFeature[];\n\n // Program metadata (set by runWizard in bin.ts)\n programLabel: string | null;\n skillId: string | null;\n\n // Resolved framework config (set after integration is known)\n frameworkConfig: FrameworkConfig | null;\n\n /** Active wizard_ask request, set by the bridge when the agent calls the tool. */\n pendingQuestion: PendingQuestion | null;\n}\n\n/**\n * Build a WizardSession from CLI args, pre-populating whatever is known.\n */\nexport function buildSession(args: {\n debug?: boolean;\n forceInstall?: boolean;\n installDir?: string;\n ci?: boolean;\n signup?: boolean;\n localMcp?: boolean;\n mcpFeatures?: string[];\n apiKey?: string;\n email?: string;\n region?: CloudRegion;\n menu?: boolean;\n integration?: Integration;\n benchmark?: boolean;\n yaraReport?: boolean;\n projectId?: string;\n noTelemetry?: boolean;\n}): WizardSession {\n return {\n debug: args.debug ?? false,\n forceInstall: args.forceInstall ?? false,\n installDir: args.installDir ?? process.cwd(),\n ci: args.ci ?? false,\n signup: args.signup ?? false,\n localMcp: args.localMcp ?? false,\n mcpFeatures: args.mcpFeatures,\n apiKey: args.apiKey,\n email: args.email,\n region: args.region,\n menu: args.menu ?? false,\n benchmark: args.benchmark ?? false,\n yaraReport: args.yaraReport ?? false,\n projectId: parseProjectIdArg(args.projectId),\n noTelemetry: args.noTelemetry ?? false,\n\n setupConfirmed: false,\n integration: args.integration ?? null,\n frameworkContext: {},\n typescript: false,\n detectedFrameworkLabel: null,\n detectionComplete: false,\n unsupportedVersion: null,\n\n runPhase: RunPhase.Idle,\n discoveredFeatures: [],\n llmOptIn: false,\n mcpComplete: false,\n mcpOutcome: null,\n mcpInstalledClients: [],\n mcpSuggestedPromptsDismissed: false,\n skillsComplete: false,\n outroDismissed: false,\n loginUrl: null,\n authorizeUrl: null,\n credentials: null,\n roleAtOrganization: null,\n apiUser: null,\n readinessResult: null,\n outageDismissed: false,\n settingsOverrideKeys: null,\n settingsConflicts: null,\n authErrorDetail: null,\n portConflictProcess: null,\n outroData: null,\n dashboardUrl: null,\n additionalFeatureQueue: [],\n programLabel: null,\n skillId: null,\n frameworkConfig: null,\n pendingQuestion: null,\n };\n}\n"],"mappings":";AAyBA,SAAS,kBAAkB,OAA+C;AACxE,KAAI,UAAU,KAAA,KAAa,UAAU,GAAI,QAAO,KAAA;CAChD,MAAM,IAAI,OAAO,MAAM;AACvB,QAAO,OAAO,UAAU,EAAE,IAAI,IAAI,IAAI,IAAI,KAAA;;;AAM5C,IAAY,WAAL,yBAAA,UAAA;;AAEL,UAAA,UAAA;;AAEA,UAAA,aAAA;;AAEA,UAAA,eAAA;;AAEA,UAAA,WAAA;;KACD;;AAcD,MAAa,4BAA+D,GAAA,QACjD,iBAC1B;;AAGD,MAAa,6BAAgE,GAAA,QAClD,oRAC1B;;;;AA4LD,SAAgB,aAAa,MAiBX;AAChB,QAAO;EACL,OAAO,KAAK,SAAS;EACrB,cAAc,KAAK,gBAAgB;EACnC,YAAY,KAAK,cAAc,QAAQ,KAAK;EAC5C,IAAI,KAAK,MAAM;EACf,QAAQ,KAAK,UAAU;EACvB,UAAU,KAAK,YAAY;EAC3B,aAAa,KAAK;EAClB,QAAQ,KAAK;EACb,OAAO,KAAK;EACZ,QAAQ,KAAK;EACb,MAAM,KAAK,QAAQ;EACnB,WAAW,KAAK,aAAa;EAC7B,YAAY,KAAK,cAAc;EAC/B,WAAW,kBAAkB,KAAK,UAAU;EAC5C,aAAa,KAAK,eAAe;EAEjC,gBAAgB;EAChB,aAAa,KAAK,eAAe;EACjC,kBAAkB,EAAE;EACpB,YAAY;EACZ,wBAAwB;EACxB,mBAAmB;EACnB,oBAAoB;EAEpB,UAAA;EACA,oBAAoB,EAAE;EACtB,UAAU;EACV,aAAa;EACb,YAAY;EACZ,qBAAqB,EAAE;EACvB,8BAA8B;EAC9B,gBAAgB;EAChB,gBAAgB;EAChB,UAAU;EACV,cAAc;EACd,aAAa;EACb,oBAAoB;EACpB,SAAS;EACT,iBAAiB;EACjB,iBAAiB;EACjB,sBAAsB;EACtB,mBAAmB;EACnB,iBAAiB;EACjB,qBAAqB;EACrB,WAAW;EACX,cAAc;EACd,wBAAwB,EAAE;EAC1B,cAAc;EACd,SAAS;EACT,iBAAiB;EACjB,iBAAiB;EAClB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wizard-ui-YdGFRyu_.js","names":[],"sources":["../src/ui/wizard-ui.ts"],"sourcesContent":["/**\n * WizardUI — abstraction layer for all user-facing operations.\n *\n * Business logic calls `getUI()` instead of importing the store directly.\n * Implementations: InkUI (TUI), LoggingUI (CI).\n *\n * No prompt methods — the TUI screens own all user input.\n * Session-mutating methods trigger reactive screen resolution in the TUI.\n */\n\nimport type { SettingsConflict } from '@lib/agent/agent-interface';\nimport type { WizardReadinessResult } from '@lib/health-checks/readiness';\nimport type {\n AskAnswers,\n OutroData,\n PendingQuestion,\n} from '@lib/wizard-session';\n\nexport enum TaskStatus {\n Pending = 'pending',\n InProgress = 'in_progress',\n Completed = 'completed',\n}\n\nexport function isTaskStatus(value: string): value is TaskStatus {\n return (Object.values(TaskStatus) as string[]).includes(value);\n}\n\nexport interface SpinnerHandle {\n start(message?: string): void;\n stop(message?: string): void;\n message(msg?: string): void;\n}\n\n/**\n * Context passed to `showAuthError` so the screen can pick the right copy.\n *\n * `hasSettingsConflict` is true when a Claude Code settings.json /\n * managed-settings file actually overrides the LLM Gateway auth — the\n * Wizard's pre-flight check missed it or it appeared after startup.\n * When false, the 401 has a different cause (bad PAT prefix, missing\n * scope, expired key, region mismatch) and we should not advise the\n * user to log out of Claude Code.\n */\nexport interface AuthErrorDetail {\n hasSettingsConflict: boolean;\n logFilePath: string;\n}\n\nexport interface WizardUI {\n // ── Lifecycle messages ────────────────────────────────────────────\n intro(message: string): void;\n /** Success outro with a plain text message. */\n outro(message: string): void;\n /**\n * Error outro. Sets structured outroData and transitions run phase so\n * the router advances to the outro screen. Use for abort/failure paths\n * that need a custom error render — do NOT build the outroData by\n * mutating session directly (nanostore holds a shallow copy).\n */\n outroError(data: OutroData): void;\n /** Resolves when the user dismisses the outro screen (presses any key).\n * Lets the abort path wait for the user to read the error before the\n * process exits. Resolves immediately in non-TUI environments. */\n waitForOutroDismissed(): Promise<void>;\n cancel(message: string): void;\n\n // ── Logging ───────────────────────────────────────────────────────\n log: {\n info(message: string): void;\n warn(message: string): void;\n error(message: string): void;\n success(message: string): void;\n step(message: string): void;\n };\n\n note(message: string): void;\n pushStatus(message: string): void;\n\n // ── Spinner ───────────────────────────────────────────────────────\n spinner(): SpinnerHandle;\n\n // ── Session state (triggers reactive screen resolution in TUI) ────\n /** Signal that the main work (agent run) has started. */\n startRun(): void;\n\n /** Store OAuth/API credentials. Resolves past AuthScreen in TUI. */\n setCredentials(credentials: {\n accessToken: string;\n projectApiKey: string;\n host: string;\n projectId: number;\n }): void;\n\n /** Show blocking service outage (pushes outage overlay in TUI). Blocks until dismissed. */\n showBlockingOutage(result: WizardReadinessResult): Promise<void>;\n\n /** Store non-blocking readiness warnings (shown as Health tab in RunScreen). */\n setReadinessWarnings(result: WizardReadinessResult): void;\n\n /** Warn that another process is blocking the OAuth port (pushes overlay in TUI). */\n showPortConflict(processInfo: {\n command: string;\n pid: string;\n port: number;\n user: string;\n }): Promise<void>;\n\n showSettingsOverride(\n conflicts: SettingsConflict[],\n backupAndFix: () => boolean,\n ): Promise<void>;\n\n /** Show auth error overlay when Anthropic API returns 401. */\n showAuthError(detail?: AuthErrorDetail): void;\n\n /**\n * Open the wizard_ask overlay and resolve with the user's answers.\n * Implementations that can't ask (CI/logging) reject so the bridge can\n * surface a clear \"not available\" error to the agent.\n */\n requestQuestion(question: PendingQuestion): Promise<AskAnswers>;\n\n // ── Display state ──────────────────────────────────────────────────\n /** Set the detected framework label (e.g., \"Django with Wagtail CMS\") */\n setDetectedFramework(label: string): void;\n\n /** Register a callback to run when the TUI transitions onto the given screen. */\n onEnterScreen(screen: string, fn: () => void): void;\n\n setLoginUrl(url: string | null): void;\n\n // ── Task tracking from SDK TaskCreate/TaskUpdate events ───────────\n // Receives the full materialised task list each call. The caller (agent\n // loop) maintains a Map<taskId, …> from incremental Task* events and\n // re-emits the snapshot here, preserving the existing store semantics.\n syncTodos(\n todos: Array<{ content: string; status: string; activeForm?: string }>,\n ): void;\n\n // ── Event plan from .posthog-events.json ────────────────────\n setEventPlan(events: Array<{ name: string; description: string }>): void;\n\n // ── Dashboard URL emitted by the agent via [DASHBOARD_URL] marker ──\n setDashboardUrl(url: string): void;\n\n // ── Generic frameworkContext setter for program file watchers ─────\n setFrameworkContext(key: string, value: unknown): void;\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"wizard-ui-YdGFRyu_.js","names":[],"sources":["../src/ui/wizard-ui.ts"],"sourcesContent":["/**\n * WizardUI — abstraction layer for all user-facing operations.\n *\n * Business logic calls `getUI()` instead of importing the store directly.\n * Implementations: InkUI (TUI), LoggingUI (CI).\n *\n * No prompt methods — the TUI screens own all user input.\n * Session-mutating methods trigger reactive screen resolution in the TUI.\n */\n\nimport type { SettingsConflict } from '@lib/agent/agent-interface';\nimport type { WizardReadinessResult } from '@lib/health-checks/readiness';\nimport type { ApiUser } from '@lib/api';\nimport type {\n AskAnswers,\n OutroData,\n PendingQuestion,\n} from '@lib/wizard-session';\n\nexport enum TaskStatus {\n Pending = 'pending',\n InProgress = 'in_progress',\n Completed = 'completed',\n}\n\nexport function isTaskStatus(value: string): value is TaskStatus {\n return (Object.values(TaskStatus) as string[]).includes(value);\n}\n\nexport interface SpinnerHandle {\n start(message?: string): void;\n stop(message?: string): void;\n message(msg?: string): void;\n}\n\n/**\n * Context passed to `showAuthError` so the screen can pick the right copy.\n *\n * `hasSettingsConflict` is true when a Claude Code settings.json /\n * managed-settings file actually overrides the LLM Gateway auth — the\n * Wizard's pre-flight check missed it or it appeared after startup.\n * When false, the 401 has a different cause (bad PAT prefix, missing\n * scope, expired key, region mismatch) and we should not advise the\n * user to log out of Claude Code.\n */\nexport interface AuthErrorDetail {\n hasSettingsConflict: boolean;\n logFilePath: string;\n}\n\nexport interface WizardUI {\n // ── Lifecycle messages ────────────────────────────────────────────\n intro(message: string): void;\n /** Success outro with a plain text message. */\n outro(message: string): void;\n /**\n * Error outro. Sets structured outroData and transitions run phase so\n * the router advances to the outro screen. Use for abort/failure paths\n * that need a custom error render — do NOT build the outroData by\n * mutating session directly (nanostore holds a shallow copy).\n */\n outroError(data: OutroData): void;\n /** Resolves when the user dismisses the outro screen (presses any key).\n * Lets the abort path wait for the user to read the error before the\n * process exits. Resolves immediately in non-TUI environments. */\n waitForOutroDismissed(): Promise<void>;\n cancel(message: string): void;\n\n // ── Logging ───────────────────────────────────────────────────────\n log: {\n info(message: string): void;\n warn(message: string): void;\n error(message: string): void;\n success(message: string): void;\n step(message: string): void;\n };\n\n note(message: string): void;\n pushStatus(message: string): void;\n\n // ── Spinner ───────────────────────────────────────────────────────\n spinner(): SpinnerHandle;\n\n // ── Session state (triggers reactive screen resolution in TUI) ────\n /** Signal that the main work (agent run) has started. */\n startRun(): void;\n\n /** Store OAuth/API credentials. Resolves past AuthScreen in TUI. */\n setCredentials(credentials: {\n accessToken: string;\n projectApiKey: string;\n host: string;\n projectId: number;\n }): void;\n\n /**\n * Persist the user's `role_at_organization` once it's been fetched from\n * `/api/users/@me/`. Drives role-tailored prompt suggestions on the\n * McpSuggestedPromptsScreen. Pass `null` to clear / when unknown.\n */\n setRoleAtOrganization(role: string | null): void;\n\n /**\n * Persist the full user payload from `/api/users/@me/` so downstream\n * screens can read account context (current org, team, plan, email,\n * preferences, etc.) without re-fetching. Pass `null` to clear or\n * when the request failed.\n */\n setApiUser(user: ApiUser | null): void;\n\n /** Show blocking service outage (pushes outage overlay in TUI). Blocks until dismissed. */\n showBlockingOutage(result: WizardReadinessResult): Promise<void>;\n\n /** Store non-blocking readiness warnings (shown as Health tab in RunScreen). */\n setReadinessWarnings(result: WizardReadinessResult): void;\n\n /** Warn that another process is blocking the OAuth port (pushes overlay in TUI). */\n showPortConflict(processInfo: {\n command: string;\n pid: string;\n port: number;\n user: string;\n }): Promise<void>;\n\n /**\n * Resolve with an OAuth authorization code the user enters by hand — the\n * fallback for headless/remote shells where the browser can't reach the\n * local callback server. The OAuth flow races this against the callback\n * server. Implementations that can't prompt (CI/logging) never resolve.\n */\n waitForManualAuthCode(): Promise<string>;\n\n showSettingsOverride(\n conflicts: SettingsConflict[],\n backupAndFix: () => boolean,\n ): Promise<void>;\n\n /** Show auth error overlay when Anthropic API returns 401. */\n showAuthError(detail?: AuthErrorDetail): void;\n\n /**\n * Open the wizard_ask overlay and resolve with the user's answers.\n * Implementations that can't ask (CI/logging) reject so the bridge can\n * surface a clear \"not available\" error to the agent.\n */\n requestQuestion(question: PendingQuestion): Promise<AskAnswers>;\n\n // ── Display state ──────────────────────────────────────────────────\n /** Set the detected framework label (e.g., \"Django with Wagtail CMS\") */\n setDetectedFramework(label: string): void;\n\n /** Register a callback to run when the TUI transitions onto the given screen. */\n onEnterScreen(screen: string, fn: () => void): void;\n\n setLoginUrl(url: string | null): void;\n\n /** Direct PostHog authorize URL, shown in the manual-paste modal. */\n setAuthorizeUrl(url: string | null): void;\n\n // ── Task tracking from SDK TaskCreate/TaskUpdate events ───────────\n // Receives the full materialised task list each call. The caller (agent\n // loop) maintains a Map<taskId, …> from incremental Task* events and\n // re-emits the snapshot here, preserving the existing store semantics.\n syncTodos(\n todos: Array<{ content: string; status: string; activeForm?: string }>,\n ): void;\n\n // ── Event plan from .posthog-events.json ────────────────────\n setEventPlan(events: Array<{ name: string; description: string }>): void;\n\n // ── Dashboard URL emitted by the agent via [DASHBOARD_URL] marker ──\n setDashboardUrl(url: string): void;\n\n // ── Generic frameworkContext setter for program file watchers ─────\n setFrameworkContext(key: string, value: unknown): void;\n}\n"],"mappings":";AAmBA,IAAY,aAAL,yBAAA,YAAA;AACL,YAAA,aAAA;AACA,YAAA,gBAAA;AACA,YAAA,eAAA;;KACD;AAED,SAAgB,aAAa,OAAoC;AAC/D,QAAQ,OAAO,OAAO,WAAW,CAAc,SAAS,MAAM"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@posthog/wizard",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.16.0",
|
|
4
4
|
"homepage": "https://github.com/PostHog/wizard",
|
|
5
5
|
"repository": "https://github.com/PostHog/wizard",
|
|
6
6
|
"description": "The PostHog wizard helps you to configure your project",
|
|
@@ -159,9 +159,10 @@
|
|
|
159
159
|
"prebuild": "pnpm clean && node scripts/generate-version.cjs",
|
|
160
160
|
"build:watch": "tsdown --watch",
|
|
161
161
|
"build": "tsdown",
|
|
162
|
+
"build:ci": "WIZARD_BUILD_NODE_ENV=ci pnpm build",
|
|
162
163
|
"typecheck": "tsc --noEmit",
|
|
163
164
|
"postbuild": "chmod +x ./dist/bin.js && cp -r scripts/** dist && pnpm test:smoke",
|
|
164
|
-
"test:smoke": "
|
|
165
|
+
"test:smoke": "bash ./scripts/smoke-test.sh",
|
|
165
166
|
"lint": "pnpm lint:prettier && pnpm lint:eslint",
|
|
166
167
|
"lint:prettier": "prettier --check \"{lib,src,test}/**/*.ts\"",
|
|
167
168
|
"lint:eslint": "eslint . --cache --format stylish",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"TextBlock-DEHERFec.js","names":[],"sources":["../src/lib/programs/shared/health-check-step.ts","../src/ui/tui/styles.ts","../src/ui/tui/primitives/text-helpers.ts","../src/ui/tui/primitives/content-types.ts","../src/ui/tui/primitives/layout-helpers.ts","../src/ui/tui/primitives/TextBlock.tsx"],"sourcesContent":["/**\n * Shared health-check step used by every program that runs an agent.\n *\n * Renders the HealthCheckScreen between intro and auth, kicks off the\n * readiness probe in onInit, and gates the screen on either a clean\n * readiness result or an explicit user dismissal of the outage.\n *\n * Programs without this step that hit a blocking outage gridlock the\n * router: agent-runner calls wizardAbort, which awaits outroDismissed,\n * but the router can't advance past the still-incomplete auth step to\n * render the OutroScreen.\n */\n\nimport type { ProgramStep } from '@lib/programs/program-step';\nimport type { WizardSession } from '@lib/wizard-session';\nimport {\n evaluateWizardReadiness,\n WizardReadiness,\n SIGNUP_WIZARD_READINESS_CONFIG,\n getBlockingServiceKeys,\n} from '@lib/health-checks/readiness';\n\nexport function healthCheckReady(session: WizardSession): boolean {\n if (!session.readinessResult) return false;\n\n if (session.signup) {\n const hardBlocking = getBlockingServiceKeys(\n session.readinessResult.health,\n SIGNUP_WIZARD_READINESS_CONFIG,\n );\n const defaultBlocking = getBlockingServiceKeys(\n session.readinessResult.health,\n );\n if (hardBlocking.length === 0 && defaultBlocking.length === 0) return true;\n return session.outageDismissed;\n }\n\n if (session.readinessResult.decision === WizardReadiness.No) {\n return session.outageDismissed;\n }\n return true;\n}\n\nexport const HEALTH_CHECK_STEP: ProgramStep = {\n id: 'health-check',\n label: 'Health check',\n screenId: 'health-check',\n gate: healthCheckReady,\n onInit: (ctx) => {\n evaluateWizardReadiness()\n .then((readiness) => {\n ctx.setReadinessResult(readiness);\n })\n .catch(() => {\n ctx.setReadinessResult({\n decision: WizardReadiness.Yes,\n health: {} as never,\n reasons: [],\n });\n });\n },\n};\n","/**\n * Shared style constants for TUI layout primitives.\n */\n\nexport enum HAlign {\n Left = 'flex-start',\n Center = 'center',\n Right = 'flex-end',\n}\n\nexport enum VAlign {\n Top = 'flex-start',\n Center = 'center',\n Bottom = 'flex-end',\n}\n\nexport const Colors = {\n primary: 'cyan',\n accent: '#DC9300',\n titleColor: '#3D2800',\n success: 'green',\n error: 'red',\n muted: 'gray',\n} as const;\n\nexport const Icons = {\n diamond: '\\u25C6',\n diamondOpen: '\\u25C7',\n check: '\\u2714',\n warning: '\\u26A0',\n squareFilled: '\\u25FC',\n squareOpen: '\\u25FB',\n triangleRight: '\\u25B6',\n triangleSmallRight: '\\u25B8',\n bullet: '\\u2022',\n} as const;\n","/**\n * Text-splitting helpers for sentence boundary detection.\n * Used by TextBlock for animation pauses at punctuation.\n */\n\n/** Split text into sentences (keeps the delimiter attached) */\nexport function splitSentences(text: string): string[] {\n const parts: string[] = [];\n const re = /[^.!?]*[.!?]+\\s*/g;\n let match: RegExpExecArray | null;\n let lastIndex = 0;\n while ((match = re.exec(text)) !== null) {\n parts.push(match[0]);\n lastIndex = re.lastIndex;\n }\n if (lastIndex < text.length) {\n parts.push(text.slice(lastIndex));\n }\n return parts;\n}\n\n/** Build a set of character indices where sentences end (for typewriter pause) */\nexport function sentenceEndChars(text: string): Set<number> {\n const ends = new Set<number>();\n const sentences = splitSentences(text);\n let pos = 0;\n for (const s of sentences) {\n pos += s.length;\n ends.add(pos - 1);\n }\n return ends;\n}\n\n/** Build a set of word indices where sentences end (for word-by-word pause) */\nexport function sentenceEndWords(text: string): Set<number> {\n const ends = new Set<number>();\n const sentences = splitSentences(text);\n let wordCount = 0;\n for (const s of sentences) {\n const words = s.trim().split(/\\s+/).filter(Boolean);\n wordCount += words.length;\n ends.add(wordCount - 1);\n }\n return ends;\n}\n","/**\n * Content block types and type guards.\n *\n * Extracted from ContentSequencer so that pure-logic modules (like\n * layout-helpers) can import them without pulling in Ink/React.\n */\n\nimport type { ReactNode } from 'react';\nimport type { TextRevealMode } from './TextBlock.js';\n\n/** Object form — string or ReactNode content with per-block overrides. */\nexport interface ContentObjectBlock {\n content: string | ReactNode;\n mode?: TextRevealMode;\n animationInterval?: number;\n sentenceInterval?: number;\n pause?: number;\n persist?: boolean;\n}\n\n/** Lines block — reveals ReactNode lines one at a time. */\nexport interface ContentLinesBlock {\n type: 'lines';\n lines: ReactNode[];\n interval?: number;\n pause?: number;\n}\n\n/** Clear block — page break that hides all prior blocks. */\nexport interface ContentClearBlock {\n type: 'clear';\n pause?: number;\n}\n\n/** A content block in the sequence. Bare strings are sugar for { content: '...' }. */\nexport type ContentBlock =\n | string\n | ContentObjectBlock\n | ContentLinesBlock\n | ContentClearBlock;\n\n/** Type guard for lines blocks. */\nexport function isLinesBlock(block: ContentBlock): block is ContentLinesBlock {\n return typeof block !== 'string' && 'type' in block && block.type === 'lines';\n}\n\n/** Type guard for clear blocks. */\nexport function isClearBlock(block: ContentBlock): block is ContentClearBlock {\n return typeof block !== 'string' && 'type' in block && block.type === 'clear';\n}\n\n/** Type guard for object blocks (text or node content). */\nexport function isObjectBlock(\n block: ContentBlock,\n): block is ContentObjectBlock {\n return typeof block !== 'string' && !('type' in block);\n}\n","/**\n * Layout helpers — pure functions for height estimation and viewport eviction.\n *\n * These are the core of the responsive content system. They estimate how many\n * terminal rows a content block will occupy and determine which blocks fit\n * within a given height budget.\n */\n\nimport type { ContentBlock } from './content-types.js';\nimport { isLinesBlock, isClearBlock, isObjectBlock } from './content-types.js';\n\n/**\n * Estimate the number of terminal rows a content block will occupy,\n * including 1 row of marginBottom.\n */\nexport function estimateBlockHeight(\n block: ContentBlock,\n availableWidth: number,\n): number {\n if (typeof block === 'string') {\n return wordWrap(block, availableWidth).length + 1; // +1 for marginBottom\n }\n\n if (isClearBlock(block)) return 0;\n\n if (isLinesBlock(block)) {\n return block.lines.length + 1;\n }\n\n if (isObjectBlock(block)) {\n if (typeof block.content === 'string') {\n return wordWrap(block.content, availableWidth).length + 1;\n }\n return 4; // conservative fixed estimate for ReactNode\n }\n\n return 1;\n}\n\n/**\n * Given all blocks, the active index, available width, and a row budget,\n * return [startIdx, endIdx] — the range of blocks to render.\n *\n * Always includes activeIdx. Walks backward to include as many completed\n * blocks as fit within maxHeight.\n */\nexport function computeVisibleRange(\n blocks: ContentBlock[],\n activeIdx: number,\n availableWidth: number,\n maxHeight: number,\n): [number, number] {\n // Reserve a 2-row buffer so resize-induced estimate drift doesn't\n // cause overflow=\"hidden\" to clip the margin between blocks.\n const budget = Math.max(4, maxHeight - 2);\n\n let totalHeight = estimateBlockHeight(blocks[activeIdx], availableWidth);\n let start = activeIdx;\n\n for (let i = activeIdx - 1; i >= 0; i--) {\n // Clear blocks act as a hard boundary — don't show anything before them\n if (isClearBlock(blocks[i])) break;\n const h = estimateBlockHeight(blocks[i], availableWidth);\n if (totalHeight + h > budget) break;\n totalHeight += h;\n start = i;\n }\n\n return [start, activeIdx];\n}\n\n/**\n * Word-wrap text at clean word boundaries. Always returns pre-wrapped text\n * joined with \\n — this avoids Ink's native wrap which can leave leading\n * spaces on continuation lines.\n *\n * Uses a 1-char safety margin so slight width estimate mismatches don't\n * cause Ink to re-wrap our already-wrapped lines.\n */\nexport function wordWrap(text: string, availableWidth: number): string[] {\n const safeWidth = Math.max(10, availableWidth - 1);\n const words = text.split(/\\s+/);\n const lines: string[] = [];\n let currentLine = '';\n\n for (const word of words) {\n if (\n currentLine.length + word.length + 1 > safeWidth &&\n currentLine.length > 0\n ) {\n lines.push(currentLine);\n currentLine = word;\n } else {\n currentLine += (currentLine.length > 0 ? ' ' : '') + word;\n }\n }\n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n\n return lines;\n}\n\n/**\n * Word-wrap text and return only the last `maxRows` lines.\n * Used for intra-block truncation when a single text block exceeds the viewport.\n * Also used for normal rendering to avoid Ink's leading-space wrap artifacts.\n */\nexport function wrapAndTruncate(\n text: string,\n availableWidth: number,\n maxRows: number,\n): string {\n const lines = wordWrap(text, availableWidth);\n\n if (lines.length <= maxRows) {\n return lines.join('\\n');\n }\n\n return lines.slice(-maxRows).join('\\n');\n}\n","/**\n * TextBlock — Animates a single string paragraph.\n *\n * Self-contained: owns its own animIdx and timer.\n * Calls onComplete() when the animation finishes.\n *\n * Five animation modes:\n * 1. Typewriter — character-by-character reveal\n * 2. Word by word — each word appears in order\n * 3. Sentence by sentence — sentences appear one at a time\n * 4. Paragraph fade — paragraph appears at full opacity immediately\n * 5. Sentence fade — paragraph dim, sentences light up in order\n */\n\nimport { Text } from 'ink';\nimport { useState, useEffect, useRef, useMemo, type ReactNode } from 'react';\nimport { Colors } from '@ui/tui/styles';\nimport {\n splitSentences,\n sentenceEndChars,\n sentenceEndWords,\n} from './text-helpers.js';\nimport { wrapAndTruncate } from './layout-helpers.js';\n\nexport enum TextRevealMode {\n Typewriter = 0,\n WordByWord = 1,\n SentenceBySentence = 2,\n ParagraphFade = 3,\n SentenceFade = 4,\n}\n\nexport const TEXT_REVEAL_MODE_LABELS = [\n 'Typewriter',\n 'Word by word',\n 'Sentence by sentence',\n 'Paragraph fade',\n 'Sentence fade',\n];\n\nexport const TEXT_REVEAL_MODE_COUNT = 5;\n\n/** Default interval per mode (ms) */\nexport const TEXT_REVEAL_MODE_DEFAULTS: Record<TextRevealMode, number> = {\n [TextRevealMode.WordByWord]: 240,\n [TextRevealMode.Typewriter]: 32,\n [TextRevealMode.SentenceBySentence]: 1800,\n [TextRevealMode.ParagraphFade]: 4800,\n [TextRevealMode.SentenceFade]: 2400,\n};\n\ninterface TextBlockProps {\n text: string;\n active: boolean;\n completed: boolean;\n onComplete: () => void;\n mode: TextRevealMode;\n bullet?: ReactNode;\n animationInterval?: number;\n sentenceInterval?: number;\n /** Max rows this block may occupy. When exceeded, top lines are truncated. */\n maxHeight?: number;\n /** Available text width in columns (for truncation wrapping). */\n availableWidth?: number;\n}\n\nexport const TextBlock = ({\n text,\n active,\n completed,\n onComplete,\n mode,\n bullet,\n animationInterval,\n sentenceInterval = 1600,\n maxHeight,\n availableWidth,\n}: TextBlockProps) => {\n const speed = animationInterval ?? TEXT_REVEAL_MODE_DEFAULTS[mode];\n\n const [animIdx, setAnimIdx] = useState(\n mode === TextRevealMode.SentenceFade ? 1 : 0,\n );\n\n // Reset synchronously during render to avoid a one-frame flash\n const resetRef = useRef(0);\n const prevMode = useRef(mode);\n if (prevMode.current !== mode) {\n prevMode.current = mode;\n resetRef.current += 1;\n setAnimIdx(mode === TextRevealMode.SentenceFade ? 1 : 0);\n }\n\n const words = text.split(/\\s+/);\n const sentences = splitSentences(text);\n\n const sentenceCharEnds = useMemo(() => sentenceEndChars(text), [text]);\n const sentenceWordEnds = useMemo(() => sentenceEndWords(text), [text]);\n\n const isDone =\n mode === TextRevealMode.Typewriter\n ? animIdx >= text.length\n : mode === TextRevealMode.ParagraphFade\n ? true\n : mode === TextRevealMode.WordByWord\n ? animIdx >= words.length\n : mode === TextRevealMode.SentenceFade ||\n mode === TextRevealMode.SentenceBySentence\n ? animIdx >= sentences.length\n : true;\n\n // Fire onComplete when done\n useEffect(() => {\n if (isDone && active) onComplete();\n }, [isDone, active, onComplete]);\n\n // Animate: single effect for all tick-based modes\n useEffect(() => {\n if (!active || mode === TextRevealMode.ParagraphFade || isDone) return;\n const token = resetRef.current;\n\n const isFirstTick = animIdx === 0;\n\n let delay = isFirstTick ? 0 : speed;\n if (\n !isFirstTick &&\n mode === TextRevealMode.Typewriter &&\n animIdx > 0 &&\n sentenceCharEnds.has(animIdx - 1)\n ) {\n delay = sentenceInterval;\n } else if (\n !isFirstTick &&\n mode === TextRevealMode.WordByWord &&\n animIdx > 0 &&\n sentenceWordEnds.has(animIdx - 1)\n ) {\n delay = sentenceInterval;\n }\n\n const timer = setTimeout(() => {\n if (token !== resetRef.current) return;\n setAnimIdx((c) => c + 1);\n }, delay);\n return () => clearTimeout(timer);\n }, [\n active,\n mode,\n animIdx,\n isDone,\n speed,\n sentenceInterval,\n sentenceCharEnds,\n sentenceWordEnds,\n ]);\n\n // Pre-wrap text ourselves to avoid Ink's native wrap leaving leading spaces\n // on continuation lines. When maxHeight is set, also truncates to last N rows.\n const wrap = (visibleText: string): string => {\n if (availableWidth == null) return visibleText;\n if (maxHeight == null) {\n return wrapAndTruncate(visibleText, availableWidth, Infinity);\n }\n return wrapAndTruncate(visibleText, availableWidth, maxHeight);\n };\n\n // Completed: dimmed text\n if (completed) {\n return (\n <Text dimColor>\n {bullet}\n {wrap(text)}\n </Text>\n );\n }\n\n // Active: mode-specific rendering\n if (mode === TextRevealMode.Typewriter) {\n const revealed = text.slice(0, animIdx);\n const atSentenceEnd = /[.!?]\\s*$/.test(revealed);\n const display = atSentenceEnd ? revealed.trimEnd() : revealed;\n return (\n <Text>\n {bullet}\n {wrap(display)}\n <Text color={Colors.muted}>{'\\u258C'}</Text>\n </Text>\n );\n }\n\n if (mode === TextRevealMode.WordByWord) {\n const visible = words.slice(0, animIdx).join(' ');\n return (\n <Text>\n {bullet}\n {wrap(visible)}\n </Text>\n );\n }\n\n if (mode === TextRevealMode.ParagraphFade) {\n return (\n <Text>\n {bullet}\n {wrap(text)}\n </Text>\n );\n }\n\n if (mode === TextRevealMode.SentenceBySentence) {\n const visible = sentences.slice(0, animIdx).join('');\n return (\n <Text>\n {bullet}\n {wrap(visible)}\n </Text>\n );\n }\n\n // SentenceFade\n return (\n <Text>\n {bullet}\n {sentences.map((s, si) => (\n <Text key={si} dimColor={si >= animIdx}>\n {s}\n </Text>\n ))}\n </Text>\n );\n};\n"],"mappings":";;;;;AAsBA,SAAgB,iBAAiB,SAAiC;AAChE,KAAI,CAAC,QAAQ,gBAAiB,QAAO;AAErC,KAAI,QAAQ,QAAQ;EAClB,MAAM,eAAe,uBACnB,QAAQ,gBAAgB,QACxB,+BACD;EACD,MAAM,kBAAkB,uBACtB,Q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