@posthog/wizard 2.66.0 → 2.68.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-DWDEuDUR.js → add-mcp-server-to-clients-y0swAr9I.js} +25 -25
- package/dist/{add-mcp-server-to-clients-DWDEuDUR.js.map → add-mcp-server-to-clients-y0swAr9I.js.map} +1 -1
- package/dist/{agent-interface-D3MNaDp3.js → agent-interface-CaEptZuu.js} +404 -73
- package/dist/agent-interface-CaEptZuu.js.map +1 -0
- package/dist/{agent-prompt-loader-D8Bajo-L.js → agent-prompt-loader-DZHc9tIG.js} +5 -5
- package/dist/{agent-prompt-loader-D8Bajo-L.js.map → agent-prompt-loader-DZHc9tIG.js.map} +1 -1
- package/dist/{agent-runner-DEeMqJxy.js → agent-runner-Do5kyhPo.js} +85 -39
- package/dist/agent-runner-Do5kyhPo.js.map +1 -0
- package/dist/analytics-BNCWoTKa.js +2 -0
- package/dist/{analytics-D8JNuPAT.js → analytics-tF06lcmE.js} +2 -2
- package/dist/{analytics-D8JNuPAT.js.map → analytics-tF06lcmE.js.map} +1 -1
- package/dist/{api-CemGgyBv.js → api-D7-8R4xx.js} +3 -3
- package/dist/{api-CemGgyBv.js.map → api-D7-8R4xx.js.map} +1 -1
- package/dist/bin.js +200 -85
- package/dist/bin.js.map +1 -1
- package/dist/{bounded-fs-C6OjqZst.js → bounded-fs-BwuqKpBH.js} +3 -3
- package/dist/{bounded-fs-C6OjqZst.js.map → bounded-fs-BwuqKpBH.js.map} +1 -1
- package/dist/{ci-install-DIB2n4Ju.js → ci-install-CrqqhXAw.js} +18 -9
- package/dist/ci-install-CrqqhXAw.js.map +1 -0
- package/dist/{debug-H-GTKvvU.js → debug-CWn7PsPd.js} +1 -1
- package/dist/{debug-BKqv-yfT.js → debug-aA5dm2MR.js} +4 -4
- package/dist/debug-aA5dm2MR.js.map +1 -0
- package/dist/{defaults-BHhXrX9F.js → defaults-DI642M3n.js} +1 -1
- package/dist/{defaults-BHhXrX9F.js.map → defaults-DI642M3n.js.map} +1 -1
- package/dist/{env-api-key-CzHDwfV2.js → env-api-key-CwkRyrgi.js} +2 -2
- package/dist/{env-api-key-CzHDwfV2.js.map → env-api-key-CwkRyrgi.js.map} +1 -1
- package/dist/environment-BGUJxuvj.js +44 -0
- package/dist/environment-BGUJxuvj.js.map +1 -0
- package/dist/errors-BHervYGs.js +156 -0
- package/dist/errors-BHervYGs.js.map +1 -0
- package/dist/{file-watcher-Cr-4tA-e.js → file-watcher-Cn7tD95m.js} +2 -2
- package/dist/{file-watcher-Cr-4tA-e.js.map → file-watcher-Cn7tD95m.js.map} +1 -1
- package/dist/{headless-ui-DT3Db1bk.js → headless-ui-DtIYZNVv.js} +2 -2
- package/dist/{headless-ui-DT3Db1bk.js.map → headless-ui-DtIYZNVv.js.map} +1 -1
- package/dist/{interactive-D3LdFxZG.js → interactive-BRB6w6KG.js} +2 -2
- package/dist/{interactive-D3LdFxZG.js.map → interactive-BRB6w6KG.js.map} +1 -1
- package/dist/{local-dev-BN6NKQ0B.js → local-dev-DPZiIPCK.js} +1 -1
- package/dist/{local-dev-BN6NKQ0B.js.map → local-dev-DPZiIPCK.js.map} +1 -1
- package/dist/{mcp-BjckYQmP.js → mcp-BXdSTZe6.js} +2 -2
- package/dist/{mcp-BjckYQmP.js.map → mcp-BXdSTZe6.js.map} +1 -1
- package/dist/{mcp-prompt-streaming--sRErHKv.js → mcp-prompt-streaming-DhOT15Jj.js} +13 -12
- package/dist/mcp-prompt-streaming-DhOT15Jj.js.map +1 -0
- package/dist/{non-interactive-CNoYoEZp.js → non-interactive-ezilF3PY.js} +7 -2
- package/dist/non-interactive-ezilF3PY.js.map +1 -0
- package/dist/{orchestrator-tools-8bGyDDhn.js → orchestrator-tools-D82843t_.js} +3 -3
- package/dist/{orchestrator-tools-8bGyDDhn.js.map → orchestrator-tools-D82843t_.js.map} +1 -1
- package/dist/{package-json-D0DCWpe5.js → package-json-GEU2VZlS.js} +1 -1
- package/dist/{package-json-D0DCWpe5.js.map → package-json-GEU2VZlS.js.map} +1 -1
- package/dist/{package-manager-BQDHm7ER.js → package-manager-BPoVLj7W.js} +4 -4
- package/dist/package-manager-BPoVLj7W.js.map +1 -0
- package/dist/{pi-W-4RUPFY.js → pi-CKyt4bcu.js} +17 -13
- package/dist/pi-CKyt4bcu.js.map +1 -0
- package/dist/{playground-uHHgZChe.js → playground-Dnyb4jLu.js} +7 -7
- package/dist/{playground-uHHgZChe.js.map → playground-Dnyb4jLu.js.map} +1 -1
- package/dist/{posthog-ChzdlmCs.js → posthog-BHyJiU05.js} +2 -2
- package/dist/{posthog-ChzdlmCs.js.map → posthog-BHyJiU05.js.map} +1 -1
- package/dist/{posthog-integration-LxEBGkoe.js → posthog-integration-DJX4qTDQ.js} +22 -17
- package/dist/posthog-integration-DJX4qTDQ.js.map +1 -0
- package/dist/{provisioning-BHTl91OZ.js → provisioning-DEEt9xl4.js} +3 -3
- package/dist/{provisioning-BHTl91OZ.js.map → provisioning-DEEt9xl4.js.map} +1 -1
- package/dist/{queue-tools-DABh1Ssc.js → queue-tools-i_TmeI02.js} +3 -3
- package/dist/{queue-tools-DABh1Ssc.js.map → queue-tools-i_TmeI02.js.map} +1 -1
- package/dist/{registry-CxNpCNAj.js → registry-CbXqxcX0.js} +81 -81
- package/dist/{registry-CxNpCNAj.js.map → registry-CbXqxcX0.js.map} +1 -1
- package/dist/{security-B4jU_-7q.js → security-DZ1rkONB.js} +21 -9
- package/dist/security-DZ1rkONB.js.map +1 -0
- package/dist/{setup-utils-aWZEdfwh.js → setup-utils-BLKhAx6g.js} +13 -13
- package/dist/{setup-utils-aWZEdfwh.js.map → setup-utils-BLKhAx6g.js.map} +1 -1
- package/dist/{start-tui-BQH4mQIZ.js → start-tui-D1MqJVT1.js} +33 -23
- package/dist/start-tui-D1MqJVT1.js.map +1 -0
- package/dist/{steps-5HAqjUvn.js → steps-Dsw-zBET.js} +7 -7
- package/dist/{steps-5HAqjUvn.js.map → steps-Dsw-zBET.js.map} +1 -1
- package/dist/{store-P_7zUfbj.js → store-OGBMWp3H.js} +5 -5
- package/dist/{store-P_7zUfbj.js.map → store-OGBMWp3H.js.map} +1 -1
- package/dist/{subagent-uGPDXPfS.js → subagent-DrnKYgvu.js} +2 -2
- package/dist/{subagent-uGPDXPfS.js.map → subagent-DrnKYgvu.js.map} +1 -1
- package/dist/{task-oh8OAnvR.js → task-DyvLyDsO.js} +18 -14
- package/dist/task-DyvLyDsO.js.map +1 -0
- package/dist/{task-stream-jUARpyB5.js → task-stream-CLXzeuPO.js} +16 -9
- package/dist/task-stream-CLXzeuPO.js.map +1 -0
- package/dist/{tasks-2mu3lAvm.js → tasks-D77GNdOU.js} +2 -2
- package/dist/{tasks-2mu3lAvm.js.map → tasks-D77GNdOU.js.map} +1 -1
- package/dist/{telemetry-BllPiBKw.js → telemetry-wp-z9LXH.js} +3 -3
- package/dist/{telemetry-BllPiBKw.js.map → telemetry-wp-z9LXH.js.map} +1 -1
- package/dist/{terminal-aWQrDy8s.js → terminal-D9j4wbpD.js} +13 -13
- package/dist/{terminal-aWQrDy8s.js.map → terminal-D9j4wbpD.js.map} +1 -1
- package/dist/{tools-u8TaJFqa.js → tools-D0r4e-Vu.js} +10 -7
- package/dist/tools-D0r4e-Vu.js.map +1 -0
- package/dist/wizard-abort-Bv87YVSp.js +71 -0
- package/dist/wizard-abort-Bv87YVSp.js.map +1 -0
- package/dist/{wizard-abort-pFFH7dcx.js → wizard-abort-oazJA1Jb.js} +1 -1
- package/dist/{wizard-session-DTyLMPsX.js → wizard-session-C_7r3-rO.js} +3 -2
- package/dist/wizard-session-C_7r3-rO.js.map +1 -0
- package/dist/{wizard-session-Cw7-_OcZ.js → wizard-session-D1KQqUml.js} +1 -1
- package/dist/yara-hooks-Bl-FeANN.js +2 -0
- package/dist/{yara-hooks-BXDBIOBq.js → yara-hooks-DeonKbE_.js} +57 -8
- package/dist/yara-hooks-DeonKbE_.js.map +1 -0
- package/package.json +1 -1
- package/dist/agent-interface-D3MNaDp3.js.map +0 -1
- package/dist/agent-runner-DEeMqJxy.js.map +0 -1
- package/dist/analytics-DN3Kzf7H.js +0 -2
- package/dist/ci-install-DIB2n4Ju.js.map +0 -1
- package/dist/debug-BKqv-yfT.js.map +0 -1
- package/dist/environment-Cl-fIQku.js +0 -22
- package/dist/environment-Cl-fIQku.js.map +0 -1
- package/dist/mcp-prompt-streaming--sRErHKv.js.map +0 -1
- package/dist/non-interactive-CNoYoEZp.js.map +0 -1
- package/dist/package-manager-BQDHm7ER.js.map +0 -1
- package/dist/pi-W-4RUPFY.js.map +0 -1
- package/dist/posthog-integration-LxEBGkoe.js.map +0 -1
- package/dist/security-B4jU_-7q.js.map +0 -1
- package/dist/start-tui-BQH4mQIZ.js.map +0 -1
- package/dist/task-oh8OAnvR.js.map +0 -1
- package/dist/task-stream-jUARpyB5.js.map +0 -1
- package/dist/tools-u8TaJFqa.js.map +0 -1
- package/dist/wizard-abort-D9jiMkZA.js +0 -49
- package/dist/wizard-abort-D9jiMkZA.js.map +0 -1
- package/dist/wizard-session-DTyLMPsX.js.map +0 -1
- package/dist/yara-hooks-BXDBIOBq.js.map +0 -1
- package/dist/yara-hooks-i2jOabhI.js +0 -2
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
//#region src/lib/errors/codes.ts
|
|
2
|
+
const ErrorCodes = {
|
|
3
|
+
CliNodeVersion: "PHW_CLI_NODE_VERSION",
|
|
4
|
+
CliBadArgs: "PHW_CLI_BAD_ARGS",
|
|
5
|
+
CliFlagUnavailable: "PHW_CLI_FLAG_UNAVAILABLE",
|
|
6
|
+
CliInteractiveRequired: "PHW_CLI_INTERACTIVE_REQUIRED",
|
|
7
|
+
ArgsMissingApiKey: "PHW_ARGS_MISSING_API_KEY",
|
|
8
|
+
ArgsMissingInstallDir: "PHW_ARGS_MISSING_INSTALL_DIR",
|
|
9
|
+
ArgsMissingEmail: "PHW_ARGS_MISSING_EMAIL",
|
|
10
|
+
ArgsSignupProvisionFailed: "PHW_ARGS_SIGNUP_PROVISION_FAILED",
|
|
11
|
+
AuthKeyType: "PHW_AUTH_KEY_TYPE",
|
|
12
|
+
AuthMissingScope: "PHW_AUTH_MISSING_SCOPE",
|
|
13
|
+
AuthRegionMismatch: "PHW_AUTH_REGION_MISMATCH",
|
|
14
|
+
AuthInvalidOrExpired: "PHW_AUTH_INVALID_OR_EXPIRED",
|
|
15
|
+
AuthSettingsConflict: "PHW_AUTH_SETTINGS_CONFLICT",
|
|
16
|
+
AuthStoredLoginConflict: "PHW_AUTH_STORED_LOGIN_CONFLICT",
|
|
17
|
+
AuthProjectFetchFailed: "PHW_AUTH_PROJECT_FETCH_FAILED",
|
|
18
|
+
EnvLocalServicesDown: "PHW_ENV_LOCAL_SERVICES_DOWN",
|
|
19
|
+
EnvServiceOutage: "PHW_ENV_SERVICE_OUTAGE",
|
|
20
|
+
DetectBadDirectory: "PHW_DETECT_BAD_DIRECTORY",
|
|
21
|
+
DetectNoFramework: "PHW_DETECT_NO_FRAMEWORK",
|
|
22
|
+
DetectUnsupportedVersion: "PHW_DETECT_UNSUPPORTED_VERSION",
|
|
23
|
+
DetectUnsupportedPlatform: "PHW_DETECT_UNSUPPORTED_PLATFORM",
|
|
24
|
+
DetectNoPosthogSdk: "PHW_DETECT_NO_POSTHOG_SDK",
|
|
25
|
+
DetectNoProjectFiles: "PHW_DETECT_NO_PROJECT_FILES",
|
|
26
|
+
DetectNoSources: "PHW_DETECT_NO_SOURCES",
|
|
27
|
+
DetectNoPackageJson: "PHW_DETECT_NO_PACKAGE_JSON",
|
|
28
|
+
DetectNoSdks: "PHW_DETECT_NO_SDKS",
|
|
29
|
+
DetectMissingStripe: "PHW_DETECT_MISSING_STRIPE",
|
|
30
|
+
DetectUnclassified: "PHW_DETECT_UNCLASSIFIED",
|
|
31
|
+
SkillMenuFetchFailed: "PHW_SKILL_MENU_FETCH_FAILED",
|
|
32
|
+
SkillNotFound: "PHW_SKILL_NOT_FOUND",
|
|
33
|
+
SkillDownloadFailed: "PHW_SKILL_DOWNLOAD_FAILED",
|
|
34
|
+
AgentAbort: "PHW_AGENT_ABORT",
|
|
35
|
+
AgentMcpMissing: "PHW_AGENT_MCP_MISSING",
|
|
36
|
+
AgentResourceMissing: "PHW_AGENT_RESOURCE_MISSING",
|
|
37
|
+
AgentRateLimit: "PHW_AGENT_RATE_LIMIT",
|
|
38
|
+
AgentApiError: "PHW_AGENT_API_ERROR",
|
|
39
|
+
AgentYaraViolation: "PHW_AGENT_YARA_VIOLATION",
|
|
40
|
+
AgentNoProgress: "PHW_AGENT_NO_PROGRESS",
|
|
41
|
+
AgentIncompleteTasks: "PHW_AGENT_INCOMPLETE_TASKS",
|
|
42
|
+
AgentOrchestratorSkillVariantMissing: "PHW_AGENT_ORCHESTRATOR_SKILL_VARIANT_MISSING",
|
|
43
|
+
AgentOrchestratorTasksFailed: "PHW_AGENT_ORCHESTRATOR_TASKS_FAILED",
|
|
44
|
+
AgentOrchestratorSinkInvariant: "PHW_AGENT_ORCHESTRATOR_SINK_INVARIANT",
|
|
45
|
+
SettingsUnfixableConflict: "PHW_SETTINGS_UNFIXABLE_CONFLICT",
|
|
46
|
+
InternalUnhandled: "PHW_INTERNAL_UNHANDLED"
|
|
47
|
+
};
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region src/lib/errors/emit.ts
|
|
50
|
+
const PHW_ERROR_PREFIX = "phw-error:";
|
|
51
|
+
function formatWizardErrorLine(line) {
|
|
52
|
+
return `${PHW_ERROR_PREFIX} ${JSON.stringify(line)}`;
|
|
53
|
+
}
|
|
54
|
+
function emitWizardError(line) {
|
|
55
|
+
process.stderr.write(`${formatWizardErrorLine(line)}\n`);
|
|
56
|
+
}
|
|
57
|
+
ErrorCodes.CliNodeVersion, ErrorCodes.CliBadArgs, ErrorCodes.CliFlagUnavailable, ErrorCodes.CliInteractiveRequired, ErrorCodes.ArgsMissingApiKey, ErrorCodes.ArgsMissingInstallDir, ErrorCodes.ArgsMissingEmail, ErrorCodes.ArgsSignupProvisionFailed, ErrorCodes.AuthKeyType, ErrorCodes.AuthInvalidOrExpired, ErrorCodes.AuthMissingScope, ErrorCodes.AuthRegionMismatch, ErrorCodes.AuthSettingsConflict, ErrorCodes.AuthStoredLoginConflict, ErrorCodes.AuthProjectFetchFailed, ErrorCodes.EnvLocalServicesDown, ErrorCodes.EnvServiceOutage, ErrorCodes.DetectBadDirectory, ErrorCodes.DetectNoFramework, ErrorCodes.DetectUnsupportedVersion, ErrorCodes.DetectUnsupportedPlatform, ErrorCodes.DetectNoPosthogSdk, ErrorCodes.DetectNoProjectFiles, ErrorCodes.DetectNoSources, ErrorCodes.DetectNoPackageJson, ErrorCodes.DetectNoSdks, ErrorCodes.DetectMissingStripe, ErrorCodes.DetectUnclassified, ErrorCodes.SkillMenuFetchFailed, ErrorCodes.SkillNotFound, ErrorCodes.SkillDownloadFailed, ErrorCodes.AgentAbort, ErrorCodes.AgentMcpMissing, ErrorCodes.AgentResourceMissing, ErrorCodes.AgentRateLimit, ErrorCodes.AgentApiError, ErrorCodes.AgentYaraViolation, ErrorCodes.AgentNoProgress, ErrorCodes.AgentIncompleteTasks, ErrorCodes.AgentOrchestratorSkillVariantMissing, ErrorCodes.AgentOrchestratorTasksFailed, ErrorCodes.AgentOrchestratorSinkInvariant, ErrorCodes.SettingsUnfixableConflict, ErrorCodes.InternalUnhandled;
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/lib/errors/auth.ts
|
|
60
|
+
function classifyAuthFailure(input) {
|
|
61
|
+
if (input.usingManagedLogin) return ErrorCodes.AuthStoredLoginConflict;
|
|
62
|
+
if (input.hasSettingsConflict) return ErrorCodes.AuthSettingsConflict;
|
|
63
|
+
if (input.apiKey && !input.apiKey.startsWith("phx_") && !input.apiKey.startsWith("pha_")) return ErrorCodes.AuthKeyType;
|
|
64
|
+
if (input.missingScopes && input.missingScopes.length > 0) return ErrorCodes.AuthMissingScope;
|
|
65
|
+
if (input.gatewayRegion && input.sessionRegion && input.gatewayRegion !== "local" && input.gatewayRegion !== input.sessionRegion) return ErrorCodes.AuthRegionMismatch;
|
|
66
|
+
return ErrorCodes.AuthInvalidOrExpired;
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region src/lib/agent/signals.ts
|
|
70
|
+
/**
|
|
71
|
+
* Agent signal vocabulary — the marker strings the agent emits and the error
|
|
72
|
+
* taxonomy the runner returns. Kept as a dependency-free leaf module so both
|
|
73
|
+
* `agent-interface.ts` and `output-signals.ts` can import it without a cycle.
|
|
74
|
+
*/
|
|
75
|
+
const AgentSignals = {
|
|
76
|
+
STATUS: "[STATUS]",
|
|
77
|
+
ERROR_MCP_MISSING: "[ERROR-MCP-MISSING]",
|
|
78
|
+
ERROR_RESOURCE_MISSING: "[ERROR-RESOURCE-MISSING]",
|
|
79
|
+
SKILL_INSTALL_FAILED: "[SKILL-INSTALL-FAILED]",
|
|
80
|
+
ABORT: "[ABORT]",
|
|
81
|
+
WIZARD_REMARK: "[WIZARD-REMARK]",
|
|
82
|
+
BENCHMARK: "[BENCHMARK]",
|
|
83
|
+
DASHBOARD_URL: "[DASHBOARD_URL]",
|
|
84
|
+
NOTEBOOK_URL: "[NOTEBOOK_URL]"
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* End-of-run reflection ask, shared by both harnesses so remarks are
|
|
88
|
+
* comparable. The format clause comes FIRST and nothing trails the marker —
|
|
89
|
+
* literal models (gpt-5-mini) echo whatever text follows it. The parser also
|
|
90
|
+
* drops remarks that quote this instruction (see AgentOutputSignals.remark).
|
|
91
|
+
*/
|
|
92
|
+
const REMARK_INSTRUCTION = `Reply with a single line that starts with ${AgentSignals.WIZARD_REMARK} and no other lines. In that line, state briefly what information or guidance would have been useful to have in the integration prompt or documentation for this run — specifically anything that would have prevented tool failures, erroneous edits, or other wasted turns.`;
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/lib/errors/agent-map.ts
|
|
95
|
+
const AGENT_ERROR_CODE = {
|
|
96
|
+
["WIZARD_MCP_MISSING"]: ErrorCodes.AgentMcpMissing,
|
|
97
|
+
["WIZARD_RESOURCE_MISSING"]: ErrorCodes.AgentResourceMissing,
|
|
98
|
+
["WIZARD_RATE_LIMIT"]: ErrorCodes.AgentRateLimit,
|
|
99
|
+
["WIZARD_API_ERROR"]: ErrorCodes.AgentApiError,
|
|
100
|
+
["WIZARD_YARA_VIOLATION"]: ErrorCodes.AgentYaraViolation,
|
|
101
|
+
["WIZARD_ABORT"]: ErrorCodes.AgentAbort,
|
|
102
|
+
["WIZARD_NO_PROGRESS"]: ErrorCodes.AgentNoProgress,
|
|
103
|
+
["WIZARD_INCOMPLETE_TASKS"]: ErrorCodes.AgentIncompleteTasks
|
|
104
|
+
};
|
|
105
|
+
//#endregion
|
|
106
|
+
//#region src/lib/errors/detect-map.ts
|
|
107
|
+
const DETECT_CODES = {
|
|
108
|
+
"bad-directory": ErrorCodes.DetectBadDirectory,
|
|
109
|
+
"unsupported-platform": ErrorCodes.DetectUnsupportedPlatform,
|
|
110
|
+
"no-project-files": ErrorCodes.DetectNoProjectFiles,
|
|
111
|
+
"no-sources": ErrorCodes.DetectNoSources,
|
|
112
|
+
"no-package-json": ErrorCodes.DetectNoPackageJson,
|
|
113
|
+
"no-sdks": ErrorCodes.DetectNoSdks,
|
|
114
|
+
"missing-stripe": ErrorCodes.DetectMissingStripe,
|
|
115
|
+
"no-posthog-sdk": ErrorCodes.DetectNoPosthogSdk,
|
|
116
|
+
"no-posthog": ErrorCodes.DetectNoPosthogSdk,
|
|
117
|
+
"missing-posthog": ErrorCodes.DetectNoPosthogSdk
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* `kind` arrives as a bare string — `frameworkContext.detectError` is untyped
|
|
121
|
+
* storage — so the lookup can still miss. It falls back to a detect-group code
|
|
122
|
+
* with `retry: 'no'`, never to `InternalUnhandled`: an unrecognized precondition
|
|
123
|
+
* failure is still a precondition failure, and telling a sandbox to retry one
|
|
124
|
+
* costs it the whole budget.
|
|
125
|
+
*/
|
|
126
|
+
function detectErrorCode(kind) {
|
|
127
|
+
return DETECT_CODES[kind] ?? ErrorCodes.DetectUnclassified;
|
|
128
|
+
}
|
|
129
|
+
//#endregion
|
|
130
|
+
//#region src/lib/errors/skill-map.ts
|
|
131
|
+
const SKILL_CODES = {
|
|
132
|
+
"menu-fetch-failed": ErrorCodes.SkillMenuFetchFailed,
|
|
133
|
+
"skill-not-found": ErrorCodes.SkillNotFound,
|
|
134
|
+
"download-failed": ErrorCodes.SkillDownloadFailed
|
|
135
|
+
};
|
|
136
|
+
function skillErrorCode(result) {
|
|
137
|
+
if (result.kind === "ok") return null;
|
|
138
|
+
return SKILL_CODES[result.kind];
|
|
139
|
+
}
|
|
140
|
+
//#endregion
|
|
141
|
+
//#region src/lib/errors/sanitize.ts
|
|
142
|
+
const DETAIL_ALLOWLIST = [
|
|
143
|
+
"reason",
|
|
144
|
+
"detected",
|
|
145
|
+
"platform"
|
|
146
|
+
];
|
|
147
|
+
function sanitizeErrorDetail(detail) {
|
|
148
|
+
if (!detail) return void 0;
|
|
149
|
+
const safe = {};
|
|
150
|
+
for (const key of DETAIL_ALLOWLIST) if (detail[key] !== void 0) safe[key] = detail[key];
|
|
151
|
+
return Object.keys(safe).length > 0 ? safe : void 0;
|
|
152
|
+
}
|
|
153
|
+
//#endregion
|
|
154
|
+
export { AgentSignals as a, emitWizardError as c, AGENT_ERROR_CODE as i, ErrorCodes as l, skillErrorCode as n, REMARK_INSTRUCTION as o, detectErrorCode as r, classifyAuthFailure as s, sanitizeErrorDetail as t };
|
|
155
|
+
|
|
156
|
+
//# sourceMappingURL=errors-BHervYGs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-BHervYGs.js","names":[],"sources":["../src/lib/errors/codes.ts","../src/lib/errors/emit.ts","../src/lib/errors/catalog.ts","../src/lib/errors/auth.ts","../src/lib/agent/signals.ts","../src/lib/errors/agent-map.ts","../src/lib/errors/detect-map.ts","../src/lib/errors/skill-map.ts","../src/lib/errors/sanitize.ts"],"sourcesContent":["export const ErrorCodes = {\n CliNodeVersion: 'PHW_CLI_NODE_VERSION',\n CliBadArgs: 'PHW_CLI_BAD_ARGS',\n CliFlagUnavailable: 'PHW_CLI_FLAG_UNAVAILABLE',\n CliInteractiveRequired: 'PHW_CLI_INTERACTIVE_REQUIRED',\n ArgsMissingApiKey: 'PHW_ARGS_MISSING_API_KEY',\n ArgsMissingInstallDir: 'PHW_ARGS_MISSING_INSTALL_DIR',\n ArgsMissingEmail: 'PHW_ARGS_MISSING_EMAIL',\n ArgsSignupProvisionFailed: 'PHW_ARGS_SIGNUP_PROVISION_FAILED',\n AuthKeyType: 'PHW_AUTH_KEY_TYPE',\n AuthMissingScope: 'PHW_AUTH_MISSING_SCOPE',\n AuthRegionMismatch: 'PHW_AUTH_REGION_MISMATCH',\n AuthInvalidOrExpired: 'PHW_AUTH_INVALID_OR_EXPIRED',\n AuthSettingsConflict: 'PHW_AUTH_SETTINGS_CONFLICT',\n AuthStoredLoginConflict: 'PHW_AUTH_STORED_LOGIN_CONFLICT',\n AuthProjectFetchFailed: 'PHW_AUTH_PROJECT_FETCH_FAILED',\n EnvLocalServicesDown: 'PHW_ENV_LOCAL_SERVICES_DOWN',\n EnvServiceOutage: 'PHW_ENV_SERVICE_OUTAGE',\n DetectBadDirectory: 'PHW_DETECT_BAD_DIRECTORY',\n DetectNoFramework: 'PHW_DETECT_NO_FRAMEWORK',\n DetectUnsupportedVersion: 'PHW_DETECT_UNSUPPORTED_VERSION',\n DetectUnsupportedPlatform: 'PHW_DETECT_UNSUPPORTED_PLATFORM',\n DetectNoPosthogSdk: 'PHW_DETECT_NO_POSTHOG_SDK',\n DetectNoProjectFiles: 'PHW_DETECT_NO_PROJECT_FILES',\n DetectNoSources: 'PHW_DETECT_NO_SOURCES',\n DetectNoPackageJson: 'PHW_DETECT_NO_PACKAGE_JSON',\n DetectNoSdks: 'PHW_DETECT_NO_SDKS',\n DetectMissingStripe: 'PHW_DETECT_MISSING_STRIPE',\n DetectUnclassified: 'PHW_DETECT_UNCLASSIFIED',\n SkillMenuFetchFailed: 'PHW_SKILL_MENU_FETCH_FAILED',\n SkillNotFound: 'PHW_SKILL_NOT_FOUND',\n SkillDownloadFailed: 'PHW_SKILL_DOWNLOAD_FAILED',\n AgentAbort: 'PHW_AGENT_ABORT',\n AgentMcpMissing: 'PHW_AGENT_MCP_MISSING',\n AgentResourceMissing: 'PHW_AGENT_RESOURCE_MISSING',\n AgentRateLimit: 'PHW_AGENT_RATE_LIMIT',\n AgentApiError: 'PHW_AGENT_API_ERROR',\n AgentYaraViolation: 'PHW_AGENT_YARA_VIOLATION',\n AgentNoProgress: 'PHW_AGENT_NO_PROGRESS',\n AgentIncompleteTasks: 'PHW_AGENT_INCOMPLETE_TASKS',\n AgentOrchestratorSkillVariantMissing:\n 'PHW_AGENT_ORCHESTRATOR_SKILL_VARIANT_MISSING',\n AgentOrchestratorTasksFailed: 'PHW_AGENT_ORCHESTRATOR_TASKS_FAILED',\n AgentOrchestratorSinkInvariant: 'PHW_AGENT_ORCHESTRATOR_SINK_INVARIANT',\n SettingsUnfixableConflict: 'PHW_SETTINGS_UNFIXABLE_CONFLICT',\n InternalUnhandled: 'PHW_INTERNAL_UNHANDLED',\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\nexport const ERROR_CODE_PATTERN = /^PHW_[A-Z][A-Z0-9_]*$/;\n\nexport function isErrorCode(value: string): value is ErrorCode {\n return (Object.values(ErrorCodes) as string[]).includes(value);\n}\n","import type { ErrorCode } from './codes';\n\nexport const PHW_ERROR_PREFIX = 'phw-error:';\n\nexport interface WizardErrorLine {\n code: ErrorCode;\n message: string;\n detail?: Record<string, unknown>;\n}\n\nexport function formatWizardErrorLine(line: WizardErrorLine): string {\n return `${PHW_ERROR_PREFIX} ${JSON.stringify(line)}`;\n}\n\nexport function emitWizardError(line: WizardErrorLine): void {\n process.stderr.write(`${formatWizardErrorLine(line)}\\n`);\n}\n","import { ErrorCodes, type ErrorCode } from './codes';\nimport type { ErrorCatalogEntry } from './types';\n\nexport const ERROR_CATALOG: Record<ErrorCode, ErrorCatalogEntry> = {\n [ErrorCodes.CliNodeVersion]: {\n group: 'cli',\n retry: 'no',\n description: 'Node.js runtime is older than the required range.',\n },\n [ErrorCodes.CliBadArgs]: {\n group: 'cli',\n retry: 'no',\n description: 'Unrecognized command or option.',\n },\n [ErrorCodes.CliFlagUnavailable]: {\n group: 'cli',\n retry: 'no',\n description: 'A dev-only flag or env var was passed to a published build.',\n },\n [ErrorCodes.CliInteractiveRequired]: {\n group: 'cli',\n retry: 'no',\n description:\n 'The command requires an interactive terminal and has no non-interactive fallback.',\n },\n [ErrorCodes.ArgsMissingApiKey]: {\n group: 'args',\n retry: 'no',\n description: 'Non-interactive run without --api-key.',\n },\n [ErrorCodes.ArgsMissingInstallDir]: {\n group: 'args',\n retry: 'no',\n description: 'Non-interactive run without --install-dir.',\n },\n [ErrorCodes.ArgsMissingEmail]: {\n group: 'args',\n retry: 'no',\n description: 'Signup run without --email.',\n },\n [ErrorCodes.ArgsSignupProvisionFailed]: {\n group: 'args',\n retry: 'yes',\n description: 'Account provisioning for --signup failed.',\n },\n [ErrorCodes.AuthKeyType]: {\n group: 'auth',\n retry: 'no',\n description: 'The API key has the wrong type or prefix for this mode.',\n },\n [ErrorCodes.AuthInvalidOrExpired]: {\n group: 'auth',\n retry: 'no',\n description: 'The credential was rejected by the LLM gateway or API.',\n },\n [ErrorCodes.AuthMissingScope]: {\n group: 'auth',\n retry: 'no',\n description: 'The personal API key lacks a scope the run requires.',\n },\n [ErrorCodes.AuthRegionMismatch]: {\n group: 'auth',\n retry: 'no',\n description: 'The resolved region does not match the credential.',\n },\n [ErrorCodes.AuthSettingsConflict]: {\n group: 'auth',\n retry: 'no',\n description: 'A Claude settings file overrides the gateway credential.',\n },\n [ErrorCodes.AuthStoredLoginConflict]: {\n group: 'auth',\n retry: 'no',\n description:\n 'The agent SDK used a stored Claude login instead of the gateway token.',\n },\n [ErrorCodes.AuthProjectFetchFailed]: {\n group: 'auth',\n retry: 'yes',\n description: 'Fetching user or project data from the PostHog API failed.',\n },\n [ErrorCodes.EnvLocalServicesDown]: {\n group: 'env',\n retry: 'yes',\n description: 'A local dev target service is not running.',\n },\n [ErrorCodes.EnvServiceOutage]: {\n group: 'env',\n retry: 'yes',\n description: 'Blocking external services are down.',\n },\n [ErrorCodes.DetectBadDirectory]: {\n group: 'detect',\n retry: 'no',\n description:\n 'The install directory is missing, not a directory, or unreadable.',\n },\n [ErrorCodes.DetectNoFramework]: {\n group: 'detect',\n retry: 'no',\n description: 'Framework auto-detection found no supported framework.',\n },\n [ErrorCodes.DetectUnsupportedVersion]: {\n group: 'detect',\n retry: 'no',\n description:\n 'The detected framework version is below the supported minimum.',\n },\n [ErrorCodes.DetectUnsupportedPlatform]: {\n group: 'detect',\n retry: 'no',\n description: 'The project platform has no matching skill variant.',\n },\n [ErrorCodes.DetectNoPosthogSdk]: {\n group: 'detect',\n retry: 'no',\n description:\n 'The program requires an installed PostHog SDK and none was found.',\n },\n [ErrorCodes.DetectNoProjectFiles]: {\n group: 'detect',\n retry: 'no',\n description: 'The project has no files for the program to work on.',\n },\n [ErrorCodes.DetectNoSources]: {\n group: 'detect',\n retry: 'no',\n description: 'No data warehouse sources were found.',\n },\n [ErrorCodes.DetectNoPackageJson]: {\n group: 'detect',\n retry: 'no',\n description: 'The project has no package.json for the program to scan.',\n },\n [ErrorCodes.DetectNoSdks]: {\n group: 'detect',\n retry: 'no',\n description: 'None of the SDKs the program needs are installed.',\n },\n [ErrorCodes.DetectMissingStripe]: {\n group: 'detect',\n retry: 'no',\n description: 'Revenue analytics requires a Stripe SDK and none was found.',\n },\n [ErrorCodes.DetectUnclassified]: {\n group: 'detect',\n // A detect step reported a precondition failure we have no code for yet.\n // Every known cause is a property of the user's project, so retrying can\n // only burn budget — fail closed rather than inheriting `internal`'s 'yes'.\n retry: 'no',\n description: 'A detect step failed with a kind absent from the catalog.',\n },\n [ErrorCodes.SkillMenuFetchFailed]: {\n group: 'skill',\n retry: 'yes',\n description: 'The context-mill skill menu could not be fetched.',\n },\n [ErrorCodes.SkillNotFound]: {\n group: 'skill',\n retry: 'no',\n description: 'The skill id is absent from the context-mill menu.',\n },\n [ErrorCodes.SkillDownloadFailed]: {\n group: 'skill',\n retry: 'yes',\n description: 'The skill download or extraction failed.',\n },\n [ErrorCodes.AgentAbort]: {\n group: 'agent',\n retry: 'case-by-case',\n description: 'The agent emitted an [ABORT] signal with a reason.',\n },\n [ErrorCodes.AgentMcpMissing]: {\n group: 'agent',\n retry: 'yes',\n description: 'The agent could not reach the PostHog MCP server.',\n },\n [ErrorCodes.AgentResourceMissing]: {\n group: 'agent',\n retry: 'yes',\n description: 'The agent could not access a setup resource.',\n },\n [ErrorCodes.AgentRateLimit]: {\n group: 'agent',\n retry: 'yes',\n description: 'The LLM gateway rate-limited the run.',\n },\n [ErrorCodes.AgentApiError]: {\n group: 'agent',\n retry: 'yes',\n description: 'The agent hit an API error other than a rate limit.',\n },\n [ErrorCodes.AgentYaraViolation]: {\n group: 'agent',\n retry: 'no',\n description: 'The security scanner terminated the run.',\n },\n [ErrorCodes.AgentNoProgress]: {\n group: 'agent',\n retry: 'case-by-case',\n description: 'The agent ended without a single tool call.',\n },\n [ErrorCodes.AgentIncompleteTasks]: {\n group: 'agent',\n retry: 'case-by-case',\n description: 'The agent stopped with planned tasks still open.',\n },\n [ErrorCodes.AgentOrchestratorSkillVariantMissing]: {\n group: 'agent',\n retry: 'yes',\n description: 'The orchestrator could not download a needed skill variant.',\n },\n [ErrorCodes.AgentOrchestratorTasksFailed]: {\n group: 'agent',\n retry: 'case-by-case',\n description: 'The orchestrator queue drained with failed or blocked tasks.',\n },\n [ErrorCodes.AgentOrchestratorSinkInvariant]: {\n group: 'agent',\n retry: 'no',\n description: 'The orchestrator plan failed the sink coverage invariant.',\n },\n [ErrorCodes.SettingsUnfixableConflict]: {\n group: 'settings',\n retry: 'no',\n description:\n 'A Claude settings conflict cannot be neutralized automatically.',\n },\n [ErrorCodes.InternalUnhandled]: {\n group: 'internal',\n retry: 'yes',\n description: 'An unexpected error escaped the pipeline.',\n },\n};\n","import { ErrorCodes, type ErrorCode } from './codes';\n\nexport interface AuthFailureInput {\n hasSettingsConflict?: boolean;\n usingManagedLogin?: boolean;\n apiKey?: string;\n missingScopes?: readonly string[];\n gatewayRegion?: 'us' | 'eu' | 'local';\n sessionRegion?: 'us' | 'eu';\n}\n\nexport function classifyAuthFailure(input: AuthFailureInput): ErrorCode {\n if (input.usingManagedLogin) return ErrorCodes.AuthStoredLoginConflict;\n if (input.hasSettingsConflict) return ErrorCodes.AuthSettingsConflict;\n if (\n input.apiKey &&\n !input.apiKey.startsWith('phx_') &&\n !input.apiKey.startsWith('pha_')\n ) {\n return ErrorCodes.AuthKeyType;\n }\n if (input.missingScopes && input.missingScopes.length > 0) {\n return ErrorCodes.AuthMissingScope;\n }\n if (\n input.gatewayRegion &&\n input.sessionRegion &&\n input.gatewayRegion !== 'local' &&\n input.gatewayRegion !== input.sessionRegion\n ) {\n return ErrorCodes.AuthRegionMismatch;\n }\n return ErrorCodes.AuthInvalidOrExpired;\n}\n","/**\n * Agent signal vocabulary — the marker strings the agent emits and the error\n * taxonomy the runner returns. Kept as a dependency-free leaf module so both\n * `agent-interface.ts` and `output-signals.ts` can import it without a cycle.\n */\n\nexport const AgentSignals = {\n /** Signal emitted when the agent reports progress to the user */\n STATUS: '[STATUS]',\n /** Signal emitted when the agent cannot access the PostHog MCP server */\n ERROR_MCP_MISSING: '[ERROR-MCP-MISSING]',\n /** Signal emitted when the agent cannot access the setup resource */\n ERROR_RESOURCE_MISSING: '[ERROR-RESOURCE-MISSING]',\n /**\n * Signal emitted when `install_skill` failed and the agent is continuing\n * the integration WITHOUT the skill (best-effort from its own knowledge).\n * Format: \"[SKILL-INSTALL-FAILED] <skill id — reason>\". Non-fatal by\n * design: a freestyled integration beats an outright failure, but the run\n * must be measurable — the runner captures it as an analytics event.\n */\n SKILL_INSTALL_FAILED: '[SKILL-INSTALL-FAILED]',\n /**\n * Signal emitted when the agent cannot complete the program and is\n * aborting intentionally (distinct from errors). Format: \"[ABORT] <reason>\".\n * Programs can declare an onAbort handler to render a custom screen.\n */\n ABORT: '[ABORT]',\n /** Signal emitted when the agent provides a remark about its run */\n WIZARD_REMARK: '[WIZARD-REMARK]',\n /** Signal prefix for benchmark logging */\n BENCHMARK: '[BENCHMARK]',\n /**\n * Signal emitted when the agent has created a PostHog dashboard for the\n * user. Format: `[DASHBOARD_URL] <full https url>`. The URL is captured\n * onto `session.dashboardUrl` and surfaced by programs in their outro.\n */\n DASHBOARD_URL: '[DASHBOARD_URL]',\n /**\n * Signal emitted when the agent has uploaded a report to a PostHog\n * notebook. Format: `[NOTEBOOK_URL] <full https url>`. The URL is captured\n * onto `session.notebookUrl` and surfaced by programs in their outro.\n */\n NOTEBOOK_URL: '[NOTEBOOK_URL]',\n} as const;\n\nexport type AgentSignal = (typeof AgentSignals)[keyof typeof AgentSignals];\n\n/**\n * End-of-run reflection ask, shared by both harnesses so remarks are\n * comparable. The format clause comes FIRST and nothing trails the marker —\n * literal models (gpt-5-mini) echo whatever text follows it. The parser also\n * drops remarks that quote this instruction (see AgentOutputSignals.remark).\n */\nexport const REMARK_INSTRUCTION = `Reply with a single line that starts with ${AgentSignals.WIZARD_REMARK} and no other lines. In that line, state briefly what information or guidance would have been useful to have in the integration prompt or documentation for this run — specifically anything that would have prevented tool failures, erroneous edits, or other wasted turns.`;\n\n/**\n * Error types that can be returned from agent execution.\n * These correspond to the error signals that the agent emits.\n */\nexport enum AgentErrorType {\n /** Agent could not access the PostHog MCP server */\n MCP_MISSING = 'WIZARD_MCP_MISSING',\n /** Agent could not access the setup resource */\n RESOURCE_MISSING = 'WIZARD_RESOURCE_MISSING',\n /** API rate limit exceeded */\n RATE_LIMIT = 'WIZARD_RATE_LIMIT',\n /** Generic API error */\n API_ERROR = 'WIZARD_API_ERROR',\n /** YARA scanner detected a security violation */\n YARA_VIOLATION = 'WIZARD_YARA_VIOLATION',\n /** Agent intentionally aborted the program (emitted [ABORT] <reason>) */\n ABORT = 'WIZARD_ABORT',\n /** Agent ended without making a single tool call — a no-op run that did no work */\n NO_PROGRESS = 'WIZARD_NO_PROGRESS',\n /** Agent acted but stopped short — planned tasks left open and/or no skill installed */\n INCOMPLETE_TASKS = 'WIZARD_INCOMPLETE_TASKS',\n}\n","import { AgentErrorType } from '../agent/signals';\nimport { ErrorCodes, type ErrorCode } from './codes';\n\nexport const AGENT_ERROR_CODE: Record<AgentErrorType, ErrorCode> = {\n [AgentErrorType.MCP_MISSING]: ErrorCodes.AgentMcpMissing,\n [AgentErrorType.RESOURCE_MISSING]: ErrorCodes.AgentResourceMissing,\n [AgentErrorType.RATE_LIMIT]: ErrorCodes.AgentRateLimit,\n [AgentErrorType.API_ERROR]: ErrorCodes.AgentApiError,\n [AgentErrorType.YARA_VIOLATION]: ErrorCodes.AgentYaraViolation,\n [AgentErrorType.ABORT]: ErrorCodes.AgentAbort,\n [AgentErrorType.NO_PROGRESS]: ErrorCodes.AgentNoProgress,\n [AgentErrorType.INCOMPLETE_TASKS]: ErrorCodes.AgentIncompleteTasks,\n};\n","import { ErrorCodes, type ErrorCode } from './codes';\nimport type { RevenueDetectError } from '@lib/programs/revenue-analytics/detect';\nimport type { SelfDrivingDetectError } from '@lib/programs/self-driving/detect';\nimport type { SourceMapsDetectError } from '@lib/programs/error-tracking-upload-source-maps/detect';\nimport type { WarehouseDetectError } from '@lib/programs/warehouse-source/detect';\nimport type { WebAnalyticsDetectError } from '@lib/programs/web-analytics-doctor/detect';\n\n/**\n * Every `kind` a program detect step can write into\n * `frameworkContext.detectError`, assembled from the programs' own unions.\n * Type-only imports, so this adds no runtime edge from the catalog to the\n * programs (same shape as `skill-map.ts` keying on `InstallSkillResult`).\n *\n * The point is the compile error: add a kind to any program's `DetectError`\n * and `DETECT_CODES` stops type-checking until it gets a code.\n */\nexport type DetectErrorKind =\n | RevenueDetectError['kind']\n | SelfDrivingDetectError['kind']\n | SourceMapsDetectError['kind']\n | WarehouseDetectError['kind']\n | WebAnalyticsDetectError['kind'];\n\nconst DETECT_CODES: Record<DetectErrorKind, ErrorCode> = {\n 'bad-directory': ErrorCodes.DetectBadDirectory,\n 'unsupported-platform': ErrorCodes.DetectUnsupportedPlatform,\n 'no-project-files': ErrorCodes.DetectNoProjectFiles,\n 'no-sources': ErrorCodes.DetectNoSources,\n 'no-package-json': ErrorCodes.DetectNoPackageJson,\n 'no-sdks': ErrorCodes.DetectNoSdks,\n 'missing-stripe': ErrorCodes.DetectMissingStripe,\n // Three kinds, one failure class: the program needs a PostHog SDK and the\n // project has none. Hosts that care which program asked read `detail.kind`.\n 'no-posthog-sdk': ErrorCodes.DetectNoPosthogSdk,\n 'no-posthog': ErrorCodes.DetectNoPosthogSdk,\n 'missing-posthog': ErrorCodes.DetectNoPosthogSdk,\n};\n\n/**\n * `kind` arrives as a bare string — `frameworkContext.detectError` is untyped\n * storage — so the lookup can still miss. It falls back to a detect-group code\n * with `retry: 'no'`, never to `InternalUnhandled`: an unrecognized precondition\n * failure is still a precondition failure, and telling a sandbox to retry one\n * costs it the whole budget.\n */\nexport function detectErrorCode(kind: string): ErrorCode {\n return DETECT_CODES[kind as DetectErrorKind] ?? ErrorCodes.DetectUnclassified;\n}\n","import { ErrorCodes, type ErrorCode } from './codes';\nimport type { InstallSkillResult } from '@lib/wizard-tools';\n\nconst SKILL_CODES: Record<\n Exclude<InstallSkillResult['kind'], 'ok'>,\n ErrorCode\n> = {\n 'menu-fetch-failed': ErrorCodes.SkillMenuFetchFailed,\n 'skill-not-found': ErrorCodes.SkillNotFound,\n 'download-failed': ErrorCodes.SkillDownloadFailed,\n};\n\nexport function skillErrorCode(result: InstallSkillResult): ErrorCode | null {\n if (result.kind === 'ok') return null;\n return SKILL_CODES[result.kind];\n}\n","const DETAIL_ALLOWLIST = ['reason', 'detected', 'platform'] as const;\n\nexport function sanitizeErrorDetail(\n detail: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!detail) return undefined;\n const safe: Record<string, unknown> = {};\n for (const key of DETAIL_ALLOWLIST) {\n if (detail[key] !== undefined) safe[key] = detail[key];\n }\n return Object.keys(safe).length > 0 ? safe : undefined;\n}\n"],"mappings":";AAAA,MAAa,aAAa;CACxB,gBAAgB;CAChB,YAAY;CACZ,oBAAoB;CACpB,wBAAwB;CACxB,mBAAmB;CACnB,uBAAuB;CACvB,kBAAkB;CAClB,2BAA2B;CAC3B,aAAa;CACb,kBAAkB;CAClB,oBAAoB;CACpB,sBAAsB;CACtB,sBAAsB;CACtB,yBAAyB;CACzB,wBAAwB;CACxB,sBAAsB;CACtB,kBAAkB;CAClB,oBAAoB;CACpB,mBAAmB;CACnB,0BAA0B;CAC1B,2BAA2B;CAC3B,oBAAoB;CACpB,sBAAsB;CACtB,iBAAiB;CACjB,qBAAqB;CACrB,cAAc;CACd,qBAAqB;CACrB,oBAAoB;CACpB,sBAAsB;CACtB,eAAe;CACf,qBAAqB;CACrB,YAAY;CACZ,iBAAiB;CACjB,sBAAsB;CACtB,gBAAgB;CAChB,eAAe;CACf,oBAAoB;CACpB,iBAAiB;CACjB,sBAAsB;CACtB,sCACE;CACF,8BAA8B;CAC9B,gCAAgC;CAChC,2BAA2B;CAC3B,mBAAmB;CACpB;;;AC5CD,MAAa,mBAAmB;AAQhC,SAAgB,sBAAsB,MAA+B;AACnE,QAAO,GAAG,iBAAiB,GAAG,KAAK,UAAU,KAAK;;AAGpD,SAAgB,gBAAgB,MAA6B;AAC3D,SAAQ,OAAO,MAAM,GAAG,sBAAsB,KAAK,CAAC,IAAI;;ACXvD,WAAW,gBAKX,WAAW,YAKX,WAAW,oBAKX,WAAW,wBAMX,WAAW,mBAKX,WAAW,uBAKX,WAAW,kBAKX,WAAW,2BAKX,WAAW,aAKX,WAAW,sBAKX,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W;CACnC,oBAAoB,WAAW;CAC/B,cAAc,WAAW;CACzB,mBAAmB,WAAW;CAC9B,WAAW,WAAW;CACtB,kBAAkB,WAAW;CAG7B,kBAAkB,WAAW;CAC7B,cAAc,WAAW;CACzB,mBAAmB,WAAW;CAC/B;;;;;;;;AASD,SAAgB,gBAAgB,MAAyB;AACvD,QAAO,aAAa,SAA4B,WAAW;;;;AC3C7D,MAAM,cAGF;CACF,qBAAqB,WAAW;CAChC,mBAAmB,WAAW;CAC9B,mBAAmB,WAAW;CAC/B;AAED,SAAgB,eAAe,QAA8C;AAC3E,KAAI,OAAO,SAAS,KAAM,QAAO;AACjC,QAAO,YAAY,OAAO;;;;ACd5B,MAAM,mBAAmB;CAAC;CAAU;CAAY;CAAW;AAE3D,SAAgB,oBACd,QACqC;AACrC,KAAI,CAAC,OAAQ,QAAO,KAAA;CACpB,MAAM,OAAgC,EAAE;AACxC,MAAK,MAAM,OAAO,iBAChB,KAAI,OAAO,SAAS,KAAA,EAAW,MAAK,OAAO,OAAO;AAEpD,QAAO,OAAO,KAAK,KAAK,CAAC,SAAS,IAAI,OAAO,KAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { s as logToFile } from "./debug-
|
|
1
|
+
import { s as logToFile } from "./debug-aA5dm2MR.js";
|
|
2
2
|
import * as fs$1 from "fs";
|
|
3
3
|
import { basename, dirname } from "node:path";
|
|
4
4
|
//#region src/lib/file-watcher.ts
|
|
@@ -120,4 +120,4 @@ function startFileWatcher(path, onUpdate, options = {}) {
|
|
|
120
120
|
//#endregion
|
|
121
121
|
export { startFileWatcher as t };
|
|
122
122
|
|
|
123
|
-
//# sourceMappingURL=file-watcher-
|
|
123
|
+
//# sourceMappingURL=file-watcher-Cn7tD95m.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-watcher-
|
|
1
|
+
{"version":3,"file":"file-watcher-Cn7tD95m.js","names":["fs"],"sources":["../src/lib/file-watcher.ts"],"sourcesContent":["/**\n * JSON file watcher shared by runner and UI machinery.\n *\n * `fs.watch` alone is unreliable for atomic-rename writes, so the watcher\n * pairs it with a continuous mtime-polled re-read. The poll catches missed\n * events; the watch keeps latency low when it does fire.\n */\n\nimport * as fs from 'fs';\nimport { basename, dirname } from 'node:path';\nimport { logToFile } from '@utils/debug';\n\nconst DEFAULT_POLL_INTERVAL_MS = 5000;\nconst DEFAULT_ATTACH_RETRY_INTERVAL_MS = 1000;\nconst DEFAULT_WATCH_DEBOUNCE_MS = 25;\n\nexport interface FileWatcherHandle {\n refresh(): void;\n stop(): void;\n}\n\nexport interface FileWatcherOptions {\n /** ms between mtime checks once the file exists. */\n pollIntervalMs?: number;\n /** ms between attach attempts while waiting for the file to appear. */\n attachRetryIntervalMs?: number;\n /** ms to coalesce duplicate filesystem events. */\n watchDebounceMs?: number;\n /** Ignore the file that exists when the watcher starts until it changes. */\n ignoreInitialFile?: boolean;\n /** Refuse to read files larger than this many bytes. */\n maxFileSizeBytes?: number;\n}\n\n/** Watch `path` for JSON updates and call `onUpdate(parsed)` whenever the\n * file's mtime changes and the contents are valid JSON. Caller must invoke\n * `handle.stop()` to release the watcher. */\nexport function startFileWatcher(\n path: string,\n onUpdate: (parsed: unknown) => void,\n options: FileWatcherOptions = {},\n): FileWatcherHandle {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const attachRetryIntervalMs =\n options.attachRetryIntervalMs ?? DEFAULT_ATTACH_RETRY_INTERVAL_MS;\n const watchDebounceMs = options.watchDebounceMs ?? DEFAULT_WATCH_DEBOUNCE_MS;\n\n const watchers: fs.FSWatcher[] = [];\n const intervals: Array<ReturnType<typeof setInterval>> = [];\n const targetDir = dirname(path);\n const targetName = basename(path);\n let lastMtimeMs = 0;\n let ignoredInitialSignature: string | null = null;\n let watchDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n let lastReadErrorSignature: string | null = null;\n let stopped = false;\n\n const signature = (stat: fs.Stats): string =>\n `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;\n\n if (options.ignoreInitialFile) {\n try {\n const stat = fs.lstatSync(path);\n if (stat.isFile() && !stat.isSymbolicLink()) {\n ignoredInitialSignature = signature(stat);\n }\n } catch {\n // No initial file to ignore.\n }\n }\n\n const logReadError = (errorSignature: string, message: string) => {\n if (lastReadErrorSignature === errorSignature) return;\n lastReadErrorSignature = errorSignature;\n logToFile(`[file-watcher] ${message}: ${path}`);\n };\n\n const read = (force = false) => {\n let stat: fs.Stats;\n try {\n stat = fs.lstatSync(path);\n } catch {\n return;\n }\n\n if (!stat.isFile() || stat.isSymbolicLink()) return;\n const fileSignature = signature(stat);\n\n try {\n if (ignoredInitialSignature) {\n if (fileSignature === ignoredInitialSignature) return;\n ignoredInitialSignature = null;\n }\n if (\n options.maxFileSizeBytes !== undefined &&\n stat.size > options.maxFileSizeBytes\n ) {\n logReadError(\n `oversized:${fileSignature}`,\n `refusing oversized JSON file (${stat.size} bytes, limit ${options.maxFileSizeBytes} bytes)`,\n );\n return;\n }\n if (!force && stat.mtimeMs === lastMtimeMs) return;\n lastMtimeMs = stat.mtimeMs;\n const parsed: unknown = JSON.parse(fs.readFileSync(path, 'utf-8'));\n lastReadErrorSignature = null;\n onUpdate(parsed);\n } catch (error) {\n logReadError(\n `invalid:${fileSignature}:${String(error)}`,\n `could not read valid JSON (${String(error)})`,\n );\n }\n };\n\n const scheduleRead = () => {\n if (stopped) return;\n if (watchDebounceTimer) clearTimeout(watchDebounceTimer);\n watchDebounceTimer = setTimeout(() => {\n watchDebounceTimer = null;\n read(true);\n }, watchDebounceMs);\n };\n\n const attachWatch = () => {\n watchers.push(\n fs.watch(targetDir, (_eventType, filename) => {\n if (filename == null || filename.toString() === targetName) {\n scheduleRead();\n }\n }),\n );\n };\n\n intervals.push(setInterval(() => read(), pollIntervalMs));\n\n try {\n attachWatch();\n // Defer the initial callback until the caller has received the handle, so\n // callbacks that stop their watcher cannot race handle assignment.\n queueMicrotask(() => {\n if (!stopped) read(true);\n });\n } catch {\n // Parent directory does not exist yet. Polling still covers a later file;\n // retry attaching the low-latency directory watcher until it appears.\n const attachInterval = setInterval(() => {\n try {\n fs.accessSync(targetDir);\n clearInterval(attachInterval);\n const idx = intervals.indexOf(attachInterval);\n if (idx >= 0) intervals.splice(idx, 1);\n attachWatch();\n read(true);\n } catch {\n // Still waiting.\n }\n }, attachRetryIntervalMs);\n intervals.push(attachInterval);\n }\n\n return {\n refresh() {\n if (stopped) return;\n if (watchDebounceTimer) {\n clearTimeout(watchDebounceTimer);\n watchDebounceTimer = null;\n }\n read(true);\n },\n stop() {\n stopped = true;\n if (watchDebounceTimer) {\n clearTimeout(watchDebounceTimer);\n watchDebounceTimer = null;\n }\n for (const watcher of watchers) watcher.close();\n for (const interval of intervals) clearInterval(interval);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,2BAA2B;AACjC,MAAM,mCAAmC;AACzC,MAAM,4BAA4B;;;;AAuBlC,SAAgB,iBACd,MACA,UACA,UAA8B,EAAE,EACb;CACnB,MAAM,iBAAiB,QAAQ,kBAAkB;CACjD,MAAM,wBACJ,QAAQ,yBAAyB;CACnC,MAAM,kBAAkB,QAAQ,mBAAmB;CAEnD,MAAM,WAA2B,EAAE;CACnC,MAAM,YAAmD,EAAE;CAC3D,MAAM,YAAY,QAAQ,KAAK;CAC/B,MAAM,aAAa,SAAS,KAAK;CACjC,IAAI,cAAc;CAClB,IAAI,0BAAyC;CAC7C,IAAI,qBAA2D;CAC/D,IAAI,yBAAwC;CAC5C,IAAI,UAAU;CAEd,MAAM,aAAa,SACjB,GAAG,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,KAAK,KAAK,GAAG,KAAK,QAAQ,GAAG,KAAK;AAE/D,KAAI,QAAQ,kBACV,KAAI;EACF,MAAM,OAAOA,KAAG,UAAU,KAAK;AAC/B,MAAI,KAAK,QAAQ,IAAI,CAAC,KAAK,gBAAgB,CACzC,2BAA0B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N,MAAM,iBAAiB,kBAAkB;AACvC,OAAI;AACF,SAAG,WAAW,UAAU;AACxB,kBAAc,eAAe;IAC7B,MAAM,MAAM,UAAU,QAAQ,eAAe;AAC7C,QAAI,OAAO,EAAG,WAAU,OAAO,KAAK,EAAE;AACtC,iBAAa;AACb,SAAK,KAAK;WACJ;KAGP,sBAAsB;AACzB,YAAU,KAAK,eAAe;;AAGhC,QAAO;EACL,UAAU;AACR,OAAI,QAAS;AACb,OAAI,oBAAoB;AACtB,iBAAa,mBAAmB;AAChC,yBAAqB;;AAEvB,QAAK,KAAK;;EAEZ,OAAO;AACL,aAAU;AACV,OAAI,oBAAoB;AACtB,iBAAa,mBAAmB;AAChC,yBAAqB;;AAEvB,QAAK,MAAM,WAAW,SAAU,SAAQ,OAAO;AAC/C,QAAK,MAAM,YAAY,UAAW,eAAc,SAAS;;EAE5D"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { m as LoggingUI } from "./debug-
|
|
1
|
+
import { m as LoggingUI } from "./debug-aA5dm2MR.js";
|
|
2
2
|
//#region src/ui/headless-ui.ts
|
|
3
3
|
/**
|
|
4
4
|
* `LoggingUI` plus it feeds run state into a `WizardStore` so the background
|
|
@@ -25,4 +25,4 @@ var HeadlessUI = class extends LoggingUI {
|
|
|
25
25
|
//#endregion
|
|
26
26
|
export { HeadlessUI };
|
|
27
27
|
|
|
28
|
-
//# sourceMappingURL=headless-ui-
|
|
28
|
+
//# sourceMappingURL=headless-ui-DtIYZNVv.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headless-ui-
|
|
1
|
+
{"version":3,"file":"headless-ui-DtIYZNVv.js","names":[],"sources":["../src/ui/headless-ui.ts"],"sourcesContent":["import { LoggingUI } from './logging-ui';\nimport type { WizardStore } from './tui/store';\n\n/**\n * `LoggingUI` plus it feeds run state into a `WizardStore` so the background\n * wizard-session sync (`TaskStreamPush`) can observe a headless run. We extend\n * `LoggingUI` (not `InkUI`) because its blocking/gate methods would wait on a\n * TUI that never renders; the runner drives phase transitions on the store\n * directly, so only UI-originated per-run updates tee through here. Runner\n * machinery loads agent-authored artifacts such as the event plan directly\n * into the store.\n */\nexport class HeadlessUI extends LoggingUI {\n constructor(private readonly store: WizardStore) {\n super();\n }\n\n syncTodos(\n todos: Array<{ content: string; status: string; activeForm?: string }>,\n ): void {\n super.syncTodos(todos);\n this.store.syncTodos(todos);\n }\n\n setHandoffText(text: string): void {\n this.store.setHandoffText(text);\n }\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAa,aAAb,cAAgC,UAAU;CACxC,YAAY,OAAqC;AAC/C,SAAO;AADoB,OAAA,QAAA;;CAI7B,UACE,OACM;AACN,QAAM,UAAU,MAAM;AACtB,OAAK,MAAM,UAAU,MAAM;;CAG7B,eAAe,MAAoB;AACjC,OAAK,MAAM,eAAe,KAAK"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as posthogIntegrationConfig } from "./posthog-integration-
|
|
1
|
+
import { r as posthogIntegrationConfig } from "./posthog-integration-DJX4qTDQ.js";
|
|
2
2
|
import { u as runWizard } from "./bin.js";
|
|
3
3
|
//#region src/commands/basic-integration/interactive.ts
|
|
4
4
|
/** Default flow: run the posthog-integration program through the TUI. */
|
|
@@ -8,4 +8,4 @@ function runInteractive(argv) {
|
|
|
8
8
|
//#endregion
|
|
9
9
|
export { runInteractive };
|
|
10
10
|
|
|
11
|
-
//# sourceMappingURL=interactive-
|
|
11
|
+
//# sourceMappingURL=interactive-BRB6w6KG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interactive-
|
|
1
|
+
{"version":3,"file":"interactive-BRB6w6KG.js","names":[],"sources":["../src/commands/basic-integration/interactive.ts"],"sourcesContent":["import type { Arguments } from 'yargs';\nimport { runWizard } from '@lib/runners';\nimport { posthogIntegrationConfig } from '@lib/programs/posthog-integration/index';\n\n/** Default flow: run the posthog-integration program through the TUI. */\nexport function runInteractive(argv: Arguments): void {\n runWizard(posthogIntegrationConfig, argv);\n}\n"],"mappings":";;;;AAKA,SAAgB,eAAe,MAAuB;AACpD,WAAU,0BAA0B,KAAK"}
|
|
@@ -132,4 +132,4 @@ function localMcpSkillsNotice(flags) {
|
|
|
132
132
|
//#endregion
|
|
133
133
|
export { getLocalDev as a, resolveLocalDev as c, checkLocalServices as i, MCP_LOCAL_URL as n, initLocalDev as o, POSTHOG_LOCAL_URL as r, localMcpSkillsNotice as s, CONTEXT_MILL_LOCAL_URL as t };
|
|
134
134
|
|
|
135
|
-
//# sourceMappingURL=local-dev-
|
|
135
|
+
//# sourceMappingURL=local-dev-DPZiIPCK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-dev-
|
|
1
|
+
{"version":3,"file":"local-dev-DPZiIPCK.js","names":[],"sources":["../src/lib/local-dev.ts"],"sourcesContent":["/**\n * Local development targets: context-mill (skills), MCP, and PostHog. Each is\n * independently switchable — CI runs local skills against the *production* MCP\n * — with `--local-dev` as a shorthand for all three.\n *\n * `wizard mcp add --local` is unrelated: it writes a `posthog-local` entry into\n * the user's editor config rather than retargeting this run. Hence no\n * `--local` here.\n */\n\nexport const CONTEXT_MILL_LOCAL_URL = 'http://localhost:8765';\nexport const MCP_LOCAL_URL = 'http://localhost:8787/mcp';\n/** Pins the API, app, OAuth, and the LLM gateway derived from them. */\nexport const POSTHOG_LOCAL_URL = 'http://localhost:8010';\n\n/**\n * Raw yargs values. The three specific flags are declared without a `default`\n * so they stay `undefined` when absent — see `resolveLocalDev`.\n */\nexport type LocalDevFlags = {\n localDev?: boolean;\n localMcp?: boolean;\n localContextMill?: boolean;\n localPosthog?: boolean;\n};\n\nexport type ResolvedLocalDev = {\n localMcp: boolean;\n localContextMill: boolean;\n localPosthog: boolean;\n};\n\n/**\n * A specific flag beats `--local-dev` in both directions. `??` is load-bearing:\n * it falls through only on `undefined`, so giving the specific flags a yargs\n * `default: false` would silently break both the umbrella and `--no-local-mcp`.\n */\nexport function resolveLocalDev(flags: LocalDevFlags): ResolvedLocalDev {\n const umbrella = flags.localDev ?? false;\n return {\n localMcp: flags.localMcp ?? umbrella,\n localContextMill: flags.localContextMill ?? umbrella,\n localPosthog: flags.localPosthog ?? umbrella,\n };\n}\n\n/** yargs populates both spellings, so read either. */\nexport function localDevFromArgv(\n argv: Record<string, unknown>,\n): ResolvedLocalDev {\n const read = (kebab: string, camel: string): boolean | undefined => {\n const value = argv[camel] ?? argv[kebab];\n return typeof value === 'boolean' ? value : undefined;\n };\n return resolveLocalDev({\n localDev: read('local-dev', 'localDev'),\n localMcp: read('local-mcp', 'localMcp'),\n localContextMill: read('local-context-mill', 'localContextMill'),\n localPosthog: read('local-posthog', 'localPosthog'),\n });\n}\n\nconst PRODUCTION_TARGETS: ResolvedLocalDev = {\n localMcp: false,\n localContextMill: false,\n localPosthog: false,\n};\n\nlet resolved: ResolvedLocalDev | null = null;\n\n/**\n * Resolve this process's targets. Called once from the yargs middleware, which\n * covers every command and the env-var spellings alike.\n */\nexport function initLocalDev(argv: Record<string, unknown>): ResolvedLocalDev {\n resolved = localDevFromArgv(argv);\n return resolved;\n}\n\n/**\n * Where this run points. Resolved once because the flags are parsed at startup\n * and never change; threading them through state let call sites read whichever\n * field they happened to have, which is how the intro screens ended up asking\n * the MCP flag where to fetch skills.\n *\n * Uninitialized means no CLI parse ran (a direct-call test) — production.\n */\nexport function getLocalDev(): ResolvedLocalDev {\n return resolved ?? PRODUCTION_TARGETS;\n}\n\n/** Tests only. */\nexport function resetLocalDev(): void {\n resolved = null;\n}\n\ntype LocalService = {\n key: keyof ResolvedLocalDev;\n label: string;\n flag: string;\n /** Probed for reachability — any HTTP reply proves the port is bound. */\n url: string;\n startHint: string;\n};\n\nconst LOCAL_SERVICES: readonly LocalService[] = [\n {\n key: 'localContextMill',\n label: 'context-mill',\n flag: '--local-context-mill',\n url: `${CONTEXT_MILL_LOCAL_URL}/skill-menu.json`,\n startHint: 'npm run dev (in the context-mill repo)',\n },\n {\n key: 'localMcp',\n label: 'MCP server',\n flag: '--local-mcp',\n url: MCP_LOCAL_URL,\n startHint:\n 'hogli start (or pnpm dev:local-resources in posthog/services/mcp)',\n },\n {\n key: 'localPosthog',\n label: 'PostHog',\n flag: '--local-posthog',\n url: POSTHOG_LOCAL_URL,\n startHint: './bin/start (in the posthog repo)',\n },\n] as const;\n\n// Retries because this gate gates `fetchWithRetry` (see fetch-retry.ts) — a\n// blip it would ride out must not abort the run instead. A missing server\n// refuses instantly, so the retries only cost time when one is slow to answer,\n// which is exactly when they're worth paying for.\nconst PROBE_TIMEOUT_MS = 2_000;\nconst PROBE_ATTEMPTS = 3;\nconst PROBE_BACKOFF_MS = 250;\n\nasync function isReachable(url: string): Promise<boolean> {\n for (let attempt = 1; attempt <= PROBE_ATTEMPTS; attempt++) {\n try {\n // Any reply — including 404 or 405 — proves something is listening, which\n // is the only question here. Deliberately not `fetchWithRetry`: that\n // treats a non-ok status as failure, and here it is a pass.\n await fetch(url, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });\n return true;\n } catch {\n if (attempt < PROBE_ATTEMPTS) {\n await new Promise((r) =>\n setTimeout(r, PROBE_BACKOFF_MS * 2 ** (attempt - 1)),\n );\n }\n }\n }\n return false;\n}\n\n/**\n * Probe every service the flags asked to be local. Returns one message naming\n * each unreachable one, or undefined if all are up (or none were requested).\n *\n * Without this a dead local server surfaces late and badly: a missing\n * context-mill looks like a registry outage, a missing MCP fails mid-run after\n * the agent has already edited files.\n */\nexport async function checkLocalServices(\n resolved: ResolvedLocalDev,\n): Promise<string | undefined> {\n const requested = LOCAL_SERVICES.filter((s) => resolved[s.key]);\n if (requested.length === 0) return undefined;\n\n const reachable = await Promise.all(requested.map((s) => isReachable(s.url)));\n const dead = requested.filter((_, i) => !reachable[i]);\n if (dead.length === 0) return undefined;\n\n return [\n `Local ${dead.length === 1 ? 'service is' : 'services are'} not running:`,\n '',\n ...dead.map(\n (s) =>\n ` ${s.label} — nothing listening at ${new URL(s.url).origin}\\n` +\n ` requested by ${s.flag}\\n` +\n ` start it with: ${s.startHint}`,\n ),\n '',\n 'Start the missing services, or drop the flag to use production.',\n ].join('\\n');\n}\n\n/**\n * `--local-mcp` used to select local skills too; anyone still relying on that\n * would silently get production skills. Temporary — drop after a release or two.\n */\nexport function localMcpSkillsNotice(flags: LocalDevFlags): string | undefined {\n if (flags.localMcp !== true) return undefined;\n if (flags.localContextMill !== undefined || flags.localDev === true) {\n return undefined;\n }\n return (\n '--local-mcp now points only at the local MCP server. ' +\n 'For local skills, add --local-context-mill (or use --local-dev for both).'\n );\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,yBAAyB;AACtC,MAAa,gBAAgB;;AAE7B,MAAa,oBAAoB;;;;;;AAwBjC,SAAgB,gBAAgB,OAAwC;CACtE,MAAM,WAAW,MAAM,YAAY;AACnC,QAAO;EACL,UAAU,MAAM,YAAY;EAC5B,kBAAkB,MAAM,oBAAoB;EAC5C,cAAc,MAAM,gBAAgB;EACrC;;;AAIH,SAAgB,iBACd,MACkB;CAClB,MAAM,QAAQ,OAAe,UAAuC;EAClE,MAAM,QAAQ,KAAK,UAAU,KAAK;AAClC,SAAO,OAAO,UAAU,YAAY,QAAQ,KAAA;;AAE9C,QAAO,gBAAgB;EACrB,UAAU,KAAK,aAAa,WAAW;EACvC,UAAU,KAAK,aAAa,WAAW;EACvC,kBAAkB,KAAK,sBAAsB,mBAAmB;EAChE,cAAc,KAAK,iBAAiB,eAAe;EACpD,CAAC;;AAGJ,MAAM,qBAAuC;CAC3C,UAAU;CACV,kBAAkB;CAClB,cAAc;CACf;AAED,IAAI,WAAoC;;;;;AAMxC,SAAgB,aAAa,MAAiD;AAC5E,YAAW,iBAAiB,KAAK;AACjC,QAAO;;;;;;;;;;AAWT,SAAgB,cAAgC;AAC9C,QAAO,YAAY;;AAiBrB,MAAM,iBAA0C;CAC9C;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,KAAK,GAAG,uBAAuB;EAC/B,WAAW;EAC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} from "./debug-
|
|
1
|
+
import { gt as VERSION, s as logToFile } from "./debug-aA5dm2MR.js";
|
|
2
2
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
3
3
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
4
4
|
import { createJiti } from "jiti";
|
|
@@ -61,4 +61,4 @@ async function setupPostHogMcp(opts) {
|
|
|
61
61
|
//#endregion
|
|
62
62
|
export { fetchInstructions, setupPostHogMcp };
|
|
63
63
|
|
|
64
|
-
//# sourceMappingURL=mcp-
|
|
64
|
+
//# sourceMappingURL=mcp-BXdSTZe6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-
|
|
1
|
+
{"version":3,"file":"mcp-BXdSTZe6.js","names":[],"sources":["../src/lib/agent/runner/harness/pi/mcp.ts"],"sourcesContent":["/**\n * pi has no built-in MCP; `pi-mcp-adapter` — pi's own MCP extension, built here\n * with its supported `createMcpAdapter` embedding API — bridges the same hosted\n * MCP the anthropic path uses into the agent.\n */\n\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { createJiti } from 'jiti';\nimport { VERSION } from '@lib/version';\nimport { logToFile } from '@utils/debug';\n\nconst MCP_TOKEN_ENV = 'POSTHOG_MCP_TOKEN';\n\nexport interface PostHogMcpSetup {\n /** pi ExtensionFactory to add to the resource loader's `extensionFactories`. */\n extensionFactory: (pi: unknown) => void;\n /** Drop the token env var. Call after the run. */\n cleanup: () => void;\n}\n\n/** Server `instructions` for the system prompt — the adapter exposes no accessor, so one standard-SDK handshake; best-effort. */\nexport async function fetchInstructions(\n mcpUrl: string,\n accessToken: string,\n userAgent: string,\n): Promise<string | undefined> {\n const client = new Client({ name: 'posthog-wizard', version: VERSION });\n try {\n const transport = new StreamableHTTPClientTransport(new URL(mcpUrl), {\n requestInit: {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'User-Agent': userAgent,\n },\n },\n });\n await client.connect(transport);\n const instructions = client.getInstructions() || undefined;\n logToFile(`[pi-mcp] instructions ${instructions?.length ?? 0} chars`);\n return instructions;\n } catch (err) {\n logToFile(`[pi-mcp] instructions fetch skipped: ${String(err)}`);\n return undefined;\n } finally {\n await client.close().catch(() => undefined);\n }\n}\n\nexport async function setupPostHogMcp(opts: {\n mcpUrl: string;\n accessToken: string;\n userAgent: string;\n}): Promise<PostHogMcpSetup> {\n const { mcpUrl, accessToken, userAgent } = opts;\n\n // By env NAME: the token stays in this process, off disk, and never reaches pi's env-scrubbed tool subprocesses.\n process.env[MCP_TOKEN_ENV] = accessToken;\n\n // The adapter ships raw TypeScript; loading through jiti is its documented requirement.\n const jiti = createJiti(import.meta.url);\n const mod = await jiti.import('pi-mcp-adapter');\n const extensionFactory = mod.createMcpAdapter({\n config: {\n mcpServers: {\n posthog: {\n url: mcpUrl,\n auth: 'bearer',\n bearerTokenEnv: MCP_TOKEN_ENV,\n headers: { 'User-Agent': userAgent },\n // Connect at extension load — direct tools register without a session_start.\n lifecycle: 'eager',\n // Register only `exec`: `directTools: true` also mints a `posthog_get_<name>` tool per MCP resource, whose sentence-length names overflow Anthropic's 128-char tool-name limit and 400 the whole request.\n directTools: ['exec'],\n exposeResources: false,\n },\n },\n // Disable the proxy `mcp` tool (its search indirection pollutes context); the adapter re-enables it only if no direct tools resolve.\n settings: { disableProxyTool: true, toolPrefix: 'posthog' },\n },\n });\n logToFile(`[pi-mcp] adapter loaded; posthog MCP at ${mcpUrl}`);\n\n const cleanup = (): void => {\n delete process.env[MCP_TOKEN_ENV];\n };\n\n return { extensionFactory, cleanup };\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAM,gBAAgB;;AAUtB,eAAsB,kBACpB,QACA,aACA,WAC6B;CAC7B,MAAM,SAAS,IAAI,OAAO;EAAE,MAAM;EAAkB,SAAS;EAAS,CAAC;AACvE,KAAI;EACF,MAAM,YAAY,IAAI,8BAA8B,IAAI,IAAI,OAAO,EAAE,EACnE,aAAa,EACX,SAAS;GACP,eAAe,UAAU;GACzB,cAAc;GACf,EACF,EACF,CAAC;AACF,QAAM,OAAO,QAAQ,UAAU;EAC/B,MAAM,eAAe,OAAO,iBAAiB,IAAI,KAAA;AACjD,YAAU,yBAAyB,cAAc,UAAU,EAAE,QAAQ;AACrE,SAAO;UACA,KAAK;AACZ,YAAU,wCAAwC,OAAO,IAAI,GAAG;AAChE;WACQ;AACR,QAAM,OAAO,OAAO,CAAC,YAAY,KAAA,EAAU;;;AAI/C,eAAsB,gBAAgB,MAIT;CAC3B,MAAM,EAAE,QAAQ,aAAa,cAAc;AAG3C,SAAQ,IAAI,iBAAiB;CAK7B,MAAM,oBADM,MADC,WAAW,OAAO,KAAK,IAAI,CACjB,OAAO,iBAAiB,EAClB,iBAAiB,EAC5C,QAAQ;EACN,YAAY,EACV,SAAS;GACP,KAAK;GACL,MAAM;GACN,gBAAgB;GAChB,SAAS,EAAE,cAAc,WAAW;GAEpC,WAAW;GAEX,aAAa,CAAC,OAAO;GACrB,iBAAiB;GAClB,EACF;EAED,UAAU;GAAE,kBAAkB;GAAM,YAAY;GAAW;EAC5D,EACF,CAAC;AACF,WAAU,2CAA2C,SAAS;CAE9D,MAAM,gBAAsB;AAC1B,SAAO,QAAQ,IAAI;;AAGrB,QAAO;EAAE;EAAkB;EAAS"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { D as DEFAULT_AGENT_MODEL, pt as WIZARD_USER_AGENT, s as logToFile } from "./debug-
|
|
2
|
-
import { n as analytics } from "./analytics-
|
|
3
|
-
import { d as sanitizeAgentSubprocessEnv, n as buildRunTags, t as buildAgentEnv } from "./agent-interface-
|
|
1
|
+
import { D as DEFAULT_AGENT_MODEL, pt as WIZARD_USER_AGENT, s as logToFile } from "./debug-aA5dm2MR.js";
|
|
2
|
+
import { n as analytics } from "./analytics-tF06lcmE.js";
|
|
3
|
+
import { d as sanitizeAgentSubprocessEnv, n as buildRunTags, q as gatewayAuth, t as buildAgentEnv } from "./agent-interface-CaEptZuu.js";
|
|
4
4
|
//#region src/lib/agent/mcp-prompt-streaming.ts
|
|
5
5
|
let _sdkModule = null;
|
|
6
6
|
async function loadSdk() {
|
|
@@ -146,11 +146,12 @@ async function* runMcpPromptViaSdk(args) {
|
|
|
146
146
|
const { prompt, credentials, signal, resumeSessionId } = args;
|
|
147
147
|
const wizardMetadata = buildTutorialRunTags(args);
|
|
148
148
|
process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS = "true";
|
|
149
|
-
const
|
|
149
|
+
const auth = await gatewayAuth(credentials.host, credentials.accessToken, args.programId);
|
|
150
|
+
const gatewayUrl = auth.gatewayUrl;
|
|
150
151
|
process.env.ANTHROPIC_BASE_URL = gatewayUrl;
|
|
151
|
-
process.env.ANTHROPIC_AUTH_TOKEN =
|
|
152
|
-
process.env.CLAUDE_CODE_OAUTH_TOKEN =
|
|
153
|
-
logToFile(`[runMcpPromptViaSdk] gatewayUrl=${gatewayUrl} tokenPrefix=${
|
|
152
|
+
process.env.ANTHROPIC_AUTH_TOKEN = auth.token;
|
|
153
|
+
process.env.CLAUDE_CODE_OAUTH_TOKEN = auth.token;
|
|
154
|
+
logToFile(`[runMcpPromptViaSdk] gatewayUrl=${gatewayUrl} edition=${auth.edition} tokenPrefix=${auth.token ? auth.token.slice(0, 4) + "***" : "(missing)"}`);
|
|
154
155
|
const { query } = await loadSdk();
|
|
155
156
|
const abortController = new AbortController();
|
|
156
157
|
if (signal.aborted) abortController.abort();
|
|
@@ -215,13 +216,13 @@ async function* runMcpPromptViaSdk(args) {
|
|
|
215
216
|
allowedTools: ["mcp__posthog-wizard__*"],
|
|
216
217
|
env: {
|
|
217
218
|
...sanitizeAgentSubprocessEnv(process.env),
|
|
218
|
-
ANTHROPIC_BASE_URL:
|
|
219
|
-
ANTHROPIC_AUTH_TOKEN:
|
|
220
|
-
CLAUDE_CODE_OAUTH_TOKEN:
|
|
219
|
+
ANTHROPIC_BASE_URL: auth.gatewayUrl,
|
|
220
|
+
ANTHROPIC_AUTH_TOKEN: auth.token,
|
|
221
|
+
CLAUDE_CODE_OAUTH_TOKEN: auth.token,
|
|
221
222
|
CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS: "true",
|
|
222
223
|
POSTHOG_MCP_TOKEN: credentials.accessToken,
|
|
223
224
|
MCP_CONNECTION_NONBLOCKING: "0",
|
|
224
|
-
ANTHROPIC_CUSTOM_HEADERS: buildAgentEnv(wizardMetadata ?? {}, {})
|
|
225
|
+
ANTHROPIC_CUSTOM_HEADERS: buildAgentEnv(wizardMetadata ?? {}, {}, auth)
|
|
225
226
|
}
|
|
226
227
|
}
|
|
227
228
|
});
|
|
@@ -246,4 +247,4 @@ async function* runMcpPromptViaSdk(args) {
|
|
|
246
247
|
//#endregion
|
|
247
248
|
export { runMcpPromptViaSdk };
|
|
248
249
|
|
|
249
|
-
//# sourceMappingURL=mcp-prompt-streaming
|
|
250
|
+
//# sourceMappingURL=mcp-prompt-streaming-DhOT15Jj.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-prompt-streaming-DhOT15Jj.js","names":[],"sources":["../src/lib/agent/mcp-prompt-streaming.ts"],"sourcesContent":["/**\n * Streaming prompt runner for the McpSuggestedPromptsScreen.\n *\n * Calls the Claude Agent SDK's `query()` directly with just the PostHog\n * MCP server configured — no skills, no sandbox, no settings sources,\n * no wizard-tools. This is the lightweight cousin of `runAgent` in\n * `agent-interface.ts`: same SDK, much narrower surface, suitable for\n * \"user asked a question, show the answer\" interactions.\n *\n * The function is an async generator that yields `AgentChunk`s extracted\n * from the SDK's message stream. Callers (the screen) consume them via\n * `for await (...)` and render as they arrive.\n */\n\nimport type { AgentChunk } from '@ui/tui/services/mcp-suggested-prompts-services';\nimport type { Credentials } from '@lib/wizard-session';\nimport { DEFAULT_AGENT_MODEL, WIZARD_USER_AGENT } from '@lib/constants';\nimport { logToFile } from '@utils/debug';\nimport { gatewayAuth } from '@lib/gateway-session';\nimport { buildAgentEnv, buildRunTags } from '@lib/agent/agent-interface';\nimport { sanitizeAgentSubprocessEnv } from '@lib/agent/agent-env-isolation';\nimport { analytics } from '@utils/analytics';\n\n// Cached SDK module — first call pays the dynamic-import cost; later\n// calls reuse the same module.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _sdkModule: any | null = null;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadSdk(): Promise<any> {\n if (!_sdkModule) {\n _sdkModule = await import('@anthropic-ai/claude-agent-sdk');\n }\n return _sdkModule;\n}\n\nconst MODEL = DEFAULT_AGENT_MODEL;\n\n// Bounded turn count so a single prompt can't loop forever on the\n// user's nickel. 20 gives the agent room for non-trivial multi-step\n// chains (multi-tool reads → reason → write → verify → summarize) while\n// still capping runaway loops. Worth tuning down once we see real\n// telemetry on average turn counts per prompt.\nconst MAX_TURNS = 30;\n\n/**\n * Extract a short, single-line summary from an arbitrary value. Used\n * for tool-call args and tool-result bodies so the screen has something\n * compact to render.\n */\nfunction summarize(value: unknown, maxLen = 120): string {\n if (value == null) return '';\n let text: string;\n if (typeof value === 'string') text = value;\n else {\n try {\n text = JSON.stringify(value);\n } catch {\n text = String(value);\n }\n }\n text = text.replace(/\\s+/g, ' ').trim();\n if (text.length > maxLen) text = text.slice(0, maxLen - 1) + '…';\n return text;\n}\n\n/**\n * Convert one SDK message into zero or more AgentChunks. Mirrors the\n * subset of message shapes the wizard's main runAgent middleware\n * handles, but narrowed to just the kinds the screen needs to render.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction messageToChunks(message: any): AgentChunk[] {\n const chunks: AgentChunk[] = [];\n\n if (message?.type === 'assistant') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (!block || typeof block !== 'object') continue;\n const type = (block as { type?: string }).type;\n if (type === 'text') {\n const text = (block as { text?: string }).text ?? '';\n if (text) chunks.push({ kind: 'text', text });\n } else if (type === 'tool_use') {\n const name = (block as { name?: string }).name ?? 'tool';\n const input = (block as { input?: unknown }).input;\n // CLI mode's exec tool takes a `command` string; keep it verbatim so\n // the screen can recover the inner tool name for follow-ups.\n const command = (input as { command?: unknown })?.command;\n chunks.push({\n kind: 'tool-call',\n toolName: name,\n detail: summarize(input),\n command: typeof command === 'string' ? command : undefined,\n });\n }\n }\n }\n }\n\n if (message?.type === 'user') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (!block || typeof block !== 'object') continue;\n const type = (block as { type?: string }).type;\n if (type === 'tool_result') {\n const detail = summarize((block as { content?: unknown }).content);\n chunks.push({ kind: 'tool-result', toolName: 'tool', detail });\n }\n }\n }\n }\n\n if (message?.type === 'result') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const sessionId = (message as { session_id?: string }).session_id;\n chunks.push({ kind: 'done', sessionId });\n }\n\n return chunks;\n}\n\n/**\n * Build a system-prompt append that nudges the agent to fit its response\n * inside the current terminal window. We can't actually constrain Claude\n * — this is a soft cap that the model usually honors. The screen also\n * applies a hard truncation cap as a fallback for non-compliant runs.\n *\n * Core principle nudged at the model: TALL CONTENT IS BAD, WIDE CONTENT\n * IS GOOD. Default terminal is 120 columns × 24 rows — that's a lot of\n * horizontal space, not much vertical. Spread data across columns, never\n * stack it down rows when a horizontal layout would work.\n */\nfunction buildTerminalFitPrompt(): string {\n const cols = process.stdout.columns ?? 120;\n const rows = process.stdout.rows ?? 24;\n // Reserve rows for wizard chrome (title, status, hint, margins).\n const messageBudget = Math.max(8, rows - 10);\n\n return [\n `You are responding inside a CLI window that is exactly ${cols} columns wide and ${rows} rows tall. The user CAN'T SCROLL — your entire reply must fit on screen.`,\n ``,\n `LAYOUT PRINCIPLE: tall content is the enemy, wide content is your friend. You have ${cols} columns of horizontal space; use them. Spread data across columns instead of stacking it down rows.`,\n ``,\n `Tables:`,\n `- Max 5 body rows. The prompts the user picks already constrain results to 5 or fewer — honor that and do not pad with extra rows.`,\n `- If a tool result returns more than 5 items, show the top 5 and mention the rest count inline (e.g. \"...and 12 more\").`,\n `- Prefer transposing wide-but-short data (items across columns, metrics down rows) when labels are short.`,\n `- A two-column table with many rows is the tall layout to AVOID.`,\n ``,\n `Other limits:`,\n `- Aim for 3-5 lines of prose. Maximum ${messageBudget} lines total.`,\n `- DO NOT announce what you are about to do. Skip preamble like \"I'll query…\", \"Let me check…\", \"Now I'll…\", \"I'm going to…\". Go straight to running tools and then the answer.`,\n `- Lists: if there are 6+ short items, format them inline (comma-separated), not as a vertical bullet list.`,\n `- For tool results, summarize the 1-3 numbers that matter. Do NOT echo raw JSON or the full payload.`,\n `- Code blocks: no language tag, no leading blank lines.`,\n `- No closing pleasantries (\"let me know if…\", \"feel free to…\"). Stop when the answer is delivered.`,\n `- No section headers unless the response actually has multiple sections.`,\n ``,\n `Naming saved artifacts:`,\n `- Every dashboard, insight, notebook, or annotation you create MUST include \"(wizard MCP tutorial)\" at the end of its title or name field. Examples: \"Weekly signups (wizard MCP tutorial)\", \"Top errors this week (wizard MCP tutorial)\", \"Onboarding analysis (wizard MCP tutorial)\".`,\n `- This applies on both create AND rename calls. If the user asks you to rename a saved artifact, preserve the \"(wizard MCP tutorial)\" suffix unless they explicitly ask you to drop it.`,\n `- Reason: lets the user find / clean up everything this tutorial created from one search in PostHog. Don't skip it — it's the only signal they'll have that an artifact came from the wizard.`,\n ``,\n `Tone & framing:`,\n `- This is a tutorial demoing PostHog (the product the user just installed). You are showing it off, not auditing it. Stay constructive and neutral about PostHog throughout.`,\n `- Don't editorialize about PostHog's reliability, performance, or cost. Describe what the data shows; treat anomalies as the user's data, not a platform issue.`,\n `- If a tool call fails or returns nothing, say \"the query didn't return data — try a different angle\" or similar. Do NOT speculate about outages, gateway issues, MCP problems, or service health.`,\n `- Avoid value-laden phrases like \"worth investigating\", \"concerning\", \"red flag\", \"problematic\", \"suspicious\", \"alarming\" when describing the user's metrics. Stick to what the numbers show; the user draws conclusions.`,\n ].join('\\n');\n}\n\n/**\n * Gateway trace tags for a tutorial prompt run — without them the gateway has\n * nothing to attribute its `$ai_generation` events to. Returns `{}` when no\n * program is supplied. Exported so the contract is testable without the SDK.\n */\nexport function buildTutorialRunTags(args: {\n programId?: string;\n integration?: string;\n}): Record<string, string> {\n if (!args.programId) return {};\n return buildRunTags({\n programId: args.programId,\n // The tutorial usually has no detected framework; fall back to the\n // program so the axis is never an empty string.\n integration: args.integration ?? args.programId,\n runId: analytics.runId,\n build: analytics.build,\n });\n}\n\nexport async function* runMcpPromptViaSdk(args: {\n prompt: string;\n credentials: Credentials;\n signal: AbortSignal;\n /** When set, the SDK loads the named session's prior turns as\n * context so the follow-up prompt can reference what the agent\n * already showed. */\n resumeSessionId?: string;\n /** Program this run's gateway spend attributes to. Omitting it fails the run\n * rather than going unattributed, so every caller must supply one. */\n programId?: string;\n /** Integration label for the trace tags; the tutorial usually has none. */\n integration?: string;\n}): AsyncIterable<AgentChunk> {\n const { prompt, credentials, signal, resumeSessionId } = args;\n\n // Assembled here rather than passed in so the TUI service layer doesn't\n // have to import this module's dependencies.\n const wizardMetadata = buildTutorialRunTags(args);\n\n // Route the SDK's LLM calls through the PostHog LLM gateway, authed\n // with the user's OAuth access token. Set BEFORE loading the SDK in\n // case any in-process code reads env at module init (cached base\n // URLs, OAuth setup, etc.) — same reason `initializeAgent` does this\n // before its query() call. Without these the SDK tries to\n // authenticate directly against Anthropic and 401s with \"Invalid\n // authentication credentials\".\n process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS = 'true';\n\n // The url, the bearer and the header edition are one unit: a run must take\n // all three from the same resolved posture.\n const auth = await gatewayAuth(\n credentials.host,\n credentials.accessToken,\n args.programId,\n );\n const gatewayUrl = auth.gatewayUrl;\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = auth.token;\n process.env.CLAUDE_CODE_OAUTH_TOKEN = auth.token;\n\n logToFile(\n `[runMcpPromptViaSdk] gatewayUrl=${gatewayUrl} edition=${\n auth.edition\n } tokenPrefix=${auth.token ? auth.token.slice(0, 4) + '***' : '(missing)'}`,\n );\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const { query } = await loadSdk();\n\n // Bridge external AbortSignal → SDK AbortController.\n const abortController = new AbortController();\n if (signal.aborted) abortController.abort();\n else\n signal.addEventListener('abort', () => abortController.abort(), {\n once: true,\n });\n\n const mcpUrl = credentials.host.mcpUrl;\n logToFile(\n `[runMcpPromptViaSdk] mcpUrl=${mcpUrl} model=${MODEL} resume=${\n resumeSessionId ?? '(none)'\n }`,\n );\n\n // The SDK expects an async generator for the prompt that stays open\n // until the result is received. For a single-turn prompt we yield one\n // user message and then await an abort (which fires when streaming\n // completes or the caller cancels).\n const createPromptStream = async function* () {\n yield {\n type: 'user' as const,\n session_id: '',\n message: { role: 'user' as const, content: prompt },\n parent_tool_use_id: null,\n };\n // Hold the stream open until abort. The SDK closes its end when it\n // sees a `result` message; we close ours via the abortController in\n // the finally block below.\n await new Promise<void>((resolve) => {\n if (abortController.signal.aborted) {\n resolve();\n return;\n }\n abortController.signal.addEventListener('abort', () => resolve(), {\n once: true,\n });\n });\n };\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n const response = query({\n prompt: createPromptStream(),\n options: {\n abortController,\n model: MODEL,\n cwd: process.cwd(),\n permissionMode: 'acceptEdits',\n maxTurns: MAX_TURNS,\n // Match agent-interface.ts — the 1M context beta is what keeps\n // resumed follow-up sessions from truncating after a few turns.\n betas: ['context-1m-2025-08-07'],\n // Only load project-level skills/settings. Without this the SDK\n // defaults to ['user', 'project'] and a user's\n // `~/.claude/settings.json` (apiKeyHelper / env block) can\n // override the OAuth routing we set above.\n settingSources: ['project'],\n // When set, the SDK replays the named session's turns into the\n // new query so the follow-up prompt has full conversation\n // context. Omit on the first prompt for a fresh session.\n ...(resumeSessionId ? { resume: resumeSessionId } : {}),\n // Without `canUseTool` the SDK falls back to \"ask the user\" on\n // every MCP tool call — `permissionMode: 'acceptEdits'` only\n // relaxes Edit/Write, not MCP. Our Ink TUI has no surface to\n // answer that prompt, so the agent would stall mid-stream\n // saying things like \"needs your approval to create dashboard\".\n // The tutorial's whole point is demoing the MCP tools against\n // the user's project, so we auto-allow everything that matches\n // the prefix and deny anything else (defense in depth — the\n // `allowedTools` filter above already enforces this).\n canUseTool: (toolName: string, input: unknown) => {\n if (toolName.startsWith('mcp__posthog-wizard__')) {\n return Promise.resolve({\n behavior: 'allow' as const,\n updatedInput: (input ?? {}) as Record<string, unknown>,\n });\n }\n logToFile(`[runMcpPromptViaSdk] denying non-MCP tool: ${toolName}`);\n return Promise.resolve({\n behavior: 'deny' as const,\n message: `${toolName} is not available in the MCP tutorial — only PostHog MCP tools are permitted.`,\n });\n },\n systemPrompt: {\n type: 'preset',\n preset: 'claude_code',\n append: buildTerminalFitPrompt(),\n },\n mcpServers: {\n 'posthog-wizard': {\n type: 'http',\n url: mcpUrl,\n headers: {\n // Env reference, not the token: the SDK puts this config on the\n // spawned CLI's argv, where `ps` shows it to any local process.\n Authorization: 'Bearer ${POSTHOG_MCP_TOKEN}',\n 'User-Agent': WIZARD_USER_AGENT,\n },\n // CLI mode's single `exec` tool carries the full command reference\n // on its schema — keep it in context, never deferred behind tool\n // search.\n alwaysLoad: true,\n },\n },\n // Only let the agent use MCP tools — no shell, no file I/O,\n // no Read/Edit/Write. This is a chat-with-MCP run, not a\n // wizard skill execution.\n allowedTools: ['mcp__posthog-wizard__*'],\n env: {\n // Drop the ENTIRE ANTHROPIC_*/CLAUDE_CODE_* namespace from the\n // inherited env so no shell/settings value can silently bypass the\n // PostHog gateway and defeat quota tracking / the OAuth flow; the\n // wizard's own gateway routing is injected fresh below. See\n // agent-env-isolation.ts.\n ...sanitizeAgentSubprocessEnv(process.env),\n // Gateway routing from this run's own auth, not process.env: a\n // concurrent run writes those globals too, and there is an await\n // between the write above and this read.\n ANTHROPIC_BASE_URL: auth.gatewayUrl,\n ANTHROPIC_AUTH_TOKEN: auth.token,\n CLAUDE_CODE_OAUTH_TOKEN: auth.token,\n CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS: 'true',\n // The MCP config resolves this in the child; sending the value would\n // put it on the CLI's argv.\n POSTHOG_MCP_TOKEN: credentials.accessToken,\n // SDK 0.3.142+ connects MCP servers in the background by\n // default; without this the agent may try to call tools\n // before posthog-wizard is connected on turn 1.\n MCP_CONNECTION_NONBLOCKING: '0',\n // Bedrock fallback plus this run's trace tags — the gateway reads\n // these to attribute its `$ai_generation` events. Flags stay empty:\n // the tutorial doesn't fork on any.\n ANTHROPIC_CUSTOM_HEADERS: buildAgentEnv(\n wizardMetadata ?? {},\n {},\n auth,\n ),\n },\n },\n });\n\n for await (const message of response as AsyncIterable<unknown>) {\n if (signal.aborted) return;\n for (const chunk of messageToChunks(message)) {\n yield chunk;\n if (chunk.kind === 'done') return;\n }\n }\n } catch (err) {\n const text = err instanceof Error ? err.message : String(err);\n logToFile(`[runMcpPromptViaSdk] error: ${text}`);\n yield { kind: 'error', text };\n } finally {\n // Closes the prompt stream so `query()` shuts down cleanly even if\n // we never saw a 'result' message.\n abortController.abort();\n }\n}\n"],"mappings":";;;;AA0BA,IAAI,aAAyB;AAG7B,eAAe,UAAwB;AACrC,KAAI,CAAC,WACH,cAAa,MAAM,OAAO;AAE5B,QAAO;;AAGT,MAAM,QAAQ;AAOd,MAAM,YAAY;;;;;;AAOlB,SAAS,UAAU,OAAgB,SAAS,KAAa;AACvD,KAAI,SAAS,KAAM,QAAO;CAC1B,IAAI;AACJ,KAAI,OAAO,UAAU,SAAU,QAAO;KAEpC,KAAI;AACF,SAAO,KAAK,UAAU,MAAM;SACtB;AACN,SAAO,OAAO,MAAM;;AAGxB,QAAO,KAAK,QAAQ,QAAQ,IAAI,CAAC,MAAM;AACvC,KAAI,KAAK,SAAS,OAAQ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QAAQ,EAAE;AAC5C,UAAM;AACN,QAAI,MAAM,SAAS,OAAQ;;;UAGxB,KAAK;EACZ,MAAM,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;AAC7D,YAAU,+BAA+B,OAAO;AAChD,QAAM;GAAE,MAAM;GAAS;GAAM;WACrB;AAGR,kBAAgB,OAAO"}
|
|
@@ -1,12 +1,17 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { c as emitWizardError, l as ErrorCodes } from "./errors-BHervYGs.js";
|
|
2
|
+
import { f as getUI } from "./debug-aA5dm2MR.js";
|
|
2
3
|
//#region src/commands/basic-integration/non-interactive.ts
|
|
3
4
|
/** Print the "needs a TTY" error and exit. Used when no `--ci` flag and no TTY. */
|
|
4
5
|
function failNonInteractive() {
|
|
5
6
|
getUI().intro("PostHog Wizard");
|
|
6
7
|
getUI().log.error("This installer requires an interactive terminal (TTY) to run.\nIt appears you are running in a non-interactive environment.\nPlease run the wizard in an interactive terminal.\n\nFor CI/CD environments, use --ci mode:\n npx @posthog/wizard --ci --region us --api-key phx_xxx");
|
|
8
|
+
emitWizardError({
|
|
9
|
+
code: ErrorCodes.CliInteractiveRequired,
|
|
10
|
+
message: "This installer requires an interactive terminal (TTY) to run."
|
|
11
|
+
});
|
|
7
12
|
process.exit(1);
|
|
8
13
|
}
|
|
9
14
|
//#endregion
|
|
10
15
|
export { failNonInteractive };
|
|
11
16
|
|
|
12
|
-
//# sourceMappingURL=non-interactive-
|
|
17
|
+
//# sourceMappingURL=non-interactive-ezilF3PY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"non-interactive-ezilF3PY.js","names":[],"sources":["../src/commands/basic-integration/non-interactive.ts"],"sourcesContent":["import { getUI } from '@ui';\nimport { ErrorCodes } from '@lib/errors';\nimport { emitWizardError } from '@lib/errors';\n\n/** Print the \"needs a TTY\" error and exit. Used when no `--ci` flag and no TTY. */\nexport function failNonInteractive(): void {\n getUI().intro('PostHog Wizard');\n getUI().log.error(\n 'This installer requires an interactive terminal (TTY) to run.\\n' +\n 'It appears you are running in a non-interactive environment.\\n' +\n 'Please run the wizard in an interactive terminal.\\n\\n' +\n 'For CI/CD environments, use --ci mode:\\n' +\n ' npx @posthog/wizard --ci --region us --api-key phx_xxx',\n );\n emitWizardError({\n code: ErrorCodes.CliInteractiveRequired,\n message: 'This installer requires an interactive terminal (TTY) to run.',\n });\n process.exit(1);\n}\n"],"mappings":";;;;AAKA,SAAgB,qBAA2B;AACzC,QAAO,CAAC,MAAM,iBAAiB;AAC/B,QAAO,CAAC,IAAI,MACV,qRAKD;AACD,iBAAgB;EACd,MAAM,WAAW;EACjB,SAAS;EACV,CAAC;AACF,SAAQ,KAAK,EAAE"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as analytics } from "./analytics-
|
|
2
|
-
import { a as applyReadHandoffs, i as applyEnqueue, n as REMARK_ASK, r as applyComplete, t as HANDOFF_FIELDS } from "./queue-tools-
|
|
1
|
+
import { n as analytics } from "./analytics-tF06lcmE.js";
|
|
2
|
+
import { a as applyReadHandoffs, i as applyEnqueue, n as REMARK_ASK, r as applyComplete, t as HANDOFF_FIELDS } from "./queue-tools-i_TmeI02.js";
|
|
3
3
|
import { Type } from "typebox";
|
|
4
4
|
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
5
5
|
//#region src/lib/agent/runner/harness/pi/orchestrator-tools.ts
|
|
@@ -102,4 +102,4 @@ function createPiOrchestratorTools(ctx) {
|
|
|
102
102
|
//#endregion
|
|
103
103
|
export { createPiOrchestratorTools };
|
|
104
104
|
|
|
105
|
-
//# sourceMappingURL=orchestrator-tools-
|
|
105
|
+
//# sourceMappingURL=orchestrator-tools-D82843t_.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orchestrator-tools-
|
|
1
|
+
{"version":3,"file":"orchestrator-tools-D82843t_.js","names":[],"sources":["../src/lib/agent/runner/harness/pi/orchestrator-tools.ts"],"sourcesContent":["/**\n * Orchestrator queue tools as pi custom tools. The queue lives in-process, and\n * `applyEnqueue` / `applyComplete` / `applyReadHandoffs` are plain exported\n * functions — so pi needs no MCP transport, just `defineTool` wrappers around\n * the same guards and apply logic the anthropic path mounts through the\n * wizard-tools MCP server. Tool names match the MCP short names so the shared\n * agent prompts are unchanged.\n *\n * Lazily imported (typebox is ESM and must stay out of the static module graph\n * so CommonJS unit tests can load the backend seam without parsing it).\n */\n\nimport { Type } from 'typebox';\nimport { defineTool } from '@earendil-works/pi-coding-agent';\nimport type { ToolDefinition } from '@earendil-works/pi-coding-agent';\nimport { analytics } from '@utils/analytics';\nimport {\n applyComplete,\n applyEnqueue,\n applyReadHandoffs,\n HANDOFF_FIELDS,\n REMARK_ASK,\n type EnqueueArgs,\n type OrchestratorToolsContext,\n} from '../../sequence/orchestrator/queue-tools';\nimport type { TaskHandoff } from '../../sequence/orchestrator/queue';\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\n/** Mirrors the zod `HANDOFF_SHAPE`; both read their text from HANDOFF_FIELDS. */\nconst HANDOFF_PARAMS = Type.Object({\n goals: Type.String({ description: HANDOFF_FIELDS.goals }),\n did: Type.String({ description: HANDOFF_FIELDS.did }),\n forNextAgent: Type.String({ description: HANDOFF_FIELDS.forNextAgent }),\n filesTouched: Type.Optional(\n Type.Array(Type.String(), { description: HANDOFF_FIELDS.filesTouched }),\n ),\n evidence: Type.Optional(\n Type.String({ description: HANDOFF_FIELDS.evidence }),\n ),\n assumptions: Type.Optional(\n Type.String({ description: HANDOFF_FIELDS.assumptions }),\n ),\n conflict: Type.Optional(\n Type.String({ description: HANDOFF_FIELDS.conflict }),\n ),\n reportSection: Type.Optional(\n Type.String({ description: HANDOFF_FIELDS.reportSection }),\n ),\n});\n\n/** Exported so the parity test can compare both harnesses' field sets. */\nexport const PI_HANDOFF_PARAM_KEYS: readonly string[] = Object.keys(\n HANDOFF_PARAMS.properties,\n);\n\n/** The three queue tools bound to one agent's orchestrator context. */\nexport function createPiOrchestratorTools(\n ctx: OrchestratorToolsContext,\n): ToolDefinition[] {\n const enqueueTask = defineTool({\n name: 'enqueue_task',\n label: 'Enqueue task',\n description:\n 'Add a task to the orchestrator queue. Use it to seed work and to enqueue follow-up work you discover. Keep tasks small and discrete.',\n promptSnippet:\n 'enqueue_task(type, label, dependsOn, reason) — add a task to the queue; returns its id',\n parameters: Type.Object({\n type: Type.String({\n description: `The task type. One of: ${ctx.validTypes.join(', ')}.`,\n }),\n label: Type.Optional(\n Type.String({\n description:\n 'A short label for the UI — the action in a few words (e.g. \"Add the PostHog SDK\", \"Initialize PostHog\"). Leave out file names, class names, and other specifics.',\n }),\n ),\n inputs: Type.Optional(Type.Record(Type.String(), Type.Unknown())),\n dependsOn: Type.Optional(\n Type.Array(Type.String(), {\n description: 'Task ids that must be done before this task runs.',\n }),\n ),\n model: Type.Optional(Type.String()),\n reason: Type.String({\n description: 'One line on why this task is needed.',\n }),\n }),\n execute(_id, args) {\n const res = applyEnqueue(ctx, args as EnqueueArgs);\n if (!res.ok) {\n analytics.wizardCapture('orchestrator guard tripped', {\n guard: res.guard,\n type: (args as EnqueueArgs).type,\n });\n return Promise.resolve(text(`Error: ${res.message}`));\n }\n return Promise.resolve(text(JSON.stringify({ id: res.task.id })));\n },\n });\n\n const completeTask = defineTool({\n name: 'complete_task',\n label: 'Complete task',\n description:\n \"Report the outcome of your task. Always call this exactly once when you finish, with a structured handoff for the next agent. Use status 'not needed' when the task does not apply to this project and you cannot do it (say why in the handoff) — not 'done'.\",\n promptSnippet:\n 'complete_task(status, handoff) — report your outcome exactly once when done',\n parameters: Type.Object({\n status: Type.Union([\n Type.Literal('done'),\n Type.Literal('failed'),\n Type.Literal('not needed'),\n ]),\n handoff: HANDOFF_PARAMS,\n remark: Type.Optional(Type.String({ description: REMARK_ASK })),\n }),\n execute(_id, args) {\n const res = applyComplete(\n ctx,\n args as {\n status: 'done' | 'failed' | 'not needed';\n handoff: TaskHandoff;\n remark?: string;\n },\n );\n if (!res.ok) return Promise.resolve(text(`Error: ${res.message}`));\n return Promise.resolve(text('ok'));\n },\n });\n\n const readHandoffs = defineTool({\n name: 'read_handoffs',\n label: 'Read handoffs',\n description:\n 'Read structured handoffs from earlier tasks. With no argument, returns the handoffs of your dependencies.',\n promptSnippet:\n 'read_handoffs() — read what earlier tasks handed off (defaults to your dependencies)',\n parameters: Type.Object({\n type: Type.Optional(Type.String()),\n taskId: Type.Optional(Type.String()),\n }),\n execute(_id, args) {\n const handoffs = applyReadHandoffs(\n ctx,\n args as { type?: string; taskId?: string },\n );\n return Promise.resolve(text(JSON.stringify(handoffs, null, 2)));\n },\n });\n\n return [enqueueTask, completeTask, readHandoffs];\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2BA,SAAS,KAAK,GAGZ;AACA,QAAO;EAAE,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAG,CAAC;EAAE,SAAS,EAAE;EAAE;;;AAI9D,MAAM,iBAAiB,KAAK,OAAO;CACjC,OAAO,KAAK,OAAO,EAAE,aAAa,eAAe,OAAO,CAAC;CACzD,KAAK,KAAK,OAAO,EAAE,aAAa,eAAe,KAAK,CAAC;CACrD,cAAc,KAAK,OAAO,EAAE,aAAa,eAAe,cAAc,CAAC;CACvE,cAAc,KAAK,SACjB,KAAK,MAAM,KAAK,QAAQ,EAAE,EAAE,aAAa,eAAe,cAAc,CAAC,CACxE;CACD,UAAU,KAAK,SACb,KAAK,OAAO,EAAE,aAAa,eAAe,UAAU,CAAC,CACtD;CACD,aAAa,KAAK,SAChB,KAAK,OAAO,EAAE,aAAa,eAAe,aAAa,CAAC,CACzD;CACD,UAAU,KAAK,SACb,KAAK,OAAO,EAAE,aAAa,eAAe,UAAU,CAAC,CACtD;CACD,eAAe,KAAK,SAClB,KAAK,OAAO,EAAE,aAAa,eAAe,eAAe,CAAC,CAC3D;CACF,CAAC;AAGsD,OAAO,KAC7D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