@posthog/wizard 2.57.0 → 2.59.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/dist/{add-mcp-server-to-clients-DWYny51f.js → add-mcp-server-to-clients-OsyI-Bkn.js} +4 -4
- package/dist/{add-mcp-server-to-clients-DWYny51f.js.map → add-mcp-server-to-clients-OsyI-Bkn.js.map} +1 -1
- package/dist/{agent-interface-IhcyCUgQ.js → agent-interface-DB8B9fET.js} +77 -8
- package/dist/agent-interface-DB8B9fET.js.map +1 -0
- package/dist/{agent-prompt-loader-QEyGIPE9.js → agent-prompt-loader-tcJQ-23m.js} +5 -5
- package/dist/{agent-prompt-loader-QEyGIPE9.js.map → agent-prompt-loader-tcJQ-23m.js.map} +1 -1
- package/dist/{agent-runner-CDW7mVZ4.js → agent-runner-2CRvJ1nS.js} +18 -17
- package/dist/{agent-runner-CDW7mVZ4.js.map → agent-runner-2CRvJ1nS.js.map} +1 -1
- package/dist/{analytics-BmiE0b4q.js → analytics-D8LSdEq7.js} +2 -2
- package/dist/{analytics-BmiE0b4q.js.map → analytics-D8LSdEq7.js.map} +1 -1
- package/dist/analytics-fOKMWN6E.js +2 -0
- package/dist/{api--kCd-MRf.js → api-XEopttY8.js} +3 -3
- package/dist/{api--kCd-MRf.js.map → api-XEopttY8.js.map} +1 -1
- package/dist/bin.js +96 -50
- package/dist/bin.js.map +1 -1
- package/dist/{bounded-fs-RsEDeRrP.js → bounded-fs-xzOAybCw.js} +3 -3
- package/dist/{bounded-fs-RsEDeRrP.js.map → bounded-fs-xzOAybCw.js.map} +1 -1
- package/dist/{ci-install-SRdZ4OhM.js → ci-install-hArQ6Imb.js} +4 -4
- package/dist/{ci-install-SRdZ4OhM.js.map → ci-install-hArQ6Imb.js.map} +1 -1
- package/dist/{debug-Cs5Fbwx3.js → debug-BC-RNoVX.js} +1 -1
- package/dist/{debug-l3bYkVA9.js → debug-CxHQG5NZ.js} +5 -3
- package/dist/debug-CxHQG5NZ.js.map +1 -0
- package/dist/{environment-BX5O4Uej.js → environment-D6GAX3yG.js} +4 -4
- package/dist/{environment-BX5O4Uej.js.map → environment-D6GAX3yG.js.map} +1 -1
- package/dist/{file-watcher-BKXpTqdO.js → file-watcher-Bw5wz1_R.js} +2 -2
- package/dist/{file-watcher-BKXpTqdO.js.map → file-watcher-Bw5wz1_R.js.map} +1 -1
- package/dist/{headless-ui-H5sds5fF.js → headless-ui-BGLCn1Dw.js} +5 -2
- package/dist/{headless-ui-H5sds5fF.js.map → headless-ui-BGLCn1Dw.js.map} +1 -1
- package/dist/{interactive-zP7oNtJ6.js → interactive-DRxZ-vOw.js} +2 -2
- package/dist/{interactive-zP7oNtJ6.js.map → interactive-DRxZ-vOw.js.map} +1 -1
- package/dist/{mcp-5Ts84uw0.js → mcp-CRYv_nRt.js} +2 -2
- package/dist/{mcp-5Ts84uw0.js.map → mcp-CRYv_nRt.js.map} +1 -1
- package/dist/{mcp-prompt-streaming-Cs9Sxyrz.js → mcp-prompt-streaming-CO28aq_J.js} +3 -3
- package/dist/{mcp-prompt-streaming-Cs9Sxyrz.js.map → mcp-prompt-streaming-CO28aq_J.js.map} +1 -1
- package/dist/{non-interactive-BL47SIBm.js → non-interactive-xhKZWWgs.js} +2 -2
- package/dist/{non-interactive-BL47SIBm.js.map → non-interactive-xhKZWWgs.js.map} +1 -1
- package/dist/{orchestrator-tools-BpfcJjlz.js → orchestrator-tools-PXqRljoB.js} +3 -3
- package/dist/{orchestrator-tools-BpfcJjlz.js.map → orchestrator-tools-PXqRljoB.js.map} +1 -1
- package/dist/{package-manager-8tumrjdV.js → package-manager-C1HqgtVK.js} +16 -3
- package/dist/{package-manager-8tumrjdV.js.map → package-manager-C1HqgtVK.js.map} +1 -1
- package/dist/{pi-D7QKZ4IT.js → pi-DNkD3usA.js} +11 -11
- package/dist/{pi-D7QKZ4IT.js.map → pi-DNkD3usA.js.map} +1 -1
- package/dist/{playground-wNJgUbxf.js → playground-BChSh0sx.js} +6 -6
- package/dist/{playground-wNJgUbxf.js.map → playground-BChSh0sx.js.map} +1 -1
- package/dist/{posthog-DDLIrku0.js → posthog-B6grWFSr.js} +6 -2
- package/dist/posthog-B6grWFSr.js.map +1 -0
- package/dist/{posthog-integration-B4wOLuEM.js → posthog-integration-D-4mdP4b.js} +24 -41
- package/dist/{posthog-integration-B4wOLuEM.js.map → posthog-integration-D-4mdP4b.js.map} +1 -1
- package/dist/{provisioning-CuDNuYSJ.js → provisioning-C1bETgMf.js} +3 -3
- package/dist/{provisioning-CuDNuYSJ.js.map → provisioning-C1bETgMf.js.map} +1 -1
- package/dist/{queue-tools-DuDCyoOG.js → queue-tools-D2FgGSUY.js} +3 -3
- package/dist/{queue-tools-DuDCyoOG.js.map → queue-tools-D2FgGSUY.js.map} +1 -1
- package/dist/{registry-CwBz0S7O.js → registry-CkGCJVqq.js} +76 -5
- package/dist/{registry-CwBz0S7O.js.map → registry-CkGCJVqq.js.map} +1 -1
- package/dist/{security-DXTPsgKR.js → security-Cb5pp8kB.js} +44 -4
- package/dist/security-Cb5pp8kB.js.map +1 -0
- package/dist/{setup-utils-DOCb_7Ib.js → setup-utils-CcYGniRV.js} +9 -9
- package/dist/{setup-utils-DOCb_7Ib.js.map → setup-utils-CcYGniRV.js.map} +1 -1
- package/dist/{start-tui-CXREjnJj.js → start-tui-BqyCxVie.js} +21 -18
- package/dist/start-tui-BqyCxVie.js.map +1 -0
- package/dist/{steps-BrhxUACc.js → steps-C0bR2Rxg.js} +7 -7
- package/dist/{steps-BrhxUACc.js.map → steps-C0bR2Rxg.js.map} +1 -1
- package/dist/{store-FMLVFTMn.js → store-suEDuCAn.js} +15 -4
- package/dist/store-suEDuCAn.js.map +1 -0
- package/dist/{subagent-BI7hcEfB.js → subagent-Dd4Hu0C5.js} +2 -2
- package/dist/{subagent-BI7hcEfB.js.map → subagent-Dd4Hu0C5.js.map} +1 -1
- package/dist/{task-z832Sfpx.js → task-CpU_54NS.js} +14 -13
- package/dist/task-CpU_54NS.js.map +1 -0
- package/dist/{task-stream-BXJjJ1wq.js → task-stream-C_xfqch0.js} +7 -5
- package/dist/task-stream-C_xfqch0.js.map +1 -0
- package/dist/{tasks-q7aRIZdo.js → tasks-Bfw6gqOO.js} +2 -2
- package/dist/{tasks-q7aRIZdo.js.map → tasks-Bfw6gqOO.js.map} +1 -1
- package/dist/{telemetry-BGm0PRse.js → telemetry-B62x5mwZ.js} +3 -3
- package/dist/{telemetry-BGm0PRse.js.map → telemetry-B62x5mwZ.js.map} +1 -1
- package/dist/{terminal-BY9GL1HK.js → terminal-CQjtfQzy.js} +11 -11
- package/dist/{terminal-BY9GL1HK.js.map → terminal-CQjtfQzy.js.map} +1 -1
- package/dist/{tools-C88_ihfS.js → tools-CzKtKaI1.js} +19 -7
- package/dist/tools-CzKtKaI1.js.map +1 -0
- package/dist/{wizard-abort-DWJ77MGo.js → wizard-abort-DPCzBsvy.js} +1 -1
- package/dist/{wizard-abort-BY5rsRqQ.js → wizard-abort-I6tR10Mx.js} +3 -3
- package/dist/{wizard-abort-BY5rsRqQ.js.map → wizard-abort-I6tR10Mx.js.map} +1 -1
- package/dist/{yara-hooks-CRz1ArdP.js → yara-hooks-CpvNIFdW.js} +4 -4
- package/dist/{yara-hooks-CRz1ArdP.js.map → yara-hooks-CpvNIFdW.js.map} +1 -1
- package/dist/yara-hooks-lnituYce.js +2 -0
- package/package.json +1 -1
- package/dist/agent-interface-IhcyCUgQ.js.map +0 -1
- package/dist/analytics-CTAQuXio.js +0 -2
- package/dist/debug-l3bYkVA9.js.map +0 -1
- package/dist/posthog-DDLIrku0.js.map +0 -1
- package/dist/security-DXTPsgKR.js.map +0 -1
- package/dist/start-tui-CXREjnJj.js.map +0 -1
- package/dist/store-FMLVFTMn.js.map +0 -1
- package/dist/task-stream-BXJjJ1wq.js.map +0 -1
- package/dist/task-z832Sfpx.js.map +0 -1
- package/dist/tools-C88_ihfS.js.map +0 -1
- package/dist/yara-hooks-CPcHyeur.js +0 -2
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { f as getUI } from "./debug-
|
|
2
|
-
import { n as analytics } from "./analytics-
|
|
3
|
-
import { t as withProgress } from "./telemetry-
|
|
4
|
-
import "./bounded-fs-
|
|
5
|
-
import "./setup-utils-
|
|
6
|
-
import "./add-mcp-server-to-clients-
|
|
1
|
+
import { f as getUI } from "./debug-CxHQG5NZ.js";
|
|
2
|
+
import { n as analytics } from "./analytics-D8LSdEq7.js";
|
|
3
|
+
import { t as withProgress } from "./telemetry-B62x5mwZ.js";
|
|
4
|
+
import "./bounded-fs-xzOAybCw.js";
|
|
5
|
+
import "./setup-utils-CcYGniRV.js";
|
|
6
|
+
import "./add-mcp-server-to-clients-OsyI-Bkn.js";
|
|
7
7
|
import * as fs$1 from "fs";
|
|
8
8
|
import * as path$1 from "path";
|
|
9
9
|
import "path";
|
|
@@ -144,4 +144,4 @@ const uploadEnvironmentVariablesStep = async (envVars, { integration, session })
|
|
|
144
144
|
//#endregion
|
|
145
145
|
export { uploadEnvironmentVariablesStep };
|
|
146
146
|
|
|
147
|
-
//# sourceMappingURL=steps-
|
|
147
|
+
//# sourceMappingURL=steps-C0bR2Rxg.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"steps-
|
|
1
|
+
{"version":3,"file":"steps-C0bR2Rxg.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;IAAO;GAC/B,KAAK;IACH,GAAG,QAAQ;IACX,aAAa;IACb,IAAI;IACL;GACF,CAAC;EAEF,MAAM,UACJ,OAAO,OAAO,OAAO,GAAG,OAAO,OAAO,OAAO,EAC7C,aAAa;AAEf,M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,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"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-B_-DWIq7.js";
|
|
2
|
-
import { b as isTaskStatus, s as logToFile, v as getBlockingServiceKeys } from "./debug-
|
|
3
|
-
import { i as sessionProperties, n as analytics } from "./analytics-
|
|
2
|
+
import { b as isTaskStatus, s as logToFile, v as getBlockingServiceKeys } from "./debug-CxHQG5NZ.js";
|
|
3
|
+
import { i as sessionProperties, n as analytics } from "./analytics-D8LSdEq7.js";
|
|
4
4
|
import { a as buildSession } from "./wizard-session-CwgR5y3-.js";
|
|
5
|
-
import { r as computeTokenCostUsd } from "./agent-runner-
|
|
5
|
+
import { r as computeTokenCostUsd } from "./agent-runner-2CRvJ1nS.js";
|
|
6
6
|
import { d as PROGRAM_REGISTRY, f as Program, p as getProgramConfig } from "./bin.js";
|
|
7
7
|
import { atom, map } from "nanostores";
|
|
8
8
|
//#region src/lib/programs/program-step.ts
|
|
@@ -208,6 +208,7 @@ var WizardStore = class {
|
|
|
208
208
|
$statusExpanded = atom(false);
|
|
209
209
|
$tasks = atom([]);
|
|
210
210
|
$eventPlan = atom([]);
|
|
211
|
+
$handoffText = atom(null);
|
|
211
212
|
$learnCardBlockIdx = atom(0);
|
|
212
213
|
$learnCardComplete = atom(false);
|
|
213
214
|
$version = atom(0);
|
|
@@ -364,6 +365,9 @@ var WizardStore = class {
|
|
|
364
365
|
get eventPlan() {
|
|
365
366
|
return this.$eventPlan.get();
|
|
366
367
|
}
|
|
368
|
+
get handoffText() {
|
|
369
|
+
return this.$handoffText.get();
|
|
370
|
+
}
|
|
367
371
|
get currentStage() {
|
|
368
372
|
return this.$currentStage.get();
|
|
369
373
|
}
|
|
@@ -856,6 +860,13 @@ var WizardStore = class {
|
|
|
856
860
|
this.$eventPlan.set(events);
|
|
857
861
|
this.emitChange();
|
|
858
862
|
}
|
|
863
|
+
/** No-op on identical text: an emit here means a network push downstream. */
|
|
864
|
+
setHandoffText(text) {
|
|
865
|
+
if (this.$handoffText.get() === text) return;
|
|
866
|
+
logToFile(`store.setHandoffText: ${text.length} chars`);
|
|
867
|
+
this.$handoffText.set(text);
|
|
868
|
+
this.emitChange();
|
|
869
|
+
}
|
|
859
870
|
get learnCardBlockIdx() {
|
|
860
871
|
return this.$learnCardBlockIdx.get();
|
|
861
872
|
}
|
|
@@ -899,4 +910,4 @@ var WizardStore = class {
|
|
|
899
910
|
//#endregion
|
|
900
911
|
export { store_exports as n, totalTokenCount as r, WizardStore as t };
|
|
901
912
|
|
|
902
|
-
//# sourceMappingURL=store-
|
|
913
|
+
//# sourceMappingURL=store-suEDuCAn.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store-suEDuCAn.js","names":[],"sources":["../src/lib/programs/program-step.ts","../src/lib/programs/ai-opt-in-gate.ts","../src/ui/tui/screen-sequences.ts","../src/ui/tui/router.ts","../src/ui/tui/store.ts"],"sourcesContent":["import type { WizardSession, DiscoveredFeature } from '@lib/wizard-session';\nimport type { WizardReadinessResult } from '@lib/health-checks/readiness';\nimport type { ProgramRun } from '@lib/agent/agent-runner';\nimport type { Integration } from '@lib/constants';\nimport type { FrameworkConfig } from '@lib/framework-config';\nimport type { ContentBlock } from '@ui/tui/primitives/index';\nimport type { WizardStore } from '@ui/tui/store';\nimport type { Tip } from '@ui/tui/components/TipsCard';\n\n/**\n * A program step is the primary unit of the wizard's execution model.\n *\n * It can own:\n * - a screen in the TUI (optional — some steps are headless)\n * - agent work via a program reference (optional — some steps are UI-only)\n * - completion and visibility predicates\n *\n * The PostHog integration program is one ordered list of steps.\n * Other programs (e.g. revenue analytics) register a different step list.\n */\n/**\n * Context passed to onInit callbacks — fires when the TUI starts\n * rendering, before bin.ts has assigned the real session.\n */\nexport interface StoreInitContext {\n readonly session: WizardSession;\n readonly setReadinessResult: (result: WizardReadinessResult | null) => void;\n readonly setFrameworkContext: (key: string, value: unknown) => void;\n readonly emitChange: () => void;\n}\n\n/**\n * Context passed to onReady callbacks — fires after bin.ts has assigned\n * the real session, so reading `session.installDir` returns the target\n * project. Use for async pre-program work like prerequisite detection.\n */\nexport interface ProgramReadyContext {\n readonly session: WizardSession;\n readonly setFrameworkContext: (key: string, value: unknown) => void;\n\n // Detection-specific methods — used by core-integration's detect step\n readonly setFrameworkConfig: (\n integration: Integration,\n config: FrameworkConfig,\n ) => void;\n readonly setDetectedFramework: (label: string) => void;\n readonly setSkillId: (skillId: string | null) => void;\n readonly setUnsupportedVersion: (info: {\n current: string;\n minimum: string;\n docsUrl: string;\n }) => void;\n readonly addDiscoveredFeature: (feature: DiscoveredFeature) => void;\n readonly setDetectionComplete: () => void;\n}\n\nexport interface ProgramStep {\n /** Unique identifier for this step */\n id: string;\n\n /** Human-readable label for progress display */\n label: string;\n\n /**\n * TUI screen this step owns, if any.\n * Matches the ScreenId enum values (e.g. 'intro', 'run', 'outro').\n */\n screenId?: string;\n\n /**\n * For a run step (`screenId: 'run'`): runs this step's own agent. A program\n * exports a self-contained run step and another imports it into its step list\n * — e.g. posthog-integration exports a run step that runs its agent, and\n * self-driving imports it before its own run step. Omit to run the host\n * program's own agent (`config.run`).\n */\n run?: (session: WizardSession) => Promise<void>;\n\n /**\n * For a run step: prepare a derived session before its agent runs — e.g.\n * gather framework context for the chosen project. The session it receives is\n * the run's own, so writes don't leak into later runs.\n */\n onRunPrep?: (session: WizardSession) => Promise<void>;\n\n /**\n * For a run step: the working directory its agent runs in, resolved from the\n * session (e.g. self-driving's integration runs in the picked monorepo\n * sub-app, not the repo root). The runner scopes a derived session to this\n * dir for that run only. Defaults to `session.installDir`.\n */\n targetDir?: (session: WizardSession) => string;\n\n /**\n * Whether this step should be visible in the current program.\n * If omitted, the step is always visible.\n */\n show?: (session: WizardSession) => boolean;\n\n /**\n * Exit condition for the screen. Router advances when true.\n * Defaults to `gate` if unset.\n */\n isComplete?: (session: WizardSession) => boolean;\n\n /**\n * Define a gate if your screen needs to await user interactions.\n * bin.ts can `await store.getGate(stepId)` to pause until the\n * predicate becomes true.\n */\n gate?: (session: WizardSession) => boolean;\n\n /**\n * Called once when the TUI starts rendering, with the default\n * session. Use for session-independent fire-and-forget work that\n * should start as early as possible (e.g. health check kicked off\n * while the user is still reading the intro screen). Never fires for\n * a store that isn't rendering screens (tests, playground).\n */\n onInit?: (ctx: StoreInitContext) => void;\n\n /**\n * Called once after bin.ts has assigned the real session to the store,\n * before any gate is awaited. Awaited in sequence with other steps'\n * onReady callbacks. Use for session-dependent pre-program work like\n * scanning the installDir for prerequisites. May be sync or async.\n */\n onReady?: (ctx: ProgramReadyContext) => void | Promise<void>;\n}\n\n/**\n * Declares a program's place in the wizard CLI surface.\n *\n * Mirrors the `cli:` block in context-mill skill configs so wizard-native\n * programs and skill-backed programs share one vocabulary. Field names\n * match `ProgramConfig.command` / `parentCommand` above, so contributors\n * only learn one set of words.\n *\n * - `role: 'command'` — appears as a normal wizard command.\n * - `role: 'skill'` — reachable only via `wizard skill <id>`.\n * - `role: 'internal'` — hidden everywhere, only reachable via the\n * `--skill=<id>` dev escape hatch.\n *\n * Mapping table — declaration on the left, registered command on the right:\n *\n * { role: 'command', → wizard revenue-analytics\n * command: 'revenue-analytics' }\n *\n * { role: 'command', → wizard audit feature-flags\n * parentCommand: 'audit',\n * command: 'feature-flags' }\n *\n * { role: 'skill' } → wizard skill <id>\n *\n * `cli` only configures the command shape — the verbs the user types.\n * Flags and positional args (e.g. `--since=30d`) are configured on\n * `cliOptions`, not here.\n *\n * Naming rule: commands use the full PostHog product name with hyphens\n * (`revenue-analytics`, `feature-flags`, `session-replay`), not\n * abbreviations like `revenue` or `flags`.\n */\nexport interface ProgramCliSurface {\n /** Where the program appears in the wizard CLI surface. */\n role: 'command' | 'skill' | 'internal';\n /**\n * The user-typed word that registers this program (e.g. `'feature-flags'`\n * in `wizard audit feature-flags`, or `'revenue-analytics'` in\n * `wizard revenue-analytics`). Required when `role` is `'command'`.\n */\n command?: string;\n /**\n * The command this program nests under (e.g. `'audit'` for\n * `wizard audit feature-flags`). Omit for flat / standalone commands.\n */\n parentCommand?: string;\n}\n\n/**\n * Uniform configuration for a wizard program.\n *\n * Each program directory exports one of these. The system uses it\n * for CLI registration, sequence/step wiring, and skill bootstrap.\n */\nexport interface ProgramConfig {\n /** CLI command name (e.g. 'revenue-analytics'). Omit for the default program. */\n command?: string;\n /**\n * Parent CLI command to nest this program under. When set, the program is\n * registered as `<parentCommand> <command>` instead of as a top-level\n * command. The parent must itself be a registered subcommand program. Omit\n * for top-level programs.\n */\n parentCommand?: string;\n /** CLI description shown in --help */\n description: string;\n /** Unique program id — matches the Program enum value */\n id: string;\n /**\n * Content-mill flow the orchestrator loads its agent prompts + step-skills\n * from (`agents/<flow>/` and `skills/<flow>/`). Defaults to `id`; set it when\n * the content-mill flow name diverges from the program id.\n */\n agentFlow?: string;\n /**\n * Whether this program's agent run requires third-party AI services.\n *\n * When true (the default), the wizard checks\n * `apiUser.organization.is_ai_data_processing_approved` after auth and\n * renders `AiOptInRequiredScreen` if the org has not opted in. Matches\n * Max's strict reading: only literal `true` proceeds.\n *\n * Opt out (set to `false`) for programs that don't run the agent —\n * doctor, mcp install/remove/tutorial, source-map upload. The safe\n * default is `true` so future programs gate by declaration.\n */\n requiresAi?: boolean;\n /**\n * Context-mill skill ID this program installs and runs. When present,\n * bin.ts seeds `session.skillId` with this value before the TUI renders\n * so intro screens can resolve skill metadata without waiting for the\n * agent run.\n */\n skillId?: string;\n /** The ordered step list */\n steps: ProgramStep[];\n /** Agent run config. Static object or async function for dynamic config. */\n run?: ProgramRun | ((session: WizardSession) => Promise<ProgramRun>);\n /**\n * CI-mode pre-run strategy. When set, runWizardCI awaits this after building\n * the ci:true session and before the agent runs, instead of walking step\n * onReady hooks. Use for headless prerequisite work (e.g. framework\n * detection) that the TUI performs via step onReady callbacks.\n */\n ciPreRun?: (session: WizardSession) => Promise<void>;\n /** Prerequisites: other program ids that must have run first */\n requires?: string[];\n /**\n * Path (relative to installDir) of the report file the program writes.\n * Mirrors `run.reportFile` but lifted to the top level so UI screens can\n * read it synchronously without resolving a deferred `run` function.\n */\n reportFile?: string;\n /**\n * Agent-authored event-plan artifact to mirror into the wizard session.\n * Relative to `session.installDir`. Programs that do not produce an event\n * plan leave this unset, so generic runner machinery does not inspect a\n * stale or unrelated `.posthog-events.json` file.\n */\n eventPlanFile?: string;\n /**\n * LearnCard deck rendered in the shared `RunScreen` while the agent\n * runs. Lives at `<program>/content/index.tsx` by convention.\n * Programs that ship a custom RunScreen variant (audit) or skip the\n * run step (posthog-doctor) leave this unset.\n */\n getContentBlocks?: (store?: WizardStore) => ContentBlock[];\n /**\n * Tips shown in the run screen's right pane (the `Tips` sidebar) once\n * the LearnCard finishes. Lets a program supply its own explainer copy\n * (e.g. self-driving explaining what signal sources and scouts are)\n * instead of the generic onboarding deck. Unset → `RunScreen` falls back\n * to `DEFAULT_TIPS`, so every other program is unaffected. Lives at\n * `<program>/content/tips.ts` by convention.\n */\n getTips?: (store?: WizardStore) => Tip[];\n /**\n * Subcommand-specific CLI options. Spread into yargs `.options(...)` when the\n * program's subcommand is registered. Program-specific knowledge stays in\n * the program config, not in bin.ts. Typed as `unknown` to avoid pulling a\n * yargs dependency into this module.\n */\n cliOptions?: Record<string, unknown>;\n /**\n * Translate parsed CLI argv into extra options the runner consumes. Runs\n * after yargs validation, before runWizard/runWizardCI. Use this when a flag\n * needs to derive another field (e.g. `--product=statsig` → `skillId:\n * 'migrate-statsig'`).\n */\n mapCliOptions?: (argv: Record<string, unknown>) => Record<string, unknown>;\n /**\n * Extra tool names added on top of BASE_ALLOWED_TOOLS for this program's\n * agent run. Use for tools that only this program needs.\n */\n allowedTools?: readonly string[];\n /**\n * Tool names removed from BASE_ALLOWED_TOOLS for this program's agent\n * run. Use to forbid a base tool — e.g. `['Agent']` to block subagent\n * dispatch in a program whose steps are explicitly single-agent.\n */\n disallowedTools?: readonly string[];\n /**\n * Declares this program's place in the wizard CLI surface. See\n * `ProgramCliSurface` for semantics.\n */\n cli?: ProgramCliSurface;\n}\n\n/**\n * Project program steps into the narrower Screen shape the router consumes.\n *\n * Two things happen here:\n * 1. Headless steps (no `screenId`) are filtered out. The router walks\n * visible screens; gate-only steps like `detect` are store concerns.\n * 2. The step is narrowed to just { id, show, isComplete } — the\n * router has no business touching gate, onInit, or label.\n *\n * This intentional separation keeps the router focused on one question:\n * \"Which screen should be rendered right now?\"\n */\nexport function createProgramSequence(steps: ProgramStep[]): Array<{\n id: string;\n show?: (session: WizardSession) => boolean;\n isComplete?: (session: WizardSession) => boolean;\n}> {\n const entries = steps\n .filter((step) => step.screenId != null)\n .map((step) => ({\n id: step.screenId!,\n show: step.show,\n // `isComplete` defaults to `gate` — for most steps they're the same\n // predicate (e.g. intro: setupConfirmed unblocks bin.ts AND finishes\n // the screen). Only override when the two conditions diverge.\n isComplete: step.isComplete ?? step.gate,\n }));\n\n // Every program ends with the exit screen.\n entries.push({ id: 'exit', show: undefined, isComplete: undefined });\n\n return entries;\n}\n","/**\n * AI opt-in gate — step injection for programs whose agent run sends\n * source to Anthropic Claude.\n *\n * Injected after the `auth` step for every program that doesn't declare\n * `requiresAi: false`. The injected step carries three predicates:\n *\n * show — renders AiOptInRequiredScreen when the org hasn't\n * approved third-party AI\n * isComplete — router advances once approval lands\n * gate — `await store.getGate('ai-opt-in')` parks the agent\n * runner until approval lands. THIS is the enforcement:\n * the screen alone is cosmetic; the gate is what stops\n * source from leaving the machine.\n *\n * Used by BOTH screen-sequences.ts (screen injection) and the store's\n * _initFromProgram (gate registration) so the two layers can't drift.\n *\n * The predicates mirror Max's strict reading of\n * `organization.is_ai_data_processing_approved`: only literal `true`\n * proceeds; `null` / `undefined` / `false` all block. CI and signup\n * sessions skip the gate:\n * - `--ci` auto-consents to AI usage per the README, and the\n * interactive kill screen would be unworkable headless.\n * - signup (account provisioning) auto-consents too: the provisioning\n * access token deliberately omits the `organization:read` scope\n * (`WIZARD_PROVISIONING_SCOPES` in constants.ts), so the org's\n * approval can never be read back — `apiUser` stays null and the gate\n * could never clear. Creating an account through the wizard to run the\n * AI agent is itself the consent, mirroring how `shouldDisableAsk`\n * already treats `ci || signup` as one non-interactive mode.\n */\n\nimport type { WizardSession } from '@lib/wizard-session';\nimport type { ProgramConfig, ProgramStep } from './program-step.js';\n\n/** Step id — also the ScreenId.AiOptIn enum value in screen-sequences. */\nexport const AI_OPT_IN_STEP_ID = 'ai-opt-in';\n\nfunction aiApproved(session: WizardSession): boolean {\n return !!session.apiUser?.organization?.is_ai_data_processing_approved;\n}\n\n/**\n * Returns the program's steps with the AI opt-in gate injected after\n * `auth`. Programs with `requiresAi: false` or no auth step pass\n * through unchanged — without auth, `apiUser` would never be populated\n * for evaluation anyway.\n */\nexport function withAiOptInGate(config: ProgramConfig): ProgramStep[] {\n if (config.requiresAi === false) return config.steps;\n\n const authIdx = config.steps.findIndex((s) => s.id === 'auth');\n if (authIdx === -1) return config.steps;\n\n const gateStep: ProgramStep = {\n id: AI_OPT_IN_STEP_ID,\n label: 'AI opt-in check',\n screenId: AI_OPT_IN_STEP_ID,\n // Only fire once apiUser has actually been populated — between\n // setCredentials and setApiUser there's a brief emitChange window\n // where apiUser is null, and we don't want to flash the gate then.\n show: (session) =>\n !session.ci &&\n !session.signup &&\n session.apiUser != null &&\n !aiApproved(session),\n isComplete: (session) =>\n session.ci || session.signup || aiApproved(session),\n gate: (session) => session.ci || session.signup || aiApproved(session),\n };\n\n return [\n ...config.steps.slice(0, authIdx + 1),\n gateStep,\n ...config.steps.slice(authIdx + 1),\n ];\n}\n","/**\n * Screen taxonomy + per-program screen sequences.\n *\n * Owns the ScreenId enum and projects each registered program's steps\n * into the router-shaped screen sequence (filtering headless steps and\n * appending the exit screen). Pure leaf module — no store, no React.\n */\n\nimport type { WizardSession } from '@lib/wizard-session';\nimport {\n PROGRAM_REGISTRY,\n type ProgramId,\n} from '@lib/programs/program-registry';\nimport { createProgramSequence } from '@lib/programs/program-step';\nimport { withAiOptInGate } from '@lib/programs/ai-opt-in-gate';\n\n/** Screens that participate in linear programs. */\nexport enum ScreenId {\n Intro = 'intro',\n RevenueIntro = 'revenue-intro',\n WarehouseIntro = 'warehouse-intro',\n SourceMapsIntro = 'source-maps-intro',\n SourceMapsDetect = 'source-maps-detect',\n SourceMapsOutro = 'source-maps-outro',\n MigrationIntro = 'migration-intro',\n AgentSkillIntro = 'agent-skill-intro',\n AiObservabilityIntro = 'ai-observability-intro',\n SelfDrivingIntro = 'self-driving-intro',\n SelfDrivingIntegrationCheck = 'self-driving-integration-check',\n SelfDrivingIntegrationDetect = 'self-driving-integration-detect',\n SelfDrivingHandoff = 'self-driving-handoff',\n AuditIntro = 'audit-intro',\n AuditRun = 'audit-run',\n AuditOutro = 'audit-outro',\n HealthCheck = 'health-check',\n DoctorIntro = 'doctor-intro',\n DoctorReport = 'doctor-report',\n Setup = 'setup',\n Auth = 'auth',\n Run = 'run',\n Mcp = 'mcp',\n McpSuggestedPrompts = 'mcp-suggested-prompts',\n SlackConnect = 'slack-connect',\n KeepSkills = 'keep-skills',\n Outro = 'outro',\n Exit = 'exit',\n McpAdd = 'mcp-add',\n McpRemove = 'mcp-remove',\n AiOptIn = 'ai-opt-in',\n}\n\nexport interface Screen {\n /** ScreenId to show */\n id: ScreenId;\n /** If provided, screen is skipped when this returns false. Omit = always show. */\n show?: (session: WizardSession) => boolean;\n /** If provided, screen is considered complete when this returns true. */\n isComplete?: (session: WizardSession) => boolean;\n}\n\n/** An ordered list of screens — a program's screen journey. */\nexport type Sequence = Screen[];\n\n/** All program screen sequences keyed by program id. */\nexport const PROGRAM_SEQUENCES: Record<ProgramId, Sequence> =\n Object.fromEntries(\n PROGRAM_REGISTRY.map((c) => [\n c.id,\n createProgramSequence(withAiOptInGate(c)) as Sequence,\n ]),\n ) as Record<ProgramId, Sequence>;\n","/**\n * WizardRouter — declarative program pipelines + overlay stack.\n *\n * Two layers:\n * Program cursor — linear sequence of screens, advanced with next()\n * Overlay stack — interrupts (outage, auth-expired, etc.) that push/pop\n *\n * The visible screen is: top of overlay stack if non-empty, otherwise the program cursor.\n *\n * Adding a program screen = append to a sequence array.\n * Adding an overlay = call pushOverlay() from anywhere.\n * No switch statements, no hardcoded transitions in business logic.\n */\n\nimport type { WizardSession } from '@lib/wizard-session';\nimport { Program, type ProgramId } from '@lib/programs/program-registry';\nimport {\n PROGRAM_SEQUENCES,\n ScreenId,\n type Screen,\n type Sequence,\n} from './screen-sequences.js';\n\n// Re-export so existing imports from './router.js' keep working\nexport { ScreenId, Program };\nexport type { Screen, Sequence, ProgramId };\n\n// ── ScreenId name taxonomy ──────────────────────────────────────────────\n\n/** Screens that interrupt programs as overlays */\nexport enum Overlay {\n SettingsOverride = 'settings-override',\n ManagedSettings = 'managed-settings',\n PortConflict = 'port-conflict',\n ManualAuthCode = 'manual-auth-code',\n AuthError = 'auth-error',\n SessionTimeout = 'session-timeout',\n WizardAsk = 'wizard-ask',\n}\n\n/** Union of all screen names */\nexport type ScreenName = ScreenId | Overlay;\n\n// ── Router ────────────────────────────────────────────────────────────\n\nexport class WizardRouter {\n private sequence: Sequence;\n private programId: ProgramId;\n private overlays: Overlay[] = [];\n\n constructor(programId: ProgramId = Program.PostHogIntegration) {\n this.programId = programId;\n this.sequence = PROGRAM_SEQUENCES[programId];\n }\n\n /**\n * Resolve which screen should be active based on session state.\n * Walks the program sequence, skipping hidden entries and completed entries,\n * returns the first incomplete screen.\n */\n resolve(session: WizardSession): ScreenName {\n if (this.overlays.length > 0) {\n return this.overlays[this.overlays.length - 1];\n }\n\n for (const entry of this.sequence) {\n if (entry.show && !entry.show(session)) continue;\n if (entry.isComplete && entry.isComplete(session)) continue;\n return entry.id;\n }\n\n // All entries complete — show the last screen (outro)\n return this.sequence[this.sequence.length - 1].id;\n }\n\n /** The screen that should be rendered right now. */\n get activeScreen(): ScreenName {\n // Overlays take priority — resolve() handles this too,\n // but activeScreen is called before session is available in some paths\n if (this.overlays.length > 0) {\n return this.overlays[this.overlays.length - 1];\n }\n return this.sequence[0].id;\n }\n\n /** The id of the active program. */\n get activeProgram(): ProgramId {\n return this.programId;\n }\n\n /** Whether an overlay is currently active. */\n get hasOverlay(): boolean {\n return this.overlays.length > 0;\n }\n\n /**\n * Push an overlay that interrupts the current program.\n * The program resumes when the overlay is dismissed via popOverlay().\n */\n pushOverlay(overlay: Overlay): void {\n this.overlays.push(overlay);\n }\n\n /**\n * Dismiss the topmost overlay. The program screen underneath resumes.\n */\n popOverlay(): void {\n this.overlays.pop();\n }\n\n /**\n * Direction hint for screen transitions.\n */\n private _lastDirection: 'push' | 'pop' | null = null;\n\n get lastNavDirection(): 'push' | 'pop' | null {\n return this._lastDirection;\n }\n\n /** @internal — called by store wrapper to track direction */\n _setDirection(dir: 'push' | 'pop' | null): void {\n this._lastDirection = dir;\n }\n}\n","/**\n * WizardStore — Nanostore-backed reactive store for the TUI.\n * React components subscribe via useSyncExternalStore.\n *\n * The active screen is derived from session state — WizardRouter walks\n * the flow and shows the first step whose `isComplete` is still false.\n *\n * Define a step `gate` if your screen needs to await user interactions.\n * bin.ts calls `await store.getGate(stepId)` to pause until the gate\n * predicate becomes true.\n *\n * All session mutations that affect screen resolution go through\n * explicit setters so emitChange() is always called.\n */\n\nimport { atom, map } from 'nanostores';\nimport { logToFile } from '@utils/debug';\nimport {\n TaskStatus,\n isTaskStatus,\n type AuthErrorDetail,\n type TokenUsageDelta,\n} from '@ui/wizard-ui';\nimport {\n type WizardSession,\n type OutroData,\n type DiscoveredFeature,\n type PendingQuestion,\n type AskAnswers,\n type CloudRegion,\n AdditionalFeature,\n McpOutcome,\n RunPhase,\n buildSession,\n} from '@lib/wizard-session';\nimport type { SettingsConflict } from '@lib/agent/claude-settings';\nimport {\n WizardReadiness,\n getBlockingServiceKeys,\n type WizardReadinessResult,\n} from '@lib/health-checks/readiness';\nimport { ServiceHealthStatus } from '@lib/health-checks/types';\nimport {\n WizardRouter,\n type ScreenName,\n ScreenId,\n Overlay,\n Program,\n type ProgramId,\n} from './router.js';\nimport { analytics, sessionProperties } from '@utils/analytics';\nimport type {\n StoreInitContext,\n ProgramReadyContext,\n} from '@lib/programs/program-step';\nimport { getProgramConfig } from '@lib/programs/program-registry';\nimport { withAiOptInGate } from '@lib/programs/ai-opt-in-gate';\nimport { EXPANDED_COUNT } from '@ui/tui/constants';\nimport { IS_DEV } from '@lib/constants';\nimport { computeTokenCostUsd } from '@lib/agent/token-pricing';\n\nexport { TaskStatus, ScreenId, Overlay, Program, RunPhase, McpOutcome };\nexport type { ScreenName, OutroData, WizardSession, ProgramId };\n\nexport interface TaskItem {\n label: string;\n activeForm?: string;\n status: TaskStatus;\n /** Legacy compat */\n done: boolean;\n}\n\nexport interface PlannedEvent {\n name: string;\n description: string;\n}\n\n/**\n * Running token/cost estimate for the hidden Ctrl+T HUD. Accumulated live\n * from each assistant turn's usage (see `agent-interface.ts`), then\n * reconciled to the SDK's authoritative `total_cost_usd` once the run\n * completes — `costIsFinal` flips so the HUD can show the number as exact\n * rather than a running estimate.\n */\nexport interface TokenUsageSnapshot {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheCreationTokens: number;\n costUsd: number;\n costIsFinal: boolean;\n}\n\nconst EMPTY_TOKEN_USAGE: TokenUsageSnapshot = {\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheCreationTokens: 0,\n costUsd: 0,\n costIsFinal: false,\n};\n\n/** Total tokens across all counters in a `TokenUsageSnapshot` — used by\n * both `TokenCostHud` and `exit-line.ts` to detect \"no agent turns yet\". */\nexport function totalTokenCount(usage: TokenUsageSnapshot): number {\n return (\n usage.inputTokens +\n usage.outputTokens +\n usage.cacheReadTokens +\n usage.cacheCreationTokens\n );\n}\n\ninterface GateEntry {\n predicate: (session: WizardSession) => boolean;\n promise: Promise<void>;\n resolve: () => void;\n resolved: boolean;\n}\n\n/**\n * FIFO cap on retained status lines. The status bar is the only consumer and\n * renders at most EXPANDED_COUNT lines, so there is no reason to retain more —\n * the cap is tied to the window it feeds.\n */\nconst MAX_STATUS_MESSAGES = EXPANDED_COUNT;\n\n/**\n * Fired once per blocked readiness result, so we can quantify how often\n * the wizard refuses to start and — crucially — split that between\n * confirmed PostHog outages and probe-level reachability failures that\n * are most likely the user's network. Helps us decide whether the\n * health-check UX is over-firing.\n */\nfunction captureHealthCheckBlocked(result: WizardReadinessResult): void {\n try {\n const health = result.health;\n const blockingKeys = getBlockingServiceKeys(health);\n const blockingStatuses = blockingKeys.map((k) => health[k]?.status);\n\n const allNoConnection =\n blockingStatuses.length > 0 &&\n blockingStatuses.every((s) => s === ServiceHealthStatus.NoConnection);\n const onlyGithubReleases =\n blockingKeys.length === 1 && blockingKeys[0] === 'githubReleases';\n\n const decision = onlyGithubReleases\n ? 'github-releases-down'\n : allNoConnection\n ? 'no-connection'\n : 'confirmed-outage';\n\n const posthogStatus = health.posthogOverall?.status;\n const retriesUsed = Math.max(\n 0,\n ...(['llmGateway', 'mcp', 'githubReleases'] as const).map((k) => {\n const ind = health[k]?.rawIndicator ?? '';\n const m = ind.match(/attempts=(\\d+)/);\n return m ? Number(m[1]) - 1 : 0;\n }),\n );\n\n analytics.wizardCapture('health check blocked', {\n decision,\n blocking_keys: blockingKeys,\n posthog_status_reachable:\n posthogStatus !== ServiceHealthStatus.NoConnection,\n posthog_status_reports_incident:\n posthogStatus === ServiceHealthStatus.Down ||\n posthogStatus === ServiceHealthStatus.Degraded,\n retries_used: retriesUsed,\n });\n } catch (err) {\n logToFile(\n `[health-checks] failed to capture analytics: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n}\n\nexport class WizardStore {\n // ── Internal nanostore atoms ─────────────────────────────────────\n private $session = map<WizardSession>(buildSession({}));\n private $statusMessages = atom<string[]>([]);\n private $statusExpanded = atom(false);\n private $tasks = atom<TaskItem[]>([]);\n private $eventPlan = atom<PlannedEvent[]>([]);\n private $handoffText = atom<string | null>(null);\n private $learnCardBlockIdx = atom(0);\n private $learnCardComplete = atom(false);\n private $version = atom(0);\n private $currentStage = atom<{ stage: string; startedAt: number } | null>(\n null,\n );\n private $tokenUsage = atom<TokenUsageSnapshot>(EMPTY_TOKEN_USAGE);\n // Defaults on for local/dev/test runs (tsx, `pnpm try`, vitest) so\n // contributors see it without needing to know the shortcut; defaults off\n // for the published build, where it stays genuinely hidden. Still\n // Ctrl+T-toggleable either way.\n private $tokenHudVisible = atom(IS_DEV);\n\n private _onTasksChanged: (() => void) | null = null;\n /** Last screen seen — used to detect screen transitions for analytics. */\n private _lastScreen: ScreenName | null = null;\n\n /** Hooks run when transitioning onto a screen. */\n private _enterScreenHooks = new Map<ScreenName, (() => void)[]>();\n\n /** Gate promises derived from program step definitions. */\n private _gates = new Map<string, GateEntry>();\n\n version = '';\n\n /** Navigation router — resolves active screen from session state. */\n readonly router: WizardRouter;\n\n /** Blocks agent execution until the settings-override overlay is dismissed. */\n private _resolveSettingsOverride: (() => void) | null = null;\n private _backupAndFixSettings: (() => boolean) | null = null;\n\n /** Blocks OAuth flow until the port-conflict overlay is dismissed. */\n private _resolvePortConflict: (() => void) | null = null;\n\n /** Resolves the OAuth flow with a manually-entered authorization code. */\n private _resolveManualAuthCode: ((code: string) => void) | null = null;\n\n /** Resolves the in-flight wizard_ask request. */\n private _resolvePendingQuestion: ((answers: AskAnswers) => void) | null =\n null;\n\n constructor(program: ProgramId = Program.PostHogIntegration) {\n this.router = new WizardRouter(program);\n this._initFromProgram(program);\n }\n\n /**\n * Scan program steps for gate predicates and create gate promises.\n *\n * Steps are wrapped with withAiOptInGate so the injected ai-opt-in\n * step's gate registers here — the agent runner awaits it (via\n * WizardUI.waitForAiOptIn) before any source leaves the machine.\n * Same wrapper screen-sequences.ts uses, so the gate and its screen\n * can't drift apart.\n */\n private _initFromProgram(program: ProgramId): void {\n const steps = withAiOptInGate(getProgramConfig(program));\n\n // Create gate promises from steps that define them\n for (const step of steps) {\n if (step.gate) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => {\n resolve = r;\n });\n this._gates.set(step.id, {\n predicate: step.gate,\n promise,\n resolve,\n resolved: false,\n });\n }\n }\n }\n\n /**\n * Run the program steps' onInit callbacks. startTUI calls this once\n * the screens are actually rendering — constructing a store alone\n * (tests, playground) must not fire init work like the health-check\n * pre-flight, whose probes belong only to flows that show its screen.\n */\n runInitHooks(): void {\n const steps = getProgramConfig(this.router.activeProgram).steps;\n const getSession = (): WizardSession => this.session;\n const ctx: StoreInitContext = {\n get session() {\n return getSession();\n },\n setReadinessResult: (r) => this.setReadinessResult(r),\n setFrameworkContext: (k, v) => this.setFrameworkContext(k, v),\n emitChange: () => this.emitChange(),\n };\n for (const step of steps) {\n step.onInit?.(ctx);\n }\n }\n\n /**\n * Run all `onReady` hooks declared by the current flow's steps, in\n * order. Must be called after `store.session = session` so hooks see\n * the real installDir. bin.ts calls this generically — it doesn't\n * need to know which program has which pre-flow work.\n */\n async runReadyHooks(): Promise<void> {\n const steps = getProgramConfig(this.router.activeProgram).steps;\n const ctx: ProgramReadyContext = {\n session: this.session,\n setFrameworkContext: (k, v) => this.setFrameworkContext(k, v),\n setFrameworkConfig: (i, c) => this.setFrameworkConfig(i, c),\n setDetectedFramework: (l) => this.setDetectedFramework(l),\n setSkillId: (id) => this.setSkillId(id),\n setUnsupportedVersion: (info) => this.setUnsupportedVersion(info),\n addDiscoveredFeature: (f) => this.addDiscoveredFeature(f),\n setDetectionComplete: () => this.setDetectionComplete(),\n };\n for (const step of steps) {\n if (step.onReady) {\n await step.onReady(ctx);\n }\n }\n }\n\n // ── Gate API ────────────────────────────────────────────────────\n\n /**\n * Get a gate promise by step ID — the primary blocking checkpoint API\n * for bin.ts. `await store.getGate('...')` parks the caller until the\n * corresponding program step's gate predicate flips to true (if the\n * predicate stays false, the caller stays parked indefinitely — the\n * TUI keeps rendering so the user can resolve whatever is blocking).\n *\n * If the program doesn't define a step with this ID, or the step\n * has no `gate` predicate, this returns an already-resolved promise\n * so bin.ts flows straight through. This lets programs opt in to\n * gates on a per-step basis without bin.ts needing to know which\n * gates exist in which flow.\n */\n getGate(stepId: string): Promise<void> {\n return this._gates.get(stepId)?.promise ?? Promise.resolve();\n }\n\n /**\n * Resolve once `predicate(session)` is true. Unlike a gate, this is created\n * at the await point and evaluated live against the current session, so it\n * never latches on a startup value — the orchestrator uses it to wait for a\n * decision (a project picked, a handoff acknowledged) without the \"true while\n * undecided\" trap that latched gate predicates have.\n */\n waitUntil(predicate: (session: WizardSession) => boolean): Promise<void> {\n if (predicate(this.session)) return Promise.resolve();\n return new Promise((resolve) => {\n const unsub = this.subscribe(() => {\n if (predicate(this.session)) {\n unsub();\n resolve();\n }\n });\n });\n }\n\n /**\n * Re-evaluate every gate predicate against the current session and\n * resolve any whose predicate now returns true. Called after every\n * emitChange(), so gates unblock as soon as the session mutation\n * that satisfies them lands. Gates only resolve once — a predicate\n * that goes true → false → true will NOT re-block a caller that\n * already awaited through.\n */\n private _checkGates(): void {\n for (const [, gate] of this._gates) {\n if (!gate.resolved && gate.predicate(this.session)) {\n gate.resolved = true;\n gate.resolve();\n }\n }\n }\n\n // ── State accessors (read from atoms) ────────────────────────────\n\n get session(): WizardSession {\n return this.$session.get();\n }\n\n set session(value: WizardSession) {\n this.$session.set(value);\n this.emitChange();\n }\n\n get statusMessages(): string[] {\n return this.$statusMessages.get();\n }\n\n get tasks(): TaskItem[] {\n return this.$tasks.get();\n }\n\n get eventPlan(): PlannedEvent[] {\n return this.$eventPlan.get();\n }\n\n get handoffText(): string | null {\n return this.$handoffText.get();\n }\n\n get currentStage(): { stage: string; startedAt: number } | null {\n return this.$currentStage.get();\n }\n\n /** No-op when the stage hasn't changed, so `startedAt` survives across\n * re-renders and tab switches and measures real stage time. */\n setCurrentStage(stage: string): void {\n const cur = this.$currentStage.get();\n if (cur?.stage === stage) return;\n this.$currentStage.set({ stage, startedAt: Date.now() });\n this.emitChange();\n }\n\n get statusExpanded(): boolean {\n return this.$statusExpanded.get();\n }\n\n toggleStatusExpanded(): void {\n this.$statusExpanded.set(!this.$statusExpanded.get());\n this.emitChange();\n }\n\n setStatusExpanded(expanded: boolean): void {\n if (this.$statusExpanded.get() !== expanded) {\n this.$statusExpanded.set(expanded);\n this.emitChange();\n }\n }\n\n // ── Session setters ─────────────────────────────────────────────\n // Every setter that affects screen resolution calls emitChange().\n // Business logic calls these instead of mutating session directly.\n\n /** Sets setupConfirmed. Gate resolves via _checkGates(). */\n completeSetup(): void {\n this.$session.setKey('setupConfirmed', true);\n analytics.wizardCapture('setup confirmed', sessionProperties(this.session));\n this.emitChange();\n }\n\n setRunPhase(phase: RunPhase): void {\n this.$session.setKey('runPhase', phase);\n analytics.setTag('run_phase', phase);\n this.emitChange();\n }\n\n setCredentials(credentials: WizardSession['credentials']): void {\n this.$session.setKey('credentials', credentials);\n if (credentials?.projectId) {\n analytics.setTag('project_id', credentials.projectId);\n }\n analytics.wizardCapture('auth complete', {\n project_id: credentials?.projectId,\n });\n this.emitChange();\n }\n\n setRoleAtOrganization(role: string | null): void {\n this.$session.setKey('roleAtOrganization', role);\n this.emitChange();\n }\n\n setApiUser(user: WizardSession['apiUser']): void {\n this.$session.setKey('apiUser', user);\n this.emitChange();\n }\n\n setFrameworkConfig(\n integration: WizardSession['integration'],\n config: WizardSession['frameworkConfig'],\n ): void {\n this.$session.setKey('integration', integration);\n this.$session.setKey('frameworkConfig', config);\n this.$session.setKey('unsupportedVersion', null);\n if (integration) analytics.setTag('integration', integration);\n this.emitChange();\n }\n\n setDetectionComplete(): void {\n this.$session.setKey('detectionComplete', true);\n this.emitChange();\n }\n\n setDetectedFramework(label: string): void {\n this.$session.setKey('detectedFrameworkLabel', label);\n analytics.setTag('detected_framework', label);\n this.emitChange();\n }\n\n setSkillId(skillId: string | null): void {\n this.$session.setKey('skillId', skillId);\n this.emitChange();\n }\n\n setUnsupportedVersion(info: {\n current: string;\n minimum: string;\n docsUrl: string;\n }): void {\n this.$session.setKey('unsupportedVersion', info);\n this.emitChange();\n }\n\n setLoginUrl(url: string | null): void {\n this.$session.setKey('loginUrl', url);\n this.emitChange();\n }\n\n setAuthorizeUrl(url: string | null): void {\n this.$session.setKey('authorizeUrl', url);\n this.emitChange();\n }\n\n setReadinessResult(result: WizardReadinessResult | null): void {\n this.$session.setKey('readinessResult', result);\n if (result && result.decision === WizardReadiness.No) {\n captureHealthCheckBlocked(result);\n }\n this.emitChange();\n }\n\n /** User dismissed the blocking outage screen. Gate resolves via _checkGates(). */\n dismissOutage(): void {\n logToFile('[health-checks] user dismissed outage screen, continuing');\n this.$session.setKey('outageDismissed', true);\n this.emitChange();\n }\n\n /**\n * Push the settings-override overlay and return a promise that blocks\n * until the user dismisses it via backupAndFixSettingsOverride().\n */\n showSettingsOverride(\n conflicts: SettingsConflict[],\n backupAndFix: () => boolean,\n ): Promise<void> {\n const allKeys = conflicts.flatMap((c) => c.keys);\n this.$session.setKey('settingsOverrideKeys', allKeys);\n this.$session.setKey('settingsConflicts', conflicts);\n this._backupAndFixSettings = backupAndFix;\n\n const hasReadOnly = conflicts.some((c) => !c.writable);\n if (hasReadOnly) {\n this.pushOverlay(Overlay.ManagedSettings);\n } else {\n this.pushOverlay(Overlay.SettingsOverride);\n }\n\n return new Promise((resolve) => {\n this._resolveSettingsOverride = resolve;\n });\n }\n\n /**\n * Push the port-conflict overlay and return a promise that blocks\n * until the user frees the ports and retries, or exits.\n */\n showPortConflict(processInfo: {\n command: string;\n pid: string;\n port: number;\n user: string;\n }): Promise<void> {\n this.$session.setKey('portConflictProcess', processInfo);\n this.pushOverlay(Overlay.PortConflict);\n return new Promise((resolve) => {\n this._resolvePortConflict = resolve;\n });\n }\n\n /** Dismiss the port-conflict overlay and retry the OAuth port loop. */\n resolvePortConflict(): void {\n this.$session.setKey('portConflictProcess', null);\n this.popOverlay();\n this._resolvePortConflict?.();\n this._resolvePortConflict = null;\n }\n\n /**\n * Return a promise that resolves when the user submits a manually-entered\n * OAuth code via the paste modal. The OAuth flow races this against the\n * local callback server — see `performOAuthFlow`.\n */\n waitForManualAuthCode(): Promise<string> {\n return new Promise<string>((resolve) => {\n this._resolveManualAuthCode = resolve;\n });\n }\n\n /** Open the manual OAuth code-entry overlay over the auth screen. */\n showManualAuthCode(): void {\n this.pushOverlay(Overlay.ManualAuthCode);\n }\n\n /** Dismiss the manual OAuth code overlay without submitting. */\n dismissManualAuthCode(): void {\n this.popOverlay();\n }\n\n /**\n * Submit a manually-entered authorization code: dismiss the overlay and\n * resolve the in-flight OAuth flow so it can exchange the code for a token.\n */\n submitManualAuthCode(code: string): void {\n this.popOverlay();\n this._resolveManualAuthCode?.(code);\n this._resolveManualAuthCode = null;\n }\n\n /**\n * Open the WizardAsk overlay with a set of questions and return a promise\n * that resolves once the user submits answers (or the request is cancelled).\n *\n * Only one request is in flight at a time — calling this while a request\n * is already pending throws.\n */\n requestQuestion(question: PendingQuestion): Promise<AskAnswers> {\n if (this._resolvePendingQuestion) {\n throw new Error(\n 'requestQuestion called while another wizard_ask request is pending',\n );\n }\n this.$session.setKey('pendingQuestion', question);\n this.pushOverlay(Overlay.WizardAsk);\n analytics.wizardCapture('wizard_ask shown', {\n source: question.source,\n question_count: question.questions.length,\n kinds: question.questions.map((q) => q.kind),\n });\n return new Promise<AskAnswers>((resolve) => {\n this._resolvePendingQuestion = resolve;\n });\n }\n\n /**\n * Resolve the in-flight wizard_ask request with the user's answers and\n * dismiss the overlay. Answers flow back to the agent as the tool result.\n */\n resolvePendingQuestion(answers: AskAnswers): void {\n const resolve = this._resolvePendingQuestion;\n this._resolvePendingQuestion = null;\n this.$session.setKey('pendingQuestion', null);\n this.popOverlay();\n resolve?.(answers);\n }\n\n /**\n * Cancel the in-flight wizard_ask request — the bridge sends a sentinel\n * answer (\"__cancelled__\") so the skill can decide how to handle it.\n */\n cancelPendingQuestion(): void {\n const pending = this.session.pendingQuestion;\n if (!pending) return;\n const cancelled: AskAnswers = {};\n for (const q of pending.questions) {\n cancelled[q.id] = '__cancelled__';\n }\n this.resolvePendingQuestion(cancelled);\n }\n\n /**\n * Back up .claude/settings.json. Dismisses the overlay on success.\n */\n backupAndFixSettingsOverride(): boolean {\n const ok = this._backupAndFixSettings?.() ?? false;\n if (ok) {\n this.$session.setKey('settingsOverrideKeys', null);\n this.$session.setKey('settingsConflicts', null);\n this.popOverlay();\n this._resolveSettingsOverride?.();\n this._resolveSettingsOverride = null;\n this._backupAndFixSettings = null;\n }\n return ok;\n }\n\n /** Push the auth-error overlay (no dismiss — user must exit). */\n showAuthError(detail?: AuthErrorDetail): void {\n this.$session.setKey('authErrorDetail', detail ?? null);\n this.pushOverlay(Overlay.AuthError);\n }\n\n /** Push the session-timeout overlay (no dismiss — user must exit). */\n showSessionTimeout(): void {\n this.pushOverlay(Overlay.SessionTimeout);\n }\n\n addDiscoveredFeature(feature: DiscoveredFeature): void {\n if (!this.session.discoveredFeatures.includes(feature)) {\n this.session.discoveredFeatures.push(feature);\n this.emitChange();\n }\n }\n\n /**\n * Enable an additional feature: enqueue it for the stop hook\n * and set any feature-specific session flags.\n */\n enableFeature(feature: AdditionalFeature): void {\n if (!this.session.additionalFeatureQueue.includes(feature)) {\n this.session.additionalFeatureQueue.push(feature);\n // Distinct key from `sessionProperties()`'s array-valued\n // `additional_features` — see the note in posthog-integration/detect.ts.\n analytics.setTag(\n 'additional_feature_kinds',\n this.session.additionalFeatureQueue.join(','),\n );\n }\n // Feature-specific flags\n if (feature === AdditionalFeature.LLM) {\n this.session.llmOptIn = true;\n }\n analytics.wizardCapture('feature enabled', { feature });\n this.emitChange();\n }\n\n setMcpComplete(\n outcome: McpOutcome = McpOutcome.Skipped,\n installedClients: string[] = [],\n featuresSelected?: 'all' | string[],\n ): void {\n this.$session.setKey('mcpComplete', true);\n this.$session.setKey('mcpOutcome', outcome);\n this.$session.setKey('mcpInstalledClients', installedClients);\n const featuresPayload =\n outcome === McpOutcome.Installed && featuresSelected !== undefined\n ? { mcp_features_selected: featuresSelected }\n : {};\n analytics.wizardCapture('mcp complete', {\n mcp_outcome: outcome,\n mcp_installed_clients: installedClients,\n ...featuresPayload,\n ...sessionProperties(this.session),\n });\n this.emitChange();\n }\n\n setSkillsComplete(kept: boolean): void {\n this.$session.setKey('skillsComplete', true);\n analytics.wizardCapture('skills complete', {\n skills_kept: kept,\n ...sessionProperties(this.session),\n });\n this.emitChange();\n }\n\n setMcpSuggestedPromptsDismissed(): void {\n this.$session.setKey('mcpSuggestedPromptsDismissed', true);\n this.emitChange();\n }\n\n setSlackStepDismissed(): void {\n this.$session.setKey('slackStepDismissed', true);\n this.emitChange();\n }\n\n setSlackConnected(connected: boolean): void {\n this.$session.setKey('slackConnected', connected);\n this.emitChange();\n }\n\n /**\n * Self-driving integration-check answer. `true` → integrate the SDK as part\n * of this run; `false` → PostHog is already set up, go straight to\n * Self-driving. Resolves `session.integrate` from null.\n */\n setIntegrate(\n integrate: boolean,\n extra?: { via?: string; path?: string },\n ): void {\n this.$session.setKey('integrate', integrate);\n analytics.wizardCapture('self-driving integration check', {\n self_driving_integrate: integrate,\n ...(extra?.via ? { self_driving_integrate_via: extra.via } : {}),\n ...(extra?.path ? { self_driving_integrate_path: extra.path } : {}),\n ...sessionProperties(this.session),\n });\n this.emitChange();\n }\n\n /**\n * Self-driving \"no PostHog account\" branch of the integration check. The\n * project has no SDK, so we always integrate (`integrate = true`); and since\n * the user has no account, we flip `signup` and record the `email` / `region`\n * collected on the screen so `authenticate` → `getOrAskForProjectData` takes\n * the provisioning path (create account + email a login link) instead of\n * OAuth. The \"yes, I have an account\" branch uses `setIntegrate(true)` and\n * leaves `signup` false so auth runs the normal OAuth login.\n */\n chooseProvisionAccount(email: string, region: CloudRegion): void {\n this.$session.setKey('signup', true);\n this.$session.setKey('email', email);\n this.$session.setKey('region', region);\n this.$session.setKey('integrate', true);\n analytics.wizardCapture('self-driving integration check', {\n self_driving_integrate: true,\n self_driving_has_account: false,\n provision_region: region,\n ...sessionProperties(this.session),\n });\n this.emitChange();\n }\n\n /**\n * Self-driving handoff confirmed — the user acknowledged the post-integration\n * screen, so the Self-driving run can begin. Gate resolves via _checkGates().\n */\n confirmSelfDrivingHandoff(): void {\n this.$session.setKey('selfDrivingHandoffConfirmed', true);\n this.emitChange();\n }\n\n /**\n * Mark a composed run step complete (e.g. self-driving's `integrate-run`).\n * Records the step id so its `isComplete` predicate holds, clears the task\n * list, and resets run phase to Idle so the next run step starts fresh.\n */\n completeRunStep(stepId: string): void {\n const done = this.session.completedRuns;\n if (!done.includes(stepId)) {\n this.$session.setKey('completedRuns', [...done, stepId]);\n }\n this.$tasks.set([]);\n this.setRunPhase(RunPhase.Idle);\n }\n\n setOutroDismissed(): void {\n this.$session.setKey('outroDismissed', true);\n this.emitChange();\n }\n\n setOutroData(data: OutroData): void {\n this.$session.setKey('outroData', data);\n this.emitChange();\n }\n\n setDashboardUrl(url: string): void {\n logToFile(`store.setDashboardUrl: ${url}`);\n this.$session.setKey('dashboardUrl', url);\n this.emitChange();\n }\n\n setNotebookUrl(url: string): void {\n logToFile(`store.setNotebookUrl: ${url}`);\n this.$session.setKey('notebookUrl', url);\n this.emitChange();\n }\n\n setFrameworkContext(key: string, value: unknown): void {\n const ctx = { ...this.$session.get().frameworkContext, [key]: value };\n this.$session.setKey('frameworkContext', ctx);\n this.emitChange();\n }\n\n // ── Derived state ───────────────────────────────────────────────\n\n /**\n * The screen that should be rendered right now.\n * Derived from session state via the router.\n */\n get currentScreen(): ScreenName {\n return this.router.resolve(this.session);\n }\n\n /** Direction hint for screen transitions. */\n get lastNavDirection(): 'push' | 'pop' | null {\n return this.router.lastNavDirection;\n }\n\n // ── Change notification ─────────────────────────────────────────\n\n getVersion(): number {\n return this.$version.get();\n }\n\n /**\n * Notify React that state has changed.\n * The router re-resolves the active screen on next render.\n * Gate predicates are checked and resolved if ready.\n */\n emitChange(): void {\n this.router._setDirection('push');\n this.$version.set(this.$version.get() + 1);\n this._checkGates();\n this._detectTransition();\n }\n\n // ── Overlay navigation ──────────────────────────────────────────\n\n pushOverlay(overlay: Overlay): void {\n this.router._setDirection('push');\n this.router.pushOverlay(overlay);\n this.$version.set(this.$version.get() + 1);\n this._detectTransition();\n }\n\n popOverlay(): void {\n this.router._setDirection('pop');\n this.router.popOverlay();\n this.$version.set(this.$version.get() + 1);\n this._detectTransition();\n }\n\n // ── ScreenId transition analytics ─────────────────────────────────\n\n /**\n * Register a callback to run when transitioning onto the given screen.\n * Fires after every transition that lands on this screen.\n */\n onEnterScreen(screen: ScreenName, fn: () => void): void {\n const list = this._enterScreenHooks.get(screen) ?? [];\n list.push(fn);\n this._enterScreenHooks.set(screen, list);\n }\n\n /**\n * Detect screen transitions, run enter-screen hooks, and fire analytics.\n * Called at the end of emitChange/pushOverlay/popOverlay.\n */\n private _detectTransition(): void {\n const next = this.router.resolve(this.session);\n const prev = this._lastScreen;\n if (next !== prev) {\n // Every event carries the active TUI screen, filling the\n // \"URL / Screen\" column in PostHog.\n analytics.setTag('$screen_name', next);\n }\n if (prev !== null && next !== prev) {\n const hooks = this._enterScreenHooks.get(next);\n if (hooks) {\n for (const fn of hooks) fn();\n }\n analytics.wizardCapture(`screen ${next}`, {\n from_screen: prev,\n program_id: this.router.activeProgram,\n ...sessionProperties(this.session),\n });\n }\n this._lastScreen = next;\n }\n\n // ── Agent observation state ─────────────────────────────────────\n\n pushStatus(message: string): void {\n const msgs = this.$statusMessages.get();\n // Skip consecutive duplicate messages (no allocation on the hot path)\n if (msgs.length > 0 && msgs[msgs.length - 1] === message) return;\n // Nanostore detects change by reference equality, so a new array is\n // required. At the cap, allocate exactly once at the final size (dropping\n // the oldest entry) rather than push-then-truncate.\n const next =\n msgs.length >= MAX_STATUS_MESSAGES\n ? [...msgs.slice(msgs.length - MAX_STATUS_MESSAGES + 1), message]\n : [...msgs, message];\n this.$statusMessages.set(next);\n this.emitChange();\n }\n\n get tokenUsage(): TokenUsageSnapshot {\n return this.$tokenUsage.get();\n }\n\n get tokenHudVisible(): boolean {\n return this.$tokenHudVisible.get();\n }\n\n /** Hidden Ctrl+T shortcut — see ScreenContainer. Not registered as a\n * keyboard hint, so it never shows in the hints bar. */\n toggleTokenHud(): void {\n this.$tokenHudVisible.set(!this.$tokenHudVisible.get());\n this.emitChange();\n }\n\n /**\n * Accumulate one assistant turn's token usage into the running estimate.\n * Approximate by design (no dedup for SDK-retried/replayed turns, unlike\n * the benchmark middleware's TurnCounterPlugin) — it's a live indicator\n * for a hidden debug HUD, not a billing record, and `setFinalTokenCostUsd`\n * corrects the total once the run's authoritative cost is known.\n */\n addTokenUsage(delta: TokenUsageDelta): void {\n const cur = this.$tokenUsage.get();\n if (cur.costIsFinal) return;\n const deltaCostUsd = computeTokenCostUsd(delta);\n this.$tokenUsage.set({\n inputTokens: cur.inputTokens + delta.inputTokens,\n outputTokens: cur.outputTokens + delta.outputTokens,\n cacheReadTokens: cur.cacheReadTokens + delta.cacheReadTokens,\n cacheCreationTokens: cur.cacheCreationTokens + delta.cacheCreationTokens,\n costUsd: cur.costUsd + deltaCostUsd,\n costIsFinal: false,\n });\n this.emitChange();\n }\n\n /** Reconcile the running cost estimate to the SDK's authoritative total\n * once the agent run completes — same trick the benchmark's\n * CostTrackerPlugin.onFinalize uses to correct any per-turn drift. */\n setFinalTokenCostUsd(costUsd: number): void {\n const cur = this.$tokenUsage.get();\n this.$tokenUsage.set({ ...cur, costUsd, costIsFinal: true });\n this.emitChange();\n }\n\n setTasks(tasks: TaskItem[]): void {\n this.$tasks.set(tasks);\n this.emitChange();\n }\n\n updateTask(index: number, done: boolean): void {\n const tasks = this.$tasks.get();\n if (tasks[index]) {\n const updated = [...tasks];\n updated[index] = {\n ...updated[index],\n done,\n status: done ? TaskStatus.Completed : TaskStatus.Pending,\n };\n this.$tasks.set(updated);\n this.emitChange();\n }\n }\n\n setEventPlan(events: PlannedEvent[]): void {\n this.$eventPlan.set(events);\n this.emitChange();\n }\n\n /** No-op on identical text: an emit here means a network push downstream. */\n setHandoffText(text: string): void {\n if (this.$handoffText.get() === text) return;\n logToFile(`store.setHandoffText: ${text.length} chars`);\n this.$handoffText.set(text);\n this.emitChange();\n }\n\n get learnCardBlockIdx(): number {\n return this.$learnCardBlockIdx.get();\n }\n\n setLearnCardBlockIdx(idx: number): void {\n this.$learnCardBlockIdx.set(idx);\n }\n\n get learnCardComplete(): boolean {\n return this.$learnCardComplete.get();\n }\n\n setLearnCardComplete(): void {\n this.$learnCardComplete.set(true);\n this.emitChange();\n }\n\n syncTodos(\n todos: Array<{ content: string; status: string; activeForm?: string }>,\n ): void {\n const incoming = todos.map((t) => {\n const status = isTaskStatus(t.status) ? t.status : TaskStatus.Pending;\n return {\n label: t.content,\n activeForm: t.activeForm,\n status,\n done: status === TaskStatus.Completed,\n };\n });\n\n const incomingLabels = new Set(incoming.map((t) => t.label));\n\n const retained = this.$tasks\n .get()\n .filter((t) => t.done && !incomingLabels.has(t.label));\n\n this.$tasks.set([...retained, ...incoming]);\n this.emitChange();\n this._onTasksChanged?.();\n }\n\n /** Register a listener for task state changes (e.g. task stream push). */\n set onTasksChanged(fn: () => void) {\n this._onTasksChanged = fn;\n }\n\n // ── React integration ───────────────────────────────────────────\n\n subscribe(callback: () => void): () => void {\n return this.$version.listen(() => callback());\n }\n\n getSnapshot(): number {\n return this.$version.get();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsTA,SAAgB,sBAAsB,OAInC;CACD,MAAM,UAAU,MACb,QAAQ,SAAS,KAAK,YAAY,KAAK,CACvC,KAAK,UAAU;EACd,IAAI,KAAK;EACT,MAAM,KAAK;EAIX,YAAY,KAAK,cAAc,KAAK;EACrC,EAAE;AAGL,SAAQ,KAAK;EAAE,IAAI;EAAQ,MAAM,KAAA;EAAW,YAAY,KAAA;EAAW,CAAC;AAEpE,QAAO;;;;;ACpST,MAAa,oBAAoB;AAEjC,SAAS,WAAW,SAAiC;AACnD,QAAO,CAAC,CAAC,QAAQ,SAAS,cAAc;;;;;;;;AAS1C,SAAgB,gBAAgB,QAAsC;AACpE,KAAI,OAAO,eAAe,MAAO,QAAO,OAAO;CAE/C,MAAM,UAAU,OAAO,MAAM,WAAW,MAAM,EAAE,OAAO,OAAO;AAC9D,KAAI,YAAY,GAAI,QAAO,OAAO;CAElC,MAAM,WAAwB;EAC5B,IAAI;EACJ,OAAO;EACP,UAAU;EAIV,OAAO,YACL,CAAC,QAAQ,MACT,CAAC,QAAQ,UACT,QAAQ,WAAW,QACnB,CAAC,WAAW,QAAQ;EACtB,aAAa,YACX,QAAQ,MAAM,QAAQ,UAAU,WAAW,QAAQ;EACrD,OAAO,YAAY,QAAQ,MAAM,QAAQ,UAAU,WAAW,QAAQ;EACvE;AAED,QAAO;EACL,GAAG,OAAO,MAAM,MAAM,GAAG,UAAU,EAAE;EACrC;EACA,GAAG,OAAO,MAAM,MAAM,UAAU,EAAE;EACnC;;;;;ACZH,MAAa,oBACX,OAAO,YACL,iBAAiB,KAAK,MAAM,CAC1B,EAAE,IACF,sBAAsB,gBAAgB,EAAE,CAAC,CAC1C,CAAC,CACH;;;ACzBH,IAAa,eAAb,MAA0B;CACxB;CACA;CACA,WAA8B,EAAE;CAEhC,YAAY,YAAuB,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AC3B,OAAK,YAAY;;;CAInB,eAAe,MAAoB;AACjC,MAAI,KAAK,aAAa,KAAK,KAAK,KAAM;AACtC,YAAU,yBAAyB,KAAK,OAAO,QAAQ;AACvD,OAAK,aAAa,IAAI,KAAK;AAC3B,OAAK,YAAY;;CAGnB,IAAI,oBAA4B;AAC9B,SAAO,KAAK,mBAAmB,KAAK;;CAGtC,qBAAqB,KAAmB;AACtC,OAAK,mBAAmB,IAAI,IAAI;;CAGlC,IAAI,oBAA6B;AAC/B,SAAO,KAAK,mBAAmB,KAAK;;CAGtC,uBAA6B;AAC3B,OAAK,mBAAmB,IAAI,KAAK;AACjC,OAAK,YAAY;;CAGnB,UACE,OACM;EACN,MAAM,WAAW,MAAM,KAAK,MAAM;GAChC,MAAM,SAAS,aAAa,EAAE,OAAO,GAAG,EAAE,SAAA;AAC1C,UAAO;IACL,OAAO,EAAE;IACT,YAAY,EAAE;IACd;IACA,MAAM,WAAA;IACP;IACD;EAEF,MAAM,iBAAiB,IAAI,IAAI,SAAS,KAAK,MAAM,EAAE,MAAM,CAAC;EAE5D,MAAM,WAAW,KAAK,OACnB,KAAK,CACL,QAAQ,MAAM,EAAE,QAAQ,CAAC,eAAe,IAAI,EAAE,MAAM,CAAC;AAExD,OAAK,OAAO,IAAI,CAAC,GAAG,UAAU,GAAG,SAAS,CAAC;AAC3C,OAAK,YAAY;AACjB,OAAK,mBAAmB;;;CAI1B,IAAI,eAAe,IAAgB;AACjC,OAAK,kBAAkB;;CAKzB,UAAU,UAAkC;AAC1C,SAAO,KAAK,SAAS,aAAa,UAAU,CAAC;;CAG/C,cAAsB;AACpB,SAAO,KAAK,SAAS,KAAK"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { s as logToFile } from "./debug-
|
|
1
|
+
import { s as logToFile } from "./debug-CxHQG5NZ.js";
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
//#region src/lib/agent/runner/harness/pi/subagent.ts
|
|
@@ -105,4 +105,4 @@ function createDispatchAgentTool(ctx) {
|
|
|
105
105
|
//#endregion
|
|
106
106
|
export { createDispatchAgentTool };
|
|
107
107
|
|
|
108
|
-
//# sourceMappingURL=subagent-
|
|
108
|
+
//# sourceMappingURL=subagent-Dd4Hu0C5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-
|
|
1
|
+
{"version":3,"file":"subagent-Dd4Hu0C5.js","names":[],"sources":["../src/lib/agent/runner/harness/pi/subagent.ts"],"sourcesContent":["/**\n * Controlled subagent dispatch for pi (#526). pi has no native subagent\n * mechanism, so a subagent is a nested `createAgentSession` we construct — which\n * means WE decide its powers, closing the leak the claude-agent-sdk path warns\n * about (it can't propagate the parent's disallowedTools into subagents).\n *\n * Controls on every child:\n * - the SAME security extension (canUseTool + YARA, fail-closed) — shared state,\n * so the child shares the parent's tool-call cap and violation latch;\n * - a read-only built-in toolset (read/grep/find/ls + allowlisted bash) — no\n * write/edit, so a subagent can research but never mutate the project;\n * - no custom tools — no .env writes, and crucially no `dispatch_agent`, so a\n * child cannot recurse (depth is hard-capped at 1).\n */\n\nimport { Type } from 'typebox';\nimport { defineTool } from '@earendil-works/pi-coding-agent';\nimport type { ToolDefinition } from '@earendil-works/pi-coding-agent';\nimport { logToFile } from '@utils/debug';\n\n/**\n * Read-only built-ins a subagent may use. bash is supplied separately as the\n * parent's env-scrubbed tool (below), not the built-in, so a subagent's\n * subprocesses are locked down too.\n */\nconst SUBAGENT_TOOLS = ['read', 'grep', 'find', 'ls'];\n\nconst SUBAGENT_SYSTEM_PROMPT = [\n 'You are a read-only research subagent for the PostHog wizard.',\n 'You can read and search files and run safe build/inspect shell commands.',\n 'You cannot edit files, modify .env, or dispatch further subagents.',\n 'Investigate the task you are given and report concise findings as your final message.',\n].join('\\n');\n\nfunction text(s: string): {\n content: [{ type: 'text'; text: string }];\n details: unknown;\n} {\n return { content: [{ type: 'text', text: s }], details: {} };\n}\n\nfunction extractText(message: unknown): string {\n const content = (message as { content?: unknown })?.content;\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n return content\n .filter((c): c is { type: string; text: string } => {\n const b = c as { type?: string; text?: unknown };\n return b?.type === 'text' && typeof b.text === 'string';\n })\n .map((c) => c.text)\n .join('');\n }\n return '';\n}\n\nexport interface SubagentContext {\n /** Resolved gateway model (same as the parent). */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n model: import('@earendil-works/pi-ai').Model<any>;\n /** Registry holding the gateway provider. */\n modelRegistry: import('@earendil-works/pi-coding-agent').ModelRegistry;\n cwd: string;\n agentDir: string;\n /** The parent's security extension factory — reused so the fence is inherited. */\n securityFactory: (pi: unknown) => void;\n /** The parent's env-scrubbed bash, so a subagent's subprocesses are locked down too. */\n bashTool: ToolDefinition;\n /** pi SDK entrypoints, already imported by the backend. */\n sdk: {\n createAgentSession: typeof import('@earendil-works/pi-coding-agent')['createAgentSession'];\n DefaultResourceLoader: typeof import('@earendil-works/pi-coding-agent')['DefaultResourceLoader'];\n SessionManager: typeof import('@earendil-works/pi-coding-agent')['SessionManager'];\n };\n}\n\nexport function createDispatchAgentTool(ctx: SubagentContext): ToolDefinition {\n return defineTool({\n name: 'dispatch_agent',\n label: 'Dispatch subagent',\n description:\n 'Delegate a focused, read-only research subtask to a subagent (e.g. \"find where events are captured\"). The subagent can read/search files and run safe shell, but CANNOT edit files, change .env, or dispatch further subagents. Returns its findings.',\n promptSnippet:\n 'dispatch_agent(description, prompt) — delegate a read-only research subtask',\n parameters: Type.Object({\n description: Type.String({ description: 'Short label for the subtask' }),\n prompt: Type.String({ description: 'Full instruction for the subagent' }),\n }),\n // eslint-disable-next-line @typescript-eslint/require-await -- pi tool contract returns a Promise\n async execute(_id, args) {\n const { createAgentSession, DefaultResourceLoader, SessionManager } =\n ctx.sdk;\n\n const loader = new DefaultResourceLoader({\n cwd: ctx.cwd,\n agentDir: ctx.agentDir,\n systemPrompt: SUBAGENT_SYSTEM_PROMPT,\n noExtensions: true,\n noSkills: true,\n noContextFiles: true,\n noPromptTemplates: true,\n noThemes: true,\n extensionFactories: [ctx.securityFactory],\n });\n await loader.reload();\n\n const { session: child } = await createAgentSession({\n model: ctx.model,\n modelRegistry: ctx.modelRegistry,\n cwd: ctx.cwd,\n sessionManager: SessionManager.inMemory(ctx.cwd),\n resourceLoader: loader,\n tools: SUBAGENT_TOOLS, // read-only built-ins; no write/edit, no dispatch_agent\n customTools: [ctx.bashTool], // env-scrubbed bash only (still allowlist-fenced)\n });\n\n let result = '';\n const unsub = child.subscribe((e) => {\n if (e.type === 'message_end') {\n const t = extractText(e.message).trim();\n if (t) result = t;\n }\n });\n logToFile(`[pi] subagent dispatch: ${args.description}`);\n try {\n await child.prompt(args.prompt);\n } finally {\n unsub();\n }\n logToFile(`[pi] subagent \"${args.description}\" → ${result.length} chars`);\n return text(result || 'Subagent completed with no textual result.');\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAM,iBAAiB;CAAC;CAAQ;CAAQ;CAAQ;CAAK;AAErD,MAAM,yBAAyB;CAC7B;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,SAAS,KAAK,GAGZ;AACA,QAAO;EAAE,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAG,CAAC;EAAE,SAAS,EAAE;EAAE;;AAG9D,SAAS,YAAY,SAA0B;CAC7C,MAAM,UAAW,SAAmC;AACpD,KAAI,OAAO,YAAY,SAAU,QAAO;AACxC,KAAI,MAAM,QAAQ,QAAQ,CACxB,QAAO,QACJ,QAAQ,MAA2C;EAClD,MAAM,IAAI;AACV,SAAO,GAAG,SAAS,UAAU,OAAO,EAAE,SAAS;GAC/C,CACD,KAAK,MAAM,EAAE,KAAK,CAClB,KAAK,GAAG;AAEb,QAAO;;AAuBT,SAAgB,wBAAwB,KAAsC;AAC5E,QAAO,WAAW;EAChB,MAAM;EACN,OAAO;EACP,aACE;EACF,eACE;EACF,YAAY,KAAK,OAAO;GACtB,aAAa,KAAK,OAAO,EAAE,aAAa,+BAA+B,CAAC;GACxE,QAAQ,KAAK,OAAO,EAAE,aAAa,qCAAqC,CAAC;GAC1E,CAAC;EAEF,MAAM,QAAQ,KAAK,MAAM;GACvB,MAAM,EAAE,oBAAoB,uBAAuB,mBACjD,IAAI;GAEN,MAAM,SAAS,IAAI,sBAAsB;IACvC,KAAK,IAAI;IACT,UAAU,IAAI;IACd,cAAc;IACd,cAAc;IACd,UAAU;IACV,gBAAgB;IAChB,mBAAmB;IACnB,UAAU;IACV,oBAAoB,CAAC,IAAI,gBAAgB;IAC1C,CAAC;AACF,SAAM,OAAO,QAAQ;GAErB,MAAM,EAAE,SAAS,UAAU,MAAM,mBAAmB;IAClD,OAAO,IAAI;IACX,eAAe,IAAI;IACnB,KAAK,IAAI;IACT,gBAAgB,eAAe,SAAS,IAAI,IAAI;IAChD,gBAAgB;IAChB,OAAO;IACP,aAAa,CAAC,IAAI,SAAS;IAC5B,CAAC;GAEF,IAAI,SAAS;GACb,MAAM,QAAQ,MAAM,WAAW,MAAM;AACnC,QAAI,EAAE,SAAS,eAAe;KAC5B,MAAM,IAAI,YAAY,EAAE,QAAQ,CAAC,MAAM;AACvC,SAAI,EAAG,UAAS;;KAElB;AACF,aAAU,2BAA2B,KAAK,cAAc;AACxD,OAAI;AACF,UAAM,MAAM,OAAO,KAAK,OAAO;aACvB;AACR,WAAO;;AAET,aAAU,kBAAkB,KAAK,YAAY,MAAM,OAAO,OAAO,QAAQ;AACzE,UAAO,KAAK,UAAU,6CAA6C;;EAEtE,CAAC"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { f as getUI, ft as WIZARD_USER_AGENT, s as logToFile, ut as WIZARD_REMARK_EVENT_NAME } from "./debug-
|
|
2
|
-
import { n as analytics } from "./analytics-
|
|
3
|
-
import { c as TaskStatus } from "./queue-tools-
|
|
4
|
-
import {
|
|
5
|
-
import { i as lastStatusLine, n as buildScrubbedEnv, o as withMode, r as extractText, s as createAioCapture, t as applyOutroMarkers } from "./pi-
|
|
6
|
-
import { o as queueTools, s as renderToolInventory } from "./agent-prompt-loader-
|
|
1
|
+
import { f as getUI, ft as WIZARD_USER_AGENT, s as logToFile, ut as WIZARD_REMARK_EVENT_NAME } from "./debug-CxHQG5NZ.js";
|
|
2
|
+
import { n as analytics } from "./analytics-D8LSdEq7.js";
|
|
3
|
+
import { c as TaskStatus } from "./queue-tools-D2FgGSUY.js";
|
|
4
|
+
import { I as GATEWAY_PROVIDER, L as buildGatewayProvider, f as AgentOutputSignals, h as assembleCommandments, m as REMARK_INSTRUCTION } from "./agent-interface-DB8B9fET.js";
|
|
5
|
+
import { i as lastStatusLine, n as buildScrubbedEnv, o as withMode, r as extractText, s as createAioCapture, t as applyOutroMarkers } from "./pi-DNkD3usA.js";
|
|
6
|
+
import { o as queueTools, s as renderToolInventory } from "./agent-prompt-loader-tcJQ-23m.js";
|
|
7
7
|
//#region src/lib/agent/runner/harness/pi/task.ts
|
|
8
8
|
/**
|
|
9
9
|
* Orchestrator-mode execution on pi: one fresh pi session per unit of work —
|
|
@@ -113,18 +113,18 @@ async function runPiTask(inputs) {
|
|
|
113
113
|
error: "WIZARD_API_ERROR",
|
|
114
114
|
message: "pi: gateway model could not be resolved"
|
|
115
115
|
};
|
|
116
|
-
const { createSecurityExtension } = await import("./security-
|
|
116
|
+
const { createSecurityExtension } = await import("./security-Cb5pp8kB.js");
|
|
117
117
|
const security = createSecurityExtension({
|
|
118
118
|
disallowedTools: fenceDisallowList(disallowedTools),
|
|
119
119
|
triageProvider: boot.triageProvider
|
|
120
120
|
});
|
|
121
|
-
const { prewarmYaraScanner } = await import("./yara-hooks-
|
|
121
|
+
const { prewarmYaraScanner } = await import("./yara-hooks-lnituYce.js");
|
|
122
122
|
prewarmYaraScanner();
|
|
123
123
|
const extensionFactories = [security.factory];
|
|
124
124
|
let mcpCleanup;
|
|
125
125
|
let posthogMcp = false;
|
|
126
126
|
try {
|
|
127
|
-
const { setupPostHogMcp } = await import("./mcp-
|
|
127
|
+
const { setupPostHogMcp } = await import("./mcp-CRYv_nRt.js");
|
|
128
128
|
const mcp = await setupPostHogMcp({
|
|
129
129
|
mcpUrl: boot.credentials.host.mcpUrl,
|
|
130
130
|
accessToken: boot.credentials.accessToken,
|
|
@@ -176,7 +176,7 @@ async function runPiTask(inputs) {
|
|
|
176
176
|
find: () => withMode(createFindToolDefinition(dir), "parallel"),
|
|
177
177
|
grep: () => withMode(createGrepToolDefinition(dir), "parallel")
|
|
178
178
|
}).filter(([name]) => codingTools.has(name)).map(([, make]) => make());
|
|
179
|
-
const { createWizardPiTools } = await import("./tools-
|
|
179
|
+
const { createWizardPiTools } = await import("./tools-CzKtKaI1.js");
|
|
180
180
|
const wizardTools = createWizardPiTools({
|
|
181
181
|
workingDirectory: dir,
|
|
182
182
|
skillsBaseUrl: boot.skillsBaseUrl,
|
|
@@ -184,9 +184,10 @@ async function runPiTask(inputs) {
|
|
|
184
184
|
}).filter((t) => [
|
|
185
185
|
"check_env_keys",
|
|
186
186
|
"set_env_values",
|
|
187
|
-
"detect_package_manager"
|
|
187
|
+
"detect_package_manager",
|
|
188
|
+
"publish_handoff"
|
|
188
189
|
].includes(t.name));
|
|
189
|
-
const { createPiOrchestratorTools } = await import("./orchestrator-tools-
|
|
190
|
+
const { createPiOrchestratorTools } = await import("./orchestrator-tools-PXqRljoB.js");
|
|
190
191
|
const queueTools = createPiOrchestratorTools(orchestrator).filter((t) => orchestratorTools.has(t.name));
|
|
191
192
|
const customTools = [
|
|
192
193
|
...codingToolDefs,
|
|
@@ -300,4 +301,4 @@ async function runPiTask(inputs) {
|
|
|
300
301
|
//#endregion
|
|
301
302
|
export { runPiTask };
|
|
302
303
|
|
|
303
|
-
//# sourceMappingURL=task-
|
|
304
|
+
//# sourceMappingURL=task-CpU_54NS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"task-CpU_54NS.js","names":[],"sources":["../src/lib/agent/runner/harness/pi/task.ts"],"sourcesContent":["/**\n * Orchestrator-mode execution on pi: one fresh pi session per unit of work —\n * the seed plan, or one drained task. The linear pipeline's concerns (skill\n * menu, todo panel, event-plan cleanup) stay in `index.ts`; this module builds\n * the leaner per-task session: gateway model, security fence, the task's\n * allowed coding tools, the wizard env tools, and the in-process orchestrator\n * queue tools.\n *\n * The task's `allowedTools` / `disallowedTools` arrive in the wizard's tool\n * vocabulary (`Read`, `Edit`, `Glob`, …, plus MCP-qualified orchestrator names\n * from `agentRunTools`). pi is where they become real: allowed names decide\n * which pi tool definitions get registered at all, and the disallow list is\n * ALSO handed to the security fence, so a name that never got registered stays\n * blocked even if the model hallucinates it.\n *\n * Loaded lazily from `index.ts` (typebox/ESM constraint, same as tools.ts).\n */\n\nimport { getUI } from '@ui';\nimport { logToFile } from '@utils/debug';\nimport { analytics } from '@utils/analytics';\nimport {\n Harness,\n Sequence,\n WIZARD_REMARK_EVENT_NAME,\n WIZARD_USER_AGENT,\n} from '@lib/constants';\nimport {\n queueTools,\n renderToolInventory,\n} from '@lib/agent/agent-prompt-loader';\nimport { AgentErrorType } from '@lib/agent/agent-interface';\nimport { REMARK_INSTRUCTION } from '@lib/agent/signals';\nimport { AgentOutputSignals } from '@lib/agent/output-signals';\nimport { TaskStatus } from '../../sequence/orchestrator/queue';\nimport type { OrchestratorToolsContext } from '../../sequence/orchestrator/queue-tools';\nimport type { AgentResult, TaskRunInputs } from '../types';\nimport { buildGatewayProvider, GATEWAY_PROVIDER } from './gateway';\nimport { assembleCommandments } from '../../switchboard/commandments';\nimport {\n applyOutroMarkers,\n buildScrubbedEnv,\n extractText,\n lastStatusLine,\n withMode,\n} from './index';\nimport { createAioCapture } from '@lib/agent/aio-capture';\n\n/** wizard tool vocabulary → the pi tool definitions it unlocks. */\nconst CODING_TOOL_MAP: Record<string, readonly string[]> = {\n Read: ['read'],\n Edit: ['edit'],\n Write: ['write'],\n Bash: ['bash'],\n Glob: ['find', 'ls'],\n Grep: ['grep'],\n};\n\n/** `mcp__posthog-wizard__enqueue_task` → `enqueue_task`; native names pass through. */\nfunction shortToolName(name: string): string {\n return name.replace(/^mcp__posthog-wizard__/, '');\n}\n\n/**\n * The pi coding tools a task may use. An empty allow list means \"no\n * restriction\" (mirrors the SDK), so every coding tool registers.\n */\nexport function allowedPiCodingTools(\n allowedTools: readonly string[] | undefined,\n): Set<string> {\n const allowed = (allowedTools ?? []).map(shortToolName);\n const names = allowed.length\n ? allowed.flatMap((name) => CODING_TOOL_MAP[name] ?? [])\n : Object.values(CODING_TOOL_MAP).flat();\n return new Set(names);\n}\n\n/**\n * The orchestrator queue tools this agent gets. Everything not disallowed:\n * the seed's frontmatter disallows `complete_task` (it is not a task), a\n * task's disallows `enqueue_task` (the seed owns the graph).\n */\nexport function allowedOrchestratorTools(\n disallowedTools: readonly string[] | undefined,\n): Set<string> {\n return new Set(queueTools(disallowedTools ?? []));\n}\n\n/**\n * The disallow list for the security fence: the wizard-vocabulary names as\n * given (the fence translates pi built-ins to the same vocabulary) plus the\n * short names, so a disallowed orchestrator tool is blocked under the name pi\n * would call it by.\n */\nexport function fenceDisallowList(\n disallowedTools: readonly string[] | undefined,\n): string[] {\n const names = disallowedTools ?? [];\n return [...new Set([...names, ...names.map(shortToolName)])];\n}\n\n/** Nudges when the session returns without the work reaching a terminal state. */\nconst MAX_TASK_NUDGES = 3;\n\nconst TASK_NUDGE =\n 'You have not called complete_task yet. Finish your task now: if the work is done, call complete_task with your handoff; if it cannot be done, call it with status \"failed\" or \"not needed\" and say why.';\n\nconst SEED_NUDGE =\n 'The queue is still empty. Seed it now with enqueue_task calls for the task graph you planned.';\n\n/** Whether this unit of work has reached its terminal state. */\nfunction isSettled(ctx: OrchestratorToolsContext): boolean {\n if (!ctx.currentTaskId) {\n // The seed's job is a seeded queue, not a complete_task call.\n return ctx.store.list().length > 0;\n }\n const task = ctx.store.get(ctx.currentTaskId);\n return (\n !!task &&\n (task.status === TaskStatus.Done ||\n task.status === TaskStatus.Failed ||\n task.status === TaskStatus.Skipped)\n );\n}\n\nexport async function runPiTask(inputs: TaskRunInputs): Promise<AgentResult> {\n const {\n session,\n programConfig,\n boot,\n prompt,\n spinner,\n model: modelId,\n effort,\n allowedTools,\n disallowedTools,\n orchestrator,\n spinnerMessage,\n successMessage,\n errorMessage,\n requestRemark,\n analyticsProperties,\n } = inputs;\n\n if (spinnerMessage) spinner.start(spinnerMessage);\n\n const capture = createAioCapture({\n enabled: session.captureAio,\n projectApiKey: boot.credentials.projectApiKey,\n apiHost: boot.credentials.host.apiHost,\n runTags: boot.wizardMetadata,\n });\n\n const startTime = Date.now();\n const signals = new AgentOutputSignals();\n let assistantTurns = 0;\n const runDurations = () => {\n const durationMs = Date.now() - startTime;\n return {\n duration_ms: durationMs,\n duration_seconds: Math.round(durationMs / 1000),\n };\n };\n const captureAborted = () =>\n analytics.wizardCapture('agent aborted', {\n ...runDurations(),\n model: modelId,\n ...analyticsProperties,\n });\n\n try {\n const sdk = await import('@earendil-works/pi-coding-agent');\n const {\n createAgentSession,\n DefaultResourceLoader,\n SessionManager,\n AuthStorage,\n ModelRegistry,\n getAgentDir,\n createLsToolDefinition,\n createFindToolDefinition,\n createGrepToolDefinition,\n createBashToolDefinition,\n createReadToolDefinition,\n createEditToolDefinition,\n createWriteToolDefinition,\n } = sdk;\n\n const { provider, caps } = buildGatewayProvider({\n gatewayUrl: boot.credentials.host.gatewayUrl,\n accessToken: boot.credentials.accessToken,\n wizardMetadata: boot.wizardMetadata,\n wizardFlags: boot.wizardFlags,\n modelId,\n // Per-task agents own their effort via the prompt frontmatter, falling\n // back to the model table.\n effort,\n });\n const registry = ModelRegistry.inMemory(AuthStorage.create());\n registry.registerProvider(GATEWAY_PROVIDER, provider as never);\n const model = registry.find(GATEWAY_PROVIDER, modelId);\n if (!model) {\n return {\n error: AgentErrorType.API_ERROR,\n message: 'pi: gateway model could not be resolved',\n };\n }\n\n // The same fail-closed fence as the linear run, with the task's disallow\n // list layered in (both the wizard-vocabulary and pi-short names).\n const { createSecurityExtension } = await import('./security');\n const security = createSecurityExtension({\n disallowedTools: fenceDisallowList(disallowedTools),\n triageProvider: boot.triageProvider,\n });\n const { prewarmYaraScanner } = await import('@lib/yara-hooks');\n void prewarmYaraScanner();\n\n // PostHog MCP, best-effort — the dashboard task creates real dashboards\n // through it; every other task simply never calls a posthog_* tool.\n const extensionFactories = [security.factory] as Array<\n (pi: unknown) => void\n >;\n let mcpCleanup: (() => void) | undefined;\n let posthogMcp = false;\n try {\n const { setupPostHogMcp } = await import('./mcp');\n const mcp = await setupPostHogMcp({\n mcpUrl: boot.credentials.host.mcpUrl,\n accessToken: boot.credentials.accessToken,\n userAgent: WIZARD_USER_AGENT,\n });\n extensionFactories.push(mcp.extensionFactory);\n mcpCleanup = mcp.cleanup;\n posthogMcp = true;\n } catch (err) {\n // Silent here reads as a task failure minutes later: dashboard and report\n // need `posthog_exec` and can only skip or fail without it.\n logToFile(`[pi-task] PostHog MCP setup skipped: ${String(err)}`);\n analytics.wizardCapture('mcp setup failed', {\n harness: 'pi',\n scope: 'task',\n error: String(err).slice(0, 300),\n });\n }\n\n const codingTools = allowedPiCodingTools(allowedTools);\n const orchestratorTools = allowedOrchestratorTools(disallowedTools);\n\n const resourceLoader = new DefaultResourceLoader({\n cwd: session.installDir,\n agentDir: getAgentDir(),\n systemPrompt: assembleCommandments({\n program: programConfig.id,\n sequence: Sequence.orchestrator,\n harness: Harness.pi,\n caps: { bash: codingTools.has('bash'), posthogMcp },\n }),\n noExtensions: true,\n noSkills: true,\n noContextFiles: true,\n noPromptTemplates: true,\n noThemes: true,\n extensionFactories,\n });\n await resourceLoader.reload();\n\n // The task's coding tools, gated by its allow list. Reads and searches run\n // in parallel; mutating tools stay sequential. Bash subprocesses get the\n // scrubbed env, same as the linear run.\n const dir = session.installDir;\n const codingToolFactories = {\n read: () => withMode(createReadToolDefinition(dir), 'parallel'),\n edit: () => withMode(createEditToolDefinition(dir), 'sequential'),\n write: () => withMode(createWriteToolDefinition(dir), 'sequential'),\n bash: () =>\n withMode(\n createBashToolDefinition(dir, {\n spawnHook: (ctx) => ({ ...ctx, env: buildScrubbedEnv() }),\n }),\n 'sequential',\n ),\n ls: () => withMode(createLsToolDefinition(dir), 'parallel'),\n find: () => withMode(createFindToolDefinition(dir), 'parallel'),\n grep: () => withMode(createGrepToolDefinition(dir), 'parallel'),\n } as const;\n const codingToolDefs = Object.entries(codingToolFactories)\n .filter(([name]) => codingTools.has(name))\n .map(([, make]) => make());\n\n // Wizard env + package-manager tools are always on — their handlers are\n // fenced, and init/build tasks depend on them. publish_handoff rides\n // along (store-only handler) so the report task can publish the handoff.\n const { createWizardPiTools } = await import('./tools');\n const wizardTools = createWizardPiTools({\n workingDirectory: dir,\n skillsBaseUrl: boot.skillsBaseUrl,\n triageProvider: boot.triageProvider,\n }).filter((t) =>\n [\n 'check_env_keys',\n 'set_env_values',\n 'detect_package_manager',\n 'publish_handoff',\n ].includes(t.name),\n );\n\n const { createPiOrchestratorTools } = await import('./orchestrator-tools');\n const queueTools = createPiOrchestratorTools(orchestrator).filter((t) =>\n orchestratorTools.has(t.name),\n );\n\n const customTools = [...codingToolDefs, ...wizardTools, ...queueTools];\n const { session: agentSession } = await createAgentSession({\n model,\n modelRegistry: registry,\n thinkingLevel: caps.thinkingLevel,\n cwd: dir,\n sessionManager: SessionManager.inMemory(dir),\n resourceLoader,\n noTools: 'builtin',\n customTools,\n });\n await agentSession.bindExtensions({});\n\n // The one complete list: exactly the tools registered on this session, in\n // the names the agent will call them by. posthog_exec binds as an extension.\n const toolNames = [\n ...customTools.map((t) => t.name),\n ...(posthogMcp ? ['posthog_exec'] : []),\n ];\n logToFile(`[pi-task] tools passed to model: ${toolNames.join(', ')}`);\n const taskPrompt = `${prompt}\\n\\n${renderToolInventory(toolNames)}`;\n\n const unsubscribe = agentSession.subscribe((event) => {\n // Mirror the turn into AIO. No-op when --capture-aio is off. Runs\n // before the role guard so the module's own filter is authoritative.\n capture.captureFromPiMessageEndEvent(event);\n\n switch (event.type) {\n case 'message_end': {\n // User prompts also emit message_end; only assistant turns count.\n if ((event.message as { role?: string })?.role !== 'assistant') {\n break;\n }\n assistantTurns += 1;\n const assistant = extractText(event.message).trim();\n if (assistant) {\n logToFile(`[pi-task] assistant: ${assistant.slice(0, 1000)}`);\n applyOutroMarkers(assistant);\n const statusText = lastStatusLine(assistant);\n if (statusText) {\n getUI().pushStatus(statusText);\n spinner.message(statusText);\n }\n for (const line of assistant.split('\\n')) signals.push(line);\n }\n break;\n }\n case 'tool_execution_start': {\n const args = JSON.stringify(event.args ?? {}).slice(0, 200);\n logToFile(`[pi-task] → ${event.toolName} ${args}`);\n break;\n }\n case 'tool_execution_end': {\n if (event.isError) {\n const detail =\n typeof event.result === 'string'\n ? event.result\n : JSON.stringify(event.result ?? '');\n logToFile(`[pi-task] ✗ ${event.toolName}: ${detail.slice(0, 300)}`);\n }\n break;\n }\n default:\n break;\n }\n });\n\n // Seed AIO capture with this task's prompt — includes any handoff data\n // from prior tasks (the orchestrator bakes it into the prompt string\n // before it reaches this call site).\n capture.setInitialPrompt(taskPrompt);\n\n try {\n await agentSession.prompt(taskPrompt);\n\n // pi's prompt() resolves the moment a turn carries no tool call — which\n // an agent mid-plan does emit. While the work has not reached its\n // terminal state (task not reported, seed queue still empty), nudge.\n let nudges = 0;\n while (\n nudges < MAX_TASK_NUDGES &&\n !security.state.criticalViolation &&\n !isSettled(orchestrator)\n ) {\n nudges += 1;\n logToFile(\n `[pi-task] completion guard: not settled, nudge ${nudges}/${MAX_TASK_NUDGES}`,\n );\n await agentSession.prompt(\n orchestrator.currentTaskId ? TASK_NUDGE : SEED_NUDGE,\n );\n }\n\n if (requestRemark && !security.state.criticalViolation) {\n try {\n await agentSession.prompt(REMARK_INSTRUCTION);\n } catch (err) {\n logToFile(`[pi-task] remark request failed: ${String(err)}`);\n }\n }\n } finally {\n unsubscribe();\n mcpCleanup?.();\n }\n\n if (security.state.criticalViolation) {\n spinner.stop('Security violation detected');\n logToFile(\n `[pi-task] terminated: YARA violation (blocked ${security.state.blockedCount} call(s))`,\n );\n captureAborted();\n return { error: AgentErrorType.YARA_VIOLATION };\n }\n\n const remark = signals.remark();\n if (remark) {\n analytics.capture(WIZARD_REMARK_EVENT_NAME, { remark });\n }\n\n const stats = agentSession.getSessionStats();\n const durations = runDurations();\n analytics.wizardCapture('agent completed', {\n ...durations,\n model: modelId,\n num_turns: assistantTurns,\n input_tokens: stats.tokens.input,\n output_tokens: stats.tokens.output,\n cache_creation_input_tokens: stats.tokens.cacheWrite,\n cache_read_input_tokens: stats.tokens.cacheRead,\n ...analyticsProperties,\n });\n // Per-task usage on one parseable line so a run's per-task time and cost are\n // observable from the log, not only from analytics.\n const taskType =\n typeof (analyticsProperties as { task_type?: unknown })?.task_type ===\n 'string'\n ? (analyticsProperties as { task_type: string }).task_type\n : modelId;\n logToFile(\n `[pi-task] usage task=${taskType} model=${modelId} effort=${caps.thinkingLevel} dur=${durations.duration_seconds}s turns=${assistantTurns} in=${stats.tokens.input} out=${stats.tokens.output} cacheR=${stats.tokens.cacheRead} cacheW=${stats.tokens.cacheWrite}`,\n );\n if (successMessage) spinner.stop(successMessage);\n return {};\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logToFile(`[pi-task] run error: ${message}`);\n if (errorMessage || spinnerMessage) {\n spinner.stop(errorMessage ?? 'Task failed');\n }\n captureAborted();\n const lower = message.toLowerCase();\n if (lower.includes('rate limit') || lower.includes('429')) {\n return { error: AgentErrorType.RATE_LIMIT, message };\n }\n return { error: AgentErrorType.API_ERROR, message };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,kBAAqD;CACzD,MAAM,CAAC,OAAO;CACd,MAAM,CAAC,OAAO;CACd,OAAO,CAAC,QAAQ;CAChB,MAAM,CAAC,OAAO;CACd,MAAM,CAAC,QAAQ,KAAK;CACpB,MAAM,CAAC,OAAO;CACf;;AAGD,SAAS,cAAc,MAA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,OAAO,MAAM,OAAO,OAAO,UAAU,MAAM,OAAO,UAAU,UAAU,MAAM,OAAO,aACvP;AACD,MAAI,eAAgB,SAAQ,KAAK,eAAe;AAChD,SAAO,EAAE;UACF,KAAK;EACZ,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;AAChE,YAAU,wBAAwB,UAAU;AAC5C,MAAI,gBAAgB,eAClB,SAAQ,KAAK,gBAAgB,cAAc;AAE7C,kBAAgB;EAChB,MAAM,QAAQ,QAAQ,aAAa;AACnC,MAAI,MAAM,SAAS,aAAa,IAAI,MAAM,SAAS,MAAM,CACvD,QAAO;GAAE,OAAA;GAAkC;GAAS;AAEtD,SAAO;GAAE,OAAA;GAAiC;GAAS"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import "./debug-
|
|
1
|
+
import { s as logToFile } from "./debug-CxHQG5NZ.js";
|
|
2
2
|
import "./wizard-session-CwgR5y3-.js";
|
|
3
|
-
import { PostHogDestination } from "./posthog-
|
|
4
|
-
import { t as startFileWatcher } from "./file-watcher-
|
|
3
|
+
import { PostHogDestination } from "./posthog-B6grWFSr.js";
|
|
4
|
+
import { t as startFileWatcher } from "./file-watcher-Bw5wz1_R.js";
|
|
5
5
|
//#region src/lib/task-stream/event-plan-watcher.ts
|
|
6
6
|
const MAX_EVENT_PLAN_FILE_BYTES = 256 * 1024;
|
|
7
7
|
const MAX_EVENT_COUNT = 50;
|
|
@@ -249,7 +249,7 @@ var TaskStreamPush = class {
|
|
|
249
249
|
return this.inFlight;
|
|
250
250
|
}
|
|
251
251
|
async sendOnce() {
|
|
252
|
-
const { session, tasks, eventPlan } = this.store;
|
|
252
|
+
const { session, tasks, eventPlan, handoffText } = this.store;
|
|
253
253
|
const skillId = sanitizeChannelId(session.skillId ?? this.programId);
|
|
254
254
|
const phase = session.runPhase;
|
|
255
255
|
const payload = {
|
|
@@ -262,8 +262,10 @@ var TaskStreamPush = class {
|
|
|
262
262
|
event_plan: eventPlan.length > 0 ? { events: eventPlan } : void 0,
|
|
263
263
|
error: buildError(phase, session.outroData),
|
|
264
264
|
pending_input: buildPendingInput(session.pendingQuestion),
|
|
265
|
+
handoff_text: handoffText ?? void 0,
|
|
265
266
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
266
267
|
};
|
|
268
|
+
logToFile(`[task-stream-push] push phase=${phase} handoff_text=${handoffText === null ? "absent" : `${handoffText.length} chars`}`);
|
|
267
269
|
let event;
|
|
268
270
|
if (!this.created) {
|
|
269
271
|
this.created = true;
|
|
@@ -279,4 +281,4 @@ var TaskStreamPush = class {
|
|
|
279
281
|
//#endregion
|
|
280
282
|
export { PostHogDestination, TaskStreamPush };
|
|
281
283
|
|
|
282
|
-
//# sourceMappingURL=task-stream-
|
|
284
|
+
//# sourceMappingURL=task-stream-C_xfqch0.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"task-stream-C_xfqch0.js","names":[],"sources":["../src/lib/task-stream/event-plan-watcher.ts","../src/lib/task-stream/task-stream-push.ts"],"sourcesContent":["import type { PlannedEvent, WizardStore } from '@ui/tui/store';\nimport {\n startFileWatcher,\n type FileWatcherHandle,\n type FileWatcherOptions,\n} from '@lib/file-watcher';\n\nconst MAX_EVENT_PLAN_FILE_BYTES = 256 * 1024;\nconst MAX_EVENT_COUNT = 50;\nconst MAX_EVENT_NAME_LENGTH = 400;\nconst MAX_EVENT_DESCRIPTION_LENGTH = 4000;\n\nfunction firstString(...values: unknown[]): string | null {\n const value = values.find((candidate) => typeof candidate === 'string');\n return typeof value === 'string' ? value : null;\n}\n\nexport function normalizeEventPlan(parsed: unknown): PlannedEvent[] | null {\n if (!Array.isArray(parsed)) return null;\n\n const events: PlannedEvent[] = [];\n for (const value of parsed) {\n if (events.length >= MAX_EVENT_COUNT) break;\n\n const entry =\n value && typeof value === 'object'\n ? (value as Record<string, unknown>)\n : {};\n const name = firstString(entry.event_name, entry.name, entry.event);\n if (!name || !name.trim() || name.length > MAX_EVENT_NAME_LENGTH) continue;\n\n const description =\n firstString(entry.event_description, entry.description) ?? '';\n events.push({\n name,\n description: description.slice(0, MAX_EVENT_DESCRIPTION_LENGTH),\n });\n }\n\n return events;\n}\n\nexport class EventPlanWatcher {\n private handle: FileWatcherHandle | null = null;\n private captured = false;\n\n constructor(\n private readonly store: WizardStore,\n private readonly path: string,\n private readonly options: FileWatcherOptions = {},\n ) {}\n\n start(): void {\n if (this.handle || this.captured) return;\n\n this.handle = startFileWatcher(\n this.path,\n (parsed) => {\n const events = normalizeEventPlan(parsed);\n if (!events || events.length === 0) return;\n\n this.captured = true;\n this.store.setEventPlan(events);\n this.stop();\n },\n {\n ignoreInitialFile: true,\n maxFileSizeBytes: MAX_EVENT_PLAN_FILE_BYTES,\n ...this.options,\n },\n );\n }\n\n refresh(): void {\n if (this.captured) return;\n this.handle?.refresh();\n }\n\n stop(): void {\n this.handle?.stop();\n this.handle = null;\n }\n}\n","/**\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 destination delivery is disabled\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 {\n RunPhase,\n OutroKind,\n type OutroData,\n type PendingQuestion,\n} from '@lib/wizard-session';\nimport {\n type TaskStreamDestination,\n type TaskStreamUpdate,\n type StreamTask,\n type TaskStreamError,\n type StreamPendingInput,\n StreamTaskStatus,\n StreamEvent,\n} from './types';\nimport { EventPlanWatcher } from './event-plan-watcher';\nimport { logToFile } from '@utils/debug';\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 // The stream has no skipped state; skipped is terminal, so report it resolved.\n [TaskStatus.Skipped]: 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\n/**\n * Sensitive asks (secrets, API keys) publish only the fact that input is\n * required — never the prompt text. The session row is team-visible and\n * outlives the prompt.\n */\nfunction buildPendingInput(\n question: PendingQuestion | null | undefined,\n): StreamPendingInput | undefined {\n if (!question) return undefined;\n const sensitive = question.questions.some((q) => q.sensitive === true);\n return {\n id: question.id,\n asked_at: question.askedAt ?? new Date().toISOString(),\n question_count: question.questions.length,\n sensitive,\n prompts: sensitive ? undefined : question.questions.map((q) => q.prompt),\n };\n}\n\nexport interface TaskStreamPushOptions {\n store: WizardStore;\n programId: string;\n destinations: TaskStreamDestination[];\n /** Optional absolute event-plan path to load into the store once. */\n eventPlanPath?: string;\n /** When false, destination subscription/delivery remains disabled. */\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 private readonly eventPlanWatcher: EventPlanWatcher | null;\n\n private enabled: boolean;\n private created = false;\n private lastPushedPhase: RunPhase | null = null;\n private lastPushedQuestionId: string | 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 const startedAt = new Date();\n this.eventPlanWatcher = opts.eventPlanPath\n ? new EventPlanWatcher(this.store, opts.eventPlanPath)\n : null;\n this.startedAt = secondPrecisionIso(startedAt);\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 * Load the event plan and subscribe to store changes. Destination delivery\n * remains disabled when `enabled === false`, but the plan still populates the\n * store for local and headless consumers.\n */\n attach(store?: WizardStore): void {\n this.eventPlanWatcher?.start();\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 this.eventPlanWatcher?.stop();\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 this.eventPlanWatcher?.refresh();\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 const questionId = this.store.session.pendingQuestion?.id ?? null;\n const questionChanged = questionId !== this.lastPushedQuestionId;\n if (phaseChanged || questionChanged) {\n // Phase transitions bypass the debounce: the web app needs to\n // see Running → Completed as soon as it lands. A wizard_ask\n // opening or closing is the same shape — the whole point of\n // publishing it is that the user is looking at the web app, so\n // a 250ms-stale \"needs your input\" defeats the purpose.\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, handoffText } = 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 pending_input: buildPendingInput(session.pendingQuestion),\n // Included on every push once captured; the backend keeps it sticky, so\n // pushes that raced the capture cannot un-set it.\n handoff_text: handoffText ?? undefined,\n timestamp: new Date().toISOString(),\n };\n logToFile(\n `[task-stream-push] push phase=${phase} handoff_text=${\n handoffText === null ? 'absent' : `${handoffText.length} chars`\n }`,\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 this.lastPushedQuestionId = payload.pending_input?.id ?? null;\n\n await Promise.all(\n this.destinations.map((d) =>\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,OAAO,WAAW,OAAO,QAAQ,UAAU;GAC3C,eAAe,kBAAkB,QAAQ,gBAAgB;GAGzD,cAAc,eAAe,KAAA;GAC7B,4BAAW,IAAI,MAAM,EAAC,aAAa;GACpC;AACD,YACE,iCAAiC,MAAM,gBACrC,gBAAgB,OAAO,WAAW,GAAG,YAAY,OAAO,UAE3D;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;AACvB,OAAK,uBAAuB,QAAQ,eAAe,MAAM;AAEzD,QAAM,QAAQ,IACZ,KAAK,aAAa,KAAK,MAErB,EAAE,KAAK,OAAO,QAAQ,CAAC,YAAY,GAAG,CACvC,CACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as getUI } from "./debug-
|
|
1
|
+
import { f as getUI } from "./debug-CxHQG5NZ.js";
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
//#region src/lib/agent/runner/harness/pi/tasks.ts
|
|
@@ -109,4 +109,4 @@ function createWizardPiTaskTools() {
|
|
|
109
109
|
//#endregion
|
|
110
110
|
export { createWizardPiTaskTools };
|
|
111
111
|
|
|
112
|
-
//# sourceMappingURL=tasks-
|
|
112
|
+
//# sourceMappingURL=tasks-Bfw6gqOO.js.map
|