@phren/cli 0.1.17 → 0.1.19
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/cli/cli.js +0 -4
- package/dist/cli/hooks.js +5 -1
- package/dist/entrypoint.d.ts +0 -3
- package/dist/entrypoint.js +19 -74
- package/dist/generated/memory-ui-graph.browser.js +27 -27
- package/dist/hooks.d.ts +43 -3
- package/dist/hooks.js +196 -16
- package/dist/index.js +5 -6
- package/dist/init/config.d.ts +28 -0
- package/dist/init/config.js +107 -2
- package/dist/init/init-configure.js +13 -1
- package/dist/init/preferences.d.ts +8 -0
- package/dist/link/doctor.js +13 -6
- package/dist/memory-ui-graph.runtime.js +27 -27
- package/dist/shell/render-api.d.ts +1 -1
- package/dist/tools/hooks.js +38 -0
- package/dist/ui/deep-void.d.ts +1 -0
- package/dist/ui/deep-void.js +413 -0
- package/dist/ui/graph.js +3 -0
- package/dist/ui/page.js +3 -1
- package/package.json +3 -3
- package/dist/agent-launch.d.ts +0 -1
- package/dist/agent-launch.js +0 -48
package/dist/hooks.d.ts
CHANGED
|
@@ -13,8 +13,28 @@ export interface LifecycleCommands {
|
|
|
13
13
|
stop: string;
|
|
14
14
|
hookTool: string;
|
|
15
15
|
}
|
|
16
|
-
export
|
|
16
|
+
export interface BuildLifecycleOptions {
|
|
17
|
+
/**
|
|
18
|
+
* Force POSIX shell syntax even on Windows. Used for tools that execute
|
|
19
|
+
* hook commands via Git Bash (e.g. GitHub Copilot CLI's `bash:` key).
|
|
20
|
+
*/
|
|
21
|
+
forcePosix?: boolean;
|
|
22
|
+
}
|
|
23
|
+
export declare function buildLifecycleCommands(phrenPath: string, options?: BuildLifecycleOptions): LifecycleCommands;
|
|
17
24
|
export declare function buildSharedLifecycleCommands(): LifecycleCommands;
|
|
25
|
+
/**
|
|
26
|
+
* Windows-only: append `%USERPROFILE%\.local\bin` to the user's persistent
|
|
27
|
+
* PATH if it isn't already there. On Linux/macOS `~/.local/bin` is on PATH by
|
|
28
|
+
* default (XDG / `.profile`); on Windows nothing adds it, so the `phren.cmd`
|
|
29
|
+
* wrapper is invisible to cmd/PowerShell/Git Bash until we fix PATH.
|
|
30
|
+
*
|
|
31
|
+
* Returns:
|
|
32
|
+
* "added" — PATH was updated (user must open a new terminal).
|
|
33
|
+
* "already" — dir was already on the user PATH.
|
|
34
|
+
* "skipped" — not Windows (nothing to do).
|
|
35
|
+
* "failed" — PowerShell call failed; caller should surface a manual hint.
|
|
36
|
+
*/
|
|
37
|
+
export declare function ensureLocalBinOnWindowsPath(): "added" | "already" | "skipped" | "failed";
|
|
18
38
|
/**
|
|
19
39
|
* Install a lightweight `phren` CLI wrapper at ~/.local/bin/phren so the bare
|
|
20
40
|
* `phren` command works without a global npm install. The wrapper simply execs
|
|
@@ -29,7 +49,7 @@ export interface HookToolPreferences {
|
|
|
29
49
|
}
|
|
30
50
|
export declare function clearHookPrefsCache(): void;
|
|
31
51
|
export declare function isToolHookEnabled(phrenPath: string, tool: string): boolean;
|
|
32
|
-
export type CustomHookEvent = "pre-save" | "post-save" | "post-search" | "pre-finding" | "post-finding" | "pre-index" | "post-index" | "post-session-end" | "post-consolidate";
|
|
52
|
+
export type CustomHookEvent = "pre-save" | "post-save" | "post-search" | "pre-finding" | "post-finding" | "pre-index" | "post-index" | "post-session-end" | "post-consolidate" | "pre-prompt";
|
|
33
53
|
export interface CommandHookEntry {
|
|
34
54
|
event: CustomHookEvent;
|
|
35
55
|
command: string;
|
|
@@ -42,7 +62,7 @@ export interface WebhookHookEntry {
|
|
|
42
62
|
timeout?: number;
|
|
43
63
|
}
|
|
44
64
|
export type CustomHookEntry = CommandHookEntry | WebhookHookEntry;
|
|
45
|
-
export declare const HOOK_EVENT_VALUES: readonly ["pre-save", "post-save", "post-search", "pre-finding", "post-finding", "pre-index", "post-index", "post-session-end", "post-consolidate"];
|
|
65
|
+
export declare const HOOK_EVENT_VALUES: readonly ["pre-save", "post-save", "post-search", "pre-finding", "post-finding", "pre-index", "post-index", "post-session-end", "post-consolidate", "pre-prompt"];
|
|
46
66
|
/** Return the target (URL or shell command) for display or matching. */
|
|
47
67
|
export declare function getHookTarget(h: CustomHookEntry): string;
|
|
48
68
|
export declare function validateCustomHookCommand(command: string): string | null;
|
|
@@ -52,6 +72,26 @@ export declare function runCustomHooks(phrenPath: string, event: CustomHookEvent
|
|
|
52
72
|
ran: number;
|
|
53
73
|
errors: HookError[];
|
|
54
74
|
};
|
|
75
|
+
/**
|
|
76
|
+
* Read the set of pre-prompt command strings already registered as sibling
|
|
77
|
+
* UserPromptSubmit entries in Claude Code's settings.json. Used by
|
|
78
|
+
* runPrePromptHooks to avoid double-running a hook that Claude Code is
|
|
79
|
+
* already invoking directly (in parallel with phren's own hook).
|
|
80
|
+
*
|
|
81
|
+
* Returns an empty set on any error or if the settings file doesn't exist.
|
|
82
|
+
*/
|
|
83
|
+
export declare function getRegisteredPrePromptSiblingCommands(): Set<string>;
|
|
84
|
+
/**
|
|
85
|
+
* Run pre-prompt custom hooks, piping stdinJson to each and capturing stdout.
|
|
86
|
+
* Returns concatenated stdout from all matching hooks (empty string if none).
|
|
87
|
+
*
|
|
88
|
+
* Skips any hook whose command is already registered as a sibling
|
|
89
|
+
* UserPromptSubmit entry in Claude Code's settings.json — those are dispatched
|
|
90
|
+
* directly by Claude Code in parallel with phren's hook, so re-running them
|
|
91
|
+
* here would duplicate their work and (worse) re-import their slow latency
|
|
92
|
+
* into phren's response budget.
|
|
93
|
+
*/
|
|
94
|
+
export declare function runPrePromptHooks(phrenPath: string, stdinJson: string, siblingCommandsOverride?: Set<string>): string;
|
|
55
95
|
export interface HookConfigOptions {
|
|
56
96
|
tools?: Set<string>;
|
|
57
97
|
allTools?: boolean;
|
package/dist/hooks.js
CHANGED
|
@@ -78,15 +78,16 @@ function buildPackageLifecycleCommands() {
|
|
|
78
78
|
hookTool: `npx -y ${packageSpec} hook-tool`,
|
|
79
79
|
};
|
|
80
80
|
}
|
|
81
|
-
export function buildLifecycleCommands(phrenPath) {
|
|
81
|
+
export function buildLifecycleCommands(phrenPath, options = {}) {
|
|
82
82
|
const entry = resolveCliEntryScript();
|
|
83
|
-
const
|
|
83
|
+
const nativeWindows = process.platform === "win32" && !options.forcePosix;
|
|
84
84
|
const escapedPhren = phrenPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
85
85
|
const quotedPhren = shellEscape(phrenPath);
|
|
86
86
|
// Prefer the stable wrapper at ~/.local/bin/phren — it survives nvm switches
|
|
87
87
|
// and npx cache clears because it has a built-in npx fallback.
|
|
88
88
|
const localBinDir = homePath(".local", "bin");
|
|
89
|
-
const
|
|
89
|
+
const wrapperBaseName = process.platform === "win32" ? "phren.cmd" : "phren";
|
|
90
|
+
const wrapperPath = path.join(localBinDir, wrapperBaseName);
|
|
90
91
|
const wrapperExists = fs.existsSync(wrapperPath) && (() => {
|
|
91
92
|
try {
|
|
92
93
|
return fs.readFileSync(wrapperPath, "utf8").includes("PHREN_CLI_WRAPPER");
|
|
@@ -96,7 +97,7 @@ export function buildLifecycleCommands(phrenPath) {
|
|
|
96
97
|
}
|
|
97
98
|
})();
|
|
98
99
|
if (wrapperExists) {
|
|
99
|
-
if (
|
|
100
|
+
if (nativeWindows) {
|
|
100
101
|
return {
|
|
101
102
|
sessionStart: `set "PHREN_PATH=${escapedPhren}" && "${wrapperPath}" hook-session-start`,
|
|
102
103
|
userPromptSubmit: `set "PHREN_PATH=${escapedPhren}" && "${wrapperPath}" hook-prompt`,
|
|
@@ -116,7 +117,7 @@ export function buildLifecycleCommands(phrenPath) {
|
|
|
116
117
|
if (entry) {
|
|
117
118
|
const escapedEntry = entry.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
118
119
|
const quotedEntry = shellEscape(entry);
|
|
119
|
-
if (
|
|
120
|
+
if (nativeWindows) {
|
|
120
121
|
return {
|
|
121
122
|
sessionStart: `set "PHREN_PATH=${escapedPhren}" && node "${escapedEntry}" hook-session-start`,
|
|
122
123
|
userPromptSubmit: `set "PHREN_PATH=${escapedPhren}" && node "${escapedEntry}" hook-prompt`,
|
|
@@ -133,7 +134,7 @@ export function buildLifecycleCommands(phrenPath) {
|
|
|
133
134
|
}
|
|
134
135
|
// Last resort — npx
|
|
135
136
|
const packageSpec = phrenPackageSpec();
|
|
136
|
-
if (
|
|
137
|
+
if (nativeWindows) {
|
|
137
138
|
return {
|
|
138
139
|
sessionStart: `set "PHREN_PATH=${escapedPhren}" && npx -y ${packageSpec} hook-session-start`,
|
|
139
140
|
userPromptSubmit: `set "PHREN_PATH=${escapedPhren}" && npx -y ${packageSpec} hook-prompt`,
|
|
@@ -151,18 +152,18 @@ export function buildLifecycleCommands(phrenPath) {
|
|
|
151
152
|
export function buildSharedLifecycleCommands() {
|
|
152
153
|
return buildPackageLifecycleCommands();
|
|
153
154
|
}
|
|
154
|
-
function withHookToolEnv(command, tool) {
|
|
155
|
-
if (process.platform === "win32") {
|
|
155
|
+
function withHookToolEnv(command, tool, forcePosix = false) {
|
|
156
|
+
if (process.platform === "win32" && !forcePosix) {
|
|
156
157
|
return `set "PHREN_HOOK_TOOL=${tool}" && ${command}`;
|
|
157
158
|
}
|
|
158
159
|
return `PHREN_HOOK_TOOL=${shellEscape(tool)} ${command}`;
|
|
159
160
|
}
|
|
160
|
-
function withHookToolLifecycleCommands(lifecycle, tool) {
|
|
161
|
+
function withHookToolLifecycleCommands(lifecycle, tool, forcePosix = false) {
|
|
161
162
|
return {
|
|
162
|
-
sessionStart: withHookToolEnv(lifecycle.sessionStart, tool),
|
|
163
|
-
userPromptSubmit: withHookToolEnv(lifecycle.userPromptSubmit, tool),
|
|
164
|
-
stop: withHookToolEnv(lifecycle.stop, tool),
|
|
165
|
-
hookTool: withHookToolEnv(lifecycle.hookTool, tool),
|
|
163
|
+
sessionStart: withHookToolEnv(lifecycle.sessionStart, tool, forcePosix),
|
|
164
|
+
userPromptSubmit: withHookToolEnv(lifecycle.userPromptSubmit, tool, forcePosix),
|
|
165
|
+
stop: withHookToolEnv(lifecycle.stop, tool, forcePosix),
|
|
166
|
+
hookTool: withHookToolEnv(lifecycle.hookTool, tool, forcePosix),
|
|
166
167
|
};
|
|
167
168
|
}
|
|
168
169
|
function installSessionWrapper(tool, phrenPath) {
|
|
@@ -181,11 +182,16 @@ function installSessionWrapper(tool, phrenPath) {
|
|
|
181
182
|
const stopCmd = entry
|
|
182
183
|
? `node "${entry}" hook-stop`
|
|
183
184
|
: `npx -y ${packageSpec} hook-stop`;
|
|
185
|
+
const timeoutSec = Math.ceil(HOOK_TIMEOUT_MS / 1000);
|
|
186
|
+
// Bound hook execution with PowerShell Start-Job + Wait-Job so a hung
|
|
187
|
+
// hook can never stall the user's real command. The hook command is
|
|
188
|
+
// passed via env var to avoid nested-quote escaping hell in cmd.
|
|
184
189
|
const content = `@echo off\r
|
|
185
190
|
setlocal\r
|
|
186
191
|
set "REAL_BIN=${realBinary}"\r
|
|
187
192
|
if not defined PHREN_PATH set "PHREN_PATH=${phrenPath}"\r
|
|
188
193
|
set "PHREN_HOOK_TOOL=${tool}"\r
|
|
194
|
+
if not defined PHREN_HOOK_TIMEOUT_S set "PHREN_HOOK_TIMEOUT_S=${timeoutSec}"\r
|
|
189
195
|
\r
|
|
190
196
|
if "%~1"=="-h" goto :passthrough\r
|
|
191
197
|
if "%~1"=="--help" goto :passthrough\r
|
|
@@ -195,14 +201,21 @@ if "%~1"=="--version" goto :passthrough\r
|
|
|
195
201
|
if "%~1"=="version" goto :passthrough\r
|
|
196
202
|
if "%~1"=="completion" goto :passthrough\r
|
|
197
203
|
\r
|
|
198
|
-
|
|
204
|
+
set "PHREN_HOOK_CMD=${sessionStartCmd}"\r
|
|
205
|
+
call :run_with_timeout\r
|
|
199
206
|
"%REAL_BIN%" %*\r
|
|
200
207
|
set "EXIT_STATUS=%ERRORLEVEL%"\r
|
|
201
|
-
|
|
208
|
+
set "PHREN_HOOK_CMD=${stopCmd}"\r
|
|
209
|
+
call :run_with_timeout\r
|
|
202
210
|
exit /b %EXIT_STATUS%\r
|
|
203
211
|
\r
|
|
204
212
|
:passthrough\r
|
|
205
213
|
"%REAL_BIN%" %*\r
|
|
214
|
+
exit /b %ERRORLEVEL%\r
|
|
215
|
+
\r
|
|
216
|
+
:run_with_timeout\r
|
|
217
|
+
powershell -NoProfile -NonInteractive -Command "$j = Start-Job -ScriptBlock { & cmd /c $env:PHREN_HOOK_CMD *> $null }; if (-not (Wait-Job $j -Timeout ([int]$env:PHREN_HOOK_TIMEOUT_S))) { Stop-Job $j -ErrorAction SilentlyContinue }; Remove-Job $j -Force -ErrorAction SilentlyContinue | Out-Null" >nul 2>&1\r
|
|
218
|
+
exit /b 0\r
|
|
206
219
|
`;
|
|
207
220
|
try {
|
|
208
221
|
fs.mkdirSync(localBinDir, { recursive: true });
|
|
@@ -272,6 +285,59 @@ exit $status
|
|
|
272
285
|
return false;
|
|
273
286
|
}
|
|
274
287
|
}
|
|
288
|
+
/**
|
|
289
|
+
* Windows-only: append `%USERPROFILE%\.local\bin` to the user's persistent
|
|
290
|
+
* PATH if it isn't already there. On Linux/macOS `~/.local/bin` is on PATH by
|
|
291
|
+
* default (XDG / `.profile`); on Windows nothing adds it, so the `phren.cmd`
|
|
292
|
+
* wrapper is invisible to cmd/PowerShell/Git Bash until we fix PATH.
|
|
293
|
+
*
|
|
294
|
+
* Returns:
|
|
295
|
+
* "added" — PATH was updated (user must open a new terminal).
|
|
296
|
+
* "already" — dir was already on the user PATH.
|
|
297
|
+
* "skipped" — not Windows (nothing to do).
|
|
298
|
+
* "failed" — PowerShell call failed; caller should surface a manual hint.
|
|
299
|
+
*/
|
|
300
|
+
export function ensureLocalBinOnWindowsPath() {
|
|
301
|
+
if (process.platform !== "win32")
|
|
302
|
+
return "skipped";
|
|
303
|
+
const target = homePath(".local", "bin");
|
|
304
|
+
// Current session PATH check — cheap early-out to avoid spawning PowerShell
|
|
305
|
+
// on re-runs in a terminal that already inherits the updated PATH.
|
|
306
|
+
const currentEntries = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
|
|
307
|
+
const alreadyOnSessionPath = currentEntries.some((entry) => path.resolve(entry).toLowerCase() === target.toLowerCase());
|
|
308
|
+
// Always read persistent user PATH — session PATH can be stale in other terminals.
|
|
309
|
+
const readScript = `$p = [Environment]::GetEnvironmentVariable('Path','User'); if ($null -eq $p) { '' } else { $p }`;
|
|
310
|
+
let userPath = "";
|
|
311
|
+
try {
|
|
312
|
+
userPath = execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", readScript], {
|
|
313
|
+
encoding: "utf8",
|
|
314
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
315
|
+
timeout: EXEC_TIMEOUT_QUICK_MS,
|
|
316
|
+
}).trim();
|
|
317
|
+
}
|
|
318
|
+
catch (err) {
|
|
319
|
+
debugLog(`ensureLocalBinOnWindowsPath: read failed: ${errorMessage(err)}`);
|
|
320
|
+
return "failed";
|
|
321
|
+
}
|
|
322
|
+
const userEntries = userPath.split(";").filter(Boolean);
|
|
323
|
+
const alreadyPersisted = userEntries.some((entry) => entry.toLowerCase() === target.toLowerCase());
|
|
324
|
+
if (alreadyPersisted)
|
|
325
|
+
return alreadyOnSessionPath ? "already" : "already";
|
|
326
|
+
const newUserPath = userEntries.length > 0 ? `${userPath};${target}` : target;
|
|
327
|
+
const escaped = newUserPath.replace(/'/g, "''");
|
|
328
|
+
const writeScript = `[Environment]::SetEnvironmentVariable('Path','${escaped}','User')`;
|
|
329
|
+
try {
|
|
330
|
+
execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", writeScript], {
|
|
331
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
332
|
+
timeout: EXEC_TIMEOUT_QUICK_MS,
|
|
333
|
+
});
|
|
334
|
+
return "added";
|
|
335
|
+
}
|
|
336
|
+
catch (err) {
|
|
337
|
+
debugLog(`ensureLocalBinOnWindowsPath: write failed: ${errorMessage(err)}`);
|
|
338
|
+
return "failed";
|
|
339
|
+
}
|
|
340
|
+
}
|
|
275
341
|
/**
|
|
276
342
|
* Install a lightweight `phren` CLI wrapper at ~/.local/bin/phren so the bare
|
|
277
343
|
* `phren` command works without a global npm install. The wrapper simply execs
|
|
@@ -399,6 +465,7 @@ export const HOOK_EVENT_VALUES = [
|
|
|
399
465
|
"pre-finding", "post-finding",
|
|
400
466
|
"pre-index", "post-index",
|
|
401
467
|
"post-session-end", "post-consolidate",
|
|
468
|
+
"pre-prompt",
|
|
402
469
|
];
|
|
403
470
|
const VALID_HOOK_EVENTS = new Set(HOOK_EVENT_VALUES);
|
|
404
471
|
const MAX_HOOK_COMMAND_LENGTH = 1000;
|
|
@@ -667,6 +734,114 @@ export function runCustomHooks(phrenPath, event, env = {}) {
|
|
|
667
734
|
}
|
|
668
735
|
return { ran: matching.length, errors };
|
|
669
736
|
}
|
|
737
|
+
/**
|
|
738
|
+
* Read the set of pre-prompt command strings already registered as sibling
|
|
739
|
+
* UserPromptSubmit entries in Claude Code's settings.json. Used by
|
|
740
|
+
* runPrePromptHooks to avoid double-running a hook that Claude Code is
|
|
741
|
+
* already invoking directly (in parallel with phren's own hook).
|
|
742
|
+
*
|
|
743
|
+
* Returns an empty set on any error or if the settings file doesn't exist.
|
|
744
|
+
*/
|
|
745
|
+
export function getRegisteredPrePromptSiblingCommands() {
|
|
746
|
+
const out = new Set();
|
|
747
|
+
try {
|
|
748
|
+
const settingsPath = hookConfigPath("claude");
|
|
749
|
+
if (!fs.existsSync(settingsPath))
|
|
750
|
+
return out;
|
|
751
|
+
const parsed = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
|
|
752
|
+
if (!parsed || typeof parsed !== "object")
|
|
753
|
+
return out;
|
|
754
|
+
const hooksObj = parsed.hooks;
|
|
755
|
+
if (!hooksObj || typeof hooksObj !== "object")
|
|
756
|
+
return out;
|
|
757
|
+
const ups = hooksObj.UserPromptSubmit;
|
|
758
|
+
if (!Array.isArray(ups))
|
|
759
|
+
return out;
|
|
760
|
+
for (const entry of ups) {
|
|
761
|
+
if (!entry || typeof entry !== "object")
|
|
762
|
+
continue;
|
|
763
|
+
const inner = entry.hooks;
|
|
764
|
+
if (!Array.isArray(inner))
|
|
765
|
+
continue;
|
|
766
|
+
for (const h of inner) {
|
|
767
|
+
if (h && typeof h === "object") {
|
|
768
|
+
const cmd = h.command;
|
|
769
|
+
if (typeof cmd === "string" && cmd.length > 0)
|
|
770
|
+
out.add(cmd);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
catch (err) {
|
|
776
|
+
debugLog(`getRegisteredPrePromptSiblingCommands: ${errorMessage(err)}`);
|
|
777
|
+
}
|
|
778
|
+
return out;
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Run pre-prompt custom hooks, piping stdinJson to each and capturing stdout.
|
|
782
|
+
* Returns concatenated stdout from all matching hooks (empty string if none).
|
|
783
|
+
*
|
|
784
|
+
* Skips any hook whose command is already registered as a sibling
|
|
785
|
+
* UserPromptSubmit entry in Claude Code's settings.json — those are dispatched
|
|
786
|
+
* directly by Claude Code in parallel with phren's hook, so re-running them
|
|
787
|
+
* here would duplicate their work and (worse) re-import their slow latency
|
|
788
|
+
* into phren's response budget.
|
|
789
|
+
*/
|
|
790
|
+
export function runPrePromptHooks(phrenPath, stdinJson, siblingCommandsOverride) {
|
|
791
|
+
const hooks = readCustomHooks(phrenPath);
|
|
792
|
+
const siblingCommands = siblingCommandsOverride ?? getRegisteredPrePromptSiblingCommands();
|
|
793
|
+
const matching = hooks.filter((h) => h.event === "pre-prompt" &&
|
|
794
|
+
"command" in h &&
|
|
795
|
+
!siblingCommands.has(h.command));
|
|
796
|
+
if (matching.length === 0)
|
|
797
|
+
return "";
|
|
798
|
+
const isWindows = process.platform === "win32";
|
|
799
|
+
const shellCmd = isWindows ? "cmd" : "sh";
|
|
800
|
+
const outputs = [];
|
|
801
|
+
for (const hook of matching) {
|
|
802
|
+
if (!("command" in hook))
|
|
803
|
+
continue;
|
|
804
|
+
const cmdErr = validateCustomHookCommand(hook.command);
|
|
805
|
+
if (cmdErr) {
|
|
806
|
+
debugLog(`runPrePromptHooks: skipped (validation failed): ${cmdErr}`);
|
|
807
|
+
appendHookErrorLog(phrenPath, "pre-prompt", cmdErr);
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
const shellArgs = isWindows ? ["/c", hook.command] : ["-c", hook.command];
|
|
811
|
+
const mergedEnv = { ...process.env, PHREN_PATH: phrenPath, PHREN_HOOK_EVENT: "pre-prompt" };
|
|
812
|
+
if (isWindows) {
|
|
813
|
+
for (const [key, val] of Object.entries(mergedEnv)) {
|
|
814
|
+
if (typeof val === "string") {
|
|
815
|
+
mergedEnv[key] = val.replace(/[&|<>^%]/g, "");
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
try {
|
|
820
|
+
const result = execFileSync(shellCmd, shellArgs, {
|
|
821
|
+
cwd: phrenPath,
|
|
822
|
+
encoding: "utf8",
|
|
823
|
+
input: stdinJson,
|
|
824
|
+
timeout: hook.timeout ?? DEFAULT_CUSTOM_HOOK_TIMEOUT,
|
|
825
|
+
env: mergedEnv,
|
|
826
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
827
|
+
});
|
|
828
|
+
const trimmed = (result ?? "").trim();
|
|
829
|
+
if (trimmed)
|
|
830
|
+
outputs.push(trimmed);
|
|
831
|
+
}
|
|
832
|
+
catch (err) {
|
|
833
|
+
const message = `pre-prompt: ${hook.command}: ${errorMessage(err)}`;
|
|
834
|
+
debugLog(`runPrePromptHooks: ${message}`);
|
|
835
|
+
try {
|
|
836
|
+
appendHookErrorLog(phrenPath, "pre-prompt", errorMessage(err));
|
|
837
|
+
}
|
|
838
|
+
catch (logErr) {
|
|
839
|
+
logger.debug("runPrePromptHooks hookErrorLog", errorMessage(logErr));
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
return outputs.join("\n");
|
|
844
|
+
}
|
|
670
845
|
export function configureAllHooks(phrenPath, options = {}) {
|
|
671
846
|
const configured = [];
|
|
672
847
|
const detected = options.tools
|
|
@@ -677,7 +852,12 @@ export function configureAllHooks(phrenPath, options = {}) {
|
|
|
677
852
|
const lifecycle = buildLifecycleCommands(phrenPath);
|
|
678
853
|
// ── GitHub Copilot CLI (user-level: ~/.github/hooks/phren.json) ──────────
|
|
679
854
|
if (detected.has("copilot")) {
|
|
680
|
-
|
|
855
|
+
// Copilot CLI invokes the `bash` key through Git Bash on Windows, so the
|
|
856
|
+
// lifecycle commands must use POSIX shell syntax (not cmd's `set "VAR="`).
|
|
857
|
+
const copilotLifecycleBase = process.platform === "win32"
|
|
858
|
+
? buildLifecycleCommands(phrenPath, { forcePosix: true })
|
|
859
|
+
: lifecycle;
|
|
860
|
+
const copilotLifecycle = withHookToolLifecycleCommands(copilotLifecycleBase, "copilot", true);
|
|
681
861
|
const copilotFile = hookConfigPath("copilot", phrenPath);
|
|
682
862
|
const copilotHooksDir = path.dirname(copilotFile);
|
|
683
863
|
try {
|
package/dist/index.js
CHANGED
|
@@ -25,7 +25,6 @@ import { printIntegratedHelp, printIntegratedVersion, resolveTopLevelInvocation,
|
|
|
25
25
|
import { startEmbeddingWarmup } from "./startup-embedding.js";
|
|
26
26
|
import { resolveRuntimeProfile } from "./runtime-profile.js";
|
|
27
27
|
import { VERSION as PACKAGE_VERSION } from "./package-metadata.js";
|
|
28
|
-
import { runBundledAgentCli } from "./agent-launch.js";
|
|
29
28
|
const invocation = resolveTopLevelInvocation(process.argv.slice(2));
|
|
30
29
|
if (invocation.kind === "help") {
|
|
31
30
|
printIntegratedHelp();
|
|
@@ -36,11 +35,11 @@ if (invocation.kind === "version") {
|
|
|
36
35
|
process.exit(0);
|
|
37
36
|
}
|
|
38
37
|
if (invocation.kind === "manage") {
|
|
39
|
-
await runTopLevelCommand(invocation.argv, { allowDefaultShell:
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
|
|
38
|
+
const handled = await runTopLevelCommand(invocation.argv, { allowDefaultShell: true });
|
|
39
|
+
if (!handled) {
|
|
40
|
+
console.error(`Unknown command: ${invocation.argv[0]}\nRun 'phren --help' for available commands.`);
|
|
41
|
+
process.exit(1);
|
|
42
|
+
}
|
|
44
43
|
process.exit(process.exitCode ?? 0);
|
|
45
44
|
}
|
|
46
45
|
const phrenPath = findPhrenPathWithArg(invocation.phrenArg);
|
package/dist/init/config.d.ts
CHANGED
|
@@ -20,6 +20,34 @@ export declare function patchJsonFile(filePath: string, patch: (data: JsonObject
|
|
|
20
20
|
export declare function removeTomlMcpServer(filePath: string): boolean;
|
|
21
21
|
export declare function removeMcpServerAtPath(filePath: string): boolean;
|
|
22
22
|
export declare function isPhrenCommand(command: string): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Reconcile the set of pre-prompt custom hook commands in `customHooks` with
|
|
25
|
+
* sibling `UserPromptSubmit` entries in Claude Code's settings.json hooks map.
|
|
26
|
+
*
|
|
27
|
+
* Why: phren's chained `runPrePromptHooks` runs custom hooks sequentially
|
|
28
|
+
* inside its own UserPromptSubmit handler, so a slow custom hook (e.g. one
|
|
29
|
+
* that does an `ls` against a OneDrive-backed WSL mount) eats phren's whole
|
|
30
|
+
* response budget and times out before injecting anything. Registering each
|
|
31
|
+
* pre-prompt custom hook as a peer `UserPromptSubmit` entry lets Claude Code
|
|
32
|
+
* dispatch it in parallel with phren's own hook — they get independent
|
|
33
|
+
* timeout budgets and one cannot block the other.
|
|
34
|
+
*
|
|
35
|
+
* Identification: phren tracks "managed" sibling commands in
|
|
36
|
+
* `prefs.managedPrePromptSiblingCommands`. On each sync we (a) append a new
|
|
37
|
+
* sibling for each pre-prompt command not already in settings.json, (b)
|
|
38
|
+
* remove sibling entries whose command was previously managed but is no
|
|
39
|
+
* longer in `customHooks`, and (c) leave any user-authored hook entries
|
|
40
|
+
* (entries whose command never appeared in the managed list) untouched.
|
|
41
|
+
*
|
|
42
|
+
* Webhook custom hooks are not affected — they're already async/fire-and-
|
|
43
|
+
* forget and don't compete for hook event time.
|
|
44
|
+
*
|
|
45
|
+
* Idempotent.
|
|
46
|
+
*/
|
|
47
|
+
export declare function upsertCustomPrePromptSiblings(hooksMap: HookMap, phrenPath: string): {
|
|
48
|
+
added: number;
|
|
49
|
+
removed: number;
|
|
50
|
+
};
|
|
23
51
|
export declare function configureClaude(phrenPath: string, opts?: {
|
|
24
52
|
mcpEnabled?: boolean;
|
|
25
53
|
hooksEnabled?: boolean;
|
package/dist/init/config.js
CHANGED
|
@@ -8,8 +8,9 @@ import { buildLifecycleCommands, commandExists } from "../hooks.js";
|
|
|
8
8
|
import { isRecord, hookConfigPath, homePath, readRootManifest, atomicWriteText, } from "../shared.js";
|
|
9
9
|
import { isFeatureEnabled, errorMessage } from "../utils.js";
|
|
10
10
|
import { probeVsCodeConfig, resolveCodexMcpConfig, resolveCopilotMcpConfig, resolveCursorMcpConfig, } from "../provider-adapters.js";
|
|
11
|
-
import { getMcpEnabledPreference, getHooksEnabledPreference } from "./preferences.js";
|
|
11
|
+
import { getMcpEnabledPreference, getHooksEnabledPreference, readInstallPreferences, updateInstallPreferences } from "./preferences.js";
|
|
12
12
|
import { resolveEntryScript, log, VERSION } from "./shared.js";
|
|
13
|
+
import { readCustomHooks } from "../hooks.js";
|
|
13
14
|
function getObjectProp(value, key) {
|
|
14
15
|
const candidate = value[key];
|
|
15
16
|
return isRecord(candidate) ? candidate : undefined;
|
|
@@ -41,8 +42,11 @@ function buildMcpServerConfig(phrenPath) {
|
|
|
41
42
|
args: [entryScript, phrenPath],
|
|
42
43
|
};
|
|
43
44
|
}
|
|
45
|
+
// MCP clients spawn servers with { shell: false } on Windows, so the bare
|
|
46
|
+
// `npx` name can't resolve the `npx.cmd` shim and the server fails to start.
|
|
47
|
+
// Using `npx.cmd` on win32 matches how child_process resolves Windows binaries.
|
|
44
48
|
return {
|
|
45
|
-
command: "npx",
|
|
49
|
+
command: process.platform === "win32" ? "npx.cmd" : "npx",
|
|
46
50
|
args: ["-y", `phren@${VERSION}`, phrenPath],
|
|
47
51
|
};
|
|
48
52
|
}
|
|
@@ -157,6 +161,95 @@ export function isPhrenCommand(command) {
|
|
|
157
161
|
return true;
|
|
158
162
|
return false;
|
|
159
163
|
}
|
|
164
|
+
/**
|
|
165
|
+
* Reconcile the set of pre-prompt custom hook commands in `customHooks` with
|
|
166
|
+
* sibling `UserPromptSubmit` entries in Claude Code's settings.json hooks map.
|
|
167
|
+
*
|
|
168
|
+
* Why: phren's chained `runPrePromptHooks` runs custom hooks sequentially
|
|
169
|
+
* inside its own UserPromptSubmit handler, so a slow custom hook (e.g. one
|
|
170
|
+
* that does an `ls` against a OneDrive-backed WSL mount) eats phren's whole
|
|
171
|
+
* response budget and times out before injecting anything. Registering each
|
|
172
|
+
* pre-prompt custom hook as a peer `UserPromptSubmit` entry lets Claude Code
|
|
173
|
+
* dispatch it in parallel with phren's own hook — they get independent
|
|
174
|
+
* timeout budgets and one cannot block the other.
|
|
175
|
+
*
|
|
176
|
+
* Identification: phren tracks "managed" sibling commands in
|
|
177
|
+
* `prefs.managedPrePromptSiblingCommands`. On each sync we (a) append a new
|
|
178
|
+
* sibling for each pre-prompt command not already in settings.json, (b)
|
|
179
|
+
* remove sibling entries whose command was previously managed but is no
|
|
180
|
+
* longer in `customHooks`, and (c) leave any user-authored hook entries
|
|
181
|
+
* (entries whose command never appeared in the managed list) untouched.
|
|
182
|
+
*
|
|
183
|
+
* Webhook custom hooks are not affected — they're already async/fire-and-
|
|
184
|
+
* forget and don't compete for hook event time.
|
|
185
|
+
*
|
|
186
|
+
* Idempotent.
|
|
187
|
+
*/
|
|
188
|
+
export function upsertCustomPrePromptSiblings(hooksMap, phrenPath) {
|
|
189
|
+
const customHooks = readCustomHooks(phrenPath);
|
|
190
|
+
const desired = [];
|
|
191
|
+
for (const h of customHooks) {
|
|
192
|
+
if (h.event !== "pre-prompt")
|
|
193
|
+
continue;
|
|
194
|
+
if (!("command" in h))
|
|
195
|
+
continue;
|
|
196
|
+
const cmd = h.command.trim();
|
|
197
|
+
if (!cmd)
|
|
198
|
+
continue;
|
|
199
|
+
const timeoutSec = h.timeout != null ? Math.max(1, Math.ceil(h.timeout / 1000)) : 15;
|
|
200
|
+
desired.push({ command: cmd, timeoutSec });
|
|
201
|
+
}
|
|
202
|
+
const desiredCommands = new Set(desired.map((d) => d.command));
|
|
203
|
+
const prefs = readInstallPreferences(phrenPath);
|
|
204
|
+
const previouslyManaged = new Set(Array.isArray(prefs.managedPrePromptSiblingCommands) ? prefs.managedPrePromptSiblingCommands : []);
|
|
205
|
+
if (!Array.isArray(hooksMap.UserPromptSubmit))
|
|
206
|
+
hooksMap.UserPromptSubmit = [];
|
|
207
|
+
const eventHooks = hooksMap.UserPromptSubmit;
|
|
208
|
+
// Remove stale siblings: previously managed but no longer desired
|
|
209
|
+
let removed = 0;
|
|
210
|
+
for (let i = eventHooks.length - 1; i >= 0; i--) {
|
|
211
|
+
const entry = eventHooks[i];
|
|
212
|
+
const inner = entry?.hooks;
|
|
213
|
+
if (!Array.isArray(inner) || inner.length !== 1)
|
|
214
|
+
continue;
|
|
215
|
+
const cmd = typeof inner[0]?.command === "string" ? inner[0].command : "";
|
|
216
|
+
if (!cmd)
|
|
217
|
+
continue;
|
|
218
|
+
if (previouslyManaged.has(cmd) && !desiredCommands.has(cmd)) {
|
|
219
|
+
eventHooks.splice(i, 1);
|
|
220
|
+
removed++;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// Compute set of commands currently present in settings.json (any entry)
|
|
224
|
+
const presentCommands = new Set();
|
|
225
|
+
for (const entry of eventHooks) {
|
|
226
|
+
const inner = entry?.hooks;
|
|
227
|
+
if (!Array.isArray(inner))
|
|
228
|
+
continue;
|
|
229
|
+
for (const h of inner) {
|
|
230
|
+
if (typeof h?.command === "string")
|
|
231
|
+
presentCommands.add(h.command);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
// Append new siblings for each desired command not already present
|
|
235
|
+
let added = 0;
|
|
236
|
+
for (const d of desired) {
|
|
237
|
+
if (presentCommands.has(d.command))
|
|
238
|
+
continue;
|
|
239
|
+
eventHooks.push({
|
|
240
|
+
matcher: "",
|
|
241
|
+
hooks: [{ type: "command", command: d.command, timeout: d.timeoutSec }],
|
|
242
|
+
});
|
|
243
|
+
added++;
|
|
244
|
+
}
|
|
245
|
+
// Update bookkeeping: managed = current desired set
|
|
246
|
+
const newManaged = Array.from(desiredCommands).sort();
|
|
247
|
+
const oldManaged = Array.from(previouslyManaged).sort();
|
|
248
|
+
if (newManaged.length !== oldManaged.length || newManaged.some((c, i) => c !== oldManaged[i])) {
|
|
249
|
+
updateInstallPreferences(phrenPath, () => ({ managedPrePromptSiblingCommands: newManaged }));
|
|
250
|
+
}
|
|
251
|
+
return { added, removed };
|
|
252
|
+
}
|
|
160
253
|
export function configureClaude(phrenPath, opts = {}) {
|
|
161
254
|
const settingsPath = hookConfigPath("claude");
|
|
162
255
|
const claudeJsonPath = homePath(".claude.json");
|
|
@@ -214,6 +307,18 @@ export function configureClaude(phrenPath, opts = {}) {
|
|
|
214
307
|
command: lifecycle.userPromptSubmit || `node "${entryScript}" hook-prompt`,
|
|
215
308
|
timeout: 3,
|
|
216
309
|
});
|
|
310
|
+
// Mirror pre-prompt custom hooks into Claude's settings.json as
|
|
311
|
+
// peer UserPromptSubmit entries so they run in parallel with phren
|
|
312
|
+
// and don't share its 3-second timeout budget. See
|
|
313
|
+
// upsertCustomPrePromptSiblings docstring for details.
|
|
314
|
+
try {
|
|
315
|
+
upsertCustomPrePromptSiblings(hooksMap, phrenPath);
|
|
316
|
+
}
|
|
317
|
+
catch (err) {
|
|
318
|
+
// Sync is best-effort: a malformed prefs file should not break
|
|
319
|
+
// the rest of configureClaude. Surface a warning and continue.
|
|
320
|
+
console.warn(`configureClaude: pre-prompt sibling sync failed: ${errorMessage(err)}`);
|
|
321
|
+
}
|
|
217
322
|
upsertPhrenHook("Stop", {
|
|
218
323
|
type: "command",
|
|
219
324
|
command: lifecycle.stop,
|
|
@@ -8,7 +8,7 @@ import * as crypto from "crypto";
|
|
|
8
8
|
import { getProjectOwnershipDefault } from "../project-config.js";
|
|
9
9
|
import { atomicWriteText, debugLog, readRootManifest, writeRootManifest, } from "../shared.js";
|
|
10
10
|
import { errorMessage } from "../utils.js";
|
|
11
|
-
import { configureAllHooks, installPhrenCliWrapper } from "../hooks.js";
|
|
11
|
+
import { configureAllHooks, installPhrenCliWrapper, ensureLocalBinOnWindowsPath } from "../hooks.js";
|
|
12
12
|
import { updateWorkflowPolicy } from "../shared/governance.js";
|
|
13
13
|
import { configureClaude, configureVSCode, configureCursorMcp, configureCopilotMcp, configureCodexMcp, logMcpTargetStatus, } from "./config.js";
|
|
14
14
|
import { VERSION } from "./shared.js";
|
|
@@ -99,6 +99,18 @@ export function configureHooksIfEnabled(phrenPath, hooksEnabled, verb) {
|
|
|
99
99
|
else {
|
|
100
100
|
log(` Note: phren CLI wrapper not installed (existing non-managed binary, or no entry script found)`);
|
|
101
101
|
}
|
|
102
|
+
// Windows: ensure %USERPROFILE%\.local\bin is on the user PATH so the
|
|
103
|
+
// wrapper is actually discoverable from new terminals.
|
|
104
|
+
if (wrapperInstalled && process.platform === "win32") {
|
|
105
|
+
const pathResult = ensureLocalBinOnWindowsPath();
|
|
106
|
+
if (pathResult === "added") {
|
|
107
|
+
log(` Added %USERPROFILE%\\.local\\bin to your user PATH — open a new terminal to use 'phren' directly.`);
|
|
108
|
+
}
|
|
109
|
+
else if (pathResult === "failed") {
|
|
110
|
+
log(` Note: could not update PATH automatically. Add '%USERPROFILE%\\.local\\bin' to your user PATH manually,`);
|
|
111
|
+
log(` or use 'npx @phren/cli <command>' until then.`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
102
114
|
}
|
|
103
115
|
export function applyOnboardingPreferences(phrenPath, opts) {
|
|
104
116
|
if (opts.projectOwnershipDefault) {
|
|
@@ -12,6 +12,14 @@ export interface InstallPreferences {
|
|
|
12
12
|
installedVersion?: string;
|
|
13
13
|
updatedAt?: string;
|
|
14
14
|
customHooks?: CustomHookEntry[];
|
|
15
|
+
/**
|
|
16
|
+
* Pre-prompt custom hook commands that have been mirrored into Claude
|
|
17
|
+
* Code's settings.json as sibling UserPromptSubmit entries. Used to detect
|
|
18
|
+
* stale siblings on resync so we can remove commands that were deleted
|
|
19
|
+
* from `customHooks`. Internal bookkeeping — managed by
|
|
20
|
+
* `syncPrePromptSiblingsToClaudeSettings`. Do not edit by hand.
|
|
21
|
+
*/
|
|
22
|
+
managedPrePromptSiblingCommands?: string[];
|
|
15
23
|
/** Whether the user intended cross-machine sync ("sync") or local-only ("local"). */
|
|
16
24
|
syncIntent?: "sync" | "local";
|
|
17
25
|
}
|