@devflow-tools/cli 0.16.0 → 0.16.2
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/commands/doctor.d.ts.map +1 -1
- package/dist/commands/doctor.js +266 -5
- package/dist/commands/doctor.js.map +1 -1
- package/dist/commands/server.js +1 -1
- package/dist/commands/start.js +1 -1
- package/dist/lib/plugin-setup.d.ts +5 -6
- package/dist/lib/plugin-setup.d.ts.map +1 -1
- package/dist/lib/plugin-setup.js +132 -27
- package/dist/lib/plugin-setup.js.map +1 -1
- package/dist/lib/with-server.js +1 -1
- package/dist/plugin-files/.claude-plugin/plugin.json +1 -1
- package/dist/plugin-files/dist/hooks/hook-client.js +5 -5
- package/dist/plugin-files/dist/hooks/hook-daemon.js +11 -11
- package/dist/plugin-files/dist/hooks/post-tool-use-failure.js +2 -2
- package/dist/plugin-files/dist/hooks/post-tool-use.js +3 -3
- package/dist/plugin-files/dist/hooks/pre-compact.js +2 -2
- package/dist/plugin-files/dist/hooks/pre-tool-use.js +2 -2
- package/dist/plugin-files/dist/hooks/session-end.js +2 -2
- package/dist/plugin-files/dist/hooks/stop.js +2 -2
- package/dist/plugin-files/dist/hooks/user-prompt-submit.js +3 -2
- package/dist/plugin-files/dist/skills/devflow:react/SKILL.md +16 -3
- package/dist/plugin-files/hooks/session-start +0 -10
- package/dist/plugin-files/hooks/stop +3 -2
- package/dist/plugin-files/package.json +9 -8
- package/dist/plugin-files/skills/animation/SKILL.md +38 -0
- package/dist/plugin-files/skills/context/SKILL.md +63 -0
- package/dist/plugin-files/skills/css/SKILL.md +38 -0
- package/dist/plugin-files/skills/devflow/SKILL.md +20 -0
- package/dist/plugin-files/skills/docker/SKILL.md +42 -0
- package/dist/plugin-files/skills/doctor/SKILL.md +17 -0
- package/dist/plugin-files/skills/electron/SKILL.md +42 -0
- package/dist/plugin-files/skills/git/SKILL.md +42 -0
- package/dist/plugin-files/skills/graph/SKILL.md +55 -0
- package/dist/plugin-files/skills/graphql/SKILL.md +41 -0
- package/dist/plugin-files/skills/knowledge/SKILL.md +55 -0
- package/dist/plugin-files/skills/memory/SKILL.md +54 -0
- package/dist/plugin-files/skills/nest/SKILL.md +41 -0
- package/dist/plugin-files/skills/nextjs/SKILL.md +38 -0
- package/dist/plugin-files/skills/performance/SKILL.md +42 -0
- package/dist/plugin-files/skills/react/SKILL.md +63 -0
- package/dist/plugin-files/skills/start/SKILL.md +50 -0
- package/dist/plugin-files/skills/tailwind/SKILL.md +38 -0
- package/dist/plugin-files/skills/taro/SKILL.md +41 -0
- package/dist/plugin-files/skills/ui-layout/SKILL.md +38 -0
- package/dist/plugin-files/skills/vue/SKILL.md +45 -0
- package/dist/plugin-files/skills/workflow/SKILL.md +55 -0
- package/package.json +27 -27
- /package/dist/plugin-files/{hooks.json → hooks/hooks.json} +0 -0
package/dist/commands/server.js
CHANGED
|
@@ -77,7 +77,7 @@ export async function serverStatus() {
|
|
|
77
77
|
const pidFile = getPidFile(process.cwd());
|
|
78
78
|
const port = readPort(pidFile) ?? DEFAULT_SERVER_PORT;
|
|
79
79
|
const { DevFlowApiClient } = await import("@devflow-tools/sdk");
|
|
80
|
-
const client = new DevFlowApiClient({ baseUrl: `http://
|
|
80
|
+
const client = new DevFlowApiClient({ baseUrl: `http://127.0.0.1:${port}`, projectRoot: process.cwd() });
|
|
81
81
|
const reachable = await client.ping();
|
|
82
82
|
if (reachable) {
|
|
83
83
|
const pid = readPid(pidFile) ?? undefined;
|
package/dist/commands/start.js
CHANGED
|
@@ -4,7 +4,7 @@ async function waitForServer(port, timeoutMs = 15000) {
|
|
|
4
4
|
const start = Date.now();
|
|
5
5
|
while (Date.now() - start < timeoutMs) {
|
|
6
6
|
try {
|
|
7
|
-
const res = await fetch(`http://
|
|
7
|
+
const res = await fetch(`http://127.0.0.1:${port}/api/health`);
|
|
8
8
|
if (res.ok)
|
|
9
9
|
return true;
|
|
10
10
|
}
|
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
*/
|
|
5
5
|
export declare function getPluginFilesDir(): string;
|
|
6
6
|
/**
|
|
7
|
-
* Ensure the devflow plugin
|
|
8
|
-
*
|
|
7
|
+
* Ensure the devflow plugin and its local marketplace are configured in
|
|
8
|
+
* ~/.claude/settings.json. Existing unrelated settings are preserved.
|
|
9
9
|
*/
|
|
10
10
|
export declare function ensurePluginEnabled(settingsPath: string): void;
|
|
11
11
|
/**
|
|
@@ -15,9 +15,8 @@ export declare function ensurePluginEnabled(settingsPath: string): void;
|
|
|
15
15
|
*/
|
|
16
16
|
export declare function writeMcpConfig(projectRoot: string, mcpCommand: string): void;
|
|
17
17
|
/**
|
|
18
|
-
* Deploy plugin files
|
|
19
|
-
*
|
|
20
|
-
* Also copies dist/skills/ to ~/.claude/skills/ (Claude Code's actual skill load location).
|
|
18
|
+
* Deploy plugin files and register the installation with Claude Code.
|
|
19
|
+
* Global user skills are left untouched; Claude discovers skills from the plugin cache.
|
|
21
20
|
*/
|
|
22
|
-
export declare function deployPlugin(pluginFilesDir: string, cacheBaseDir: string, version: string,
|
|
21
|
+
export declare function deployPlugin(pluginFilesDir: string, cacheBaseDir: string, version: string, _globalSkillsDir?: string): void;
|
|
23
22
|
//# sourceMappingURL=plugin-setup.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-setup.d.ts","sourceRoot":"","sources":["../../src/lib/plugin-setup.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"plugin-setup.d.ts","sourceRoot":"","sources":["../../src/lib/plugin-setup.ts"],"names":[],"mappings":"AAkBA;;;GAGG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAoB1C;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAoC9D;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAsB5E;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAC1B,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,MAAM,EACf,gBAAgB,CAAC,EAAE,MAAM,GACxB,IAAI,CA0CN"}
|
package/dist/lib/plugin-setup.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, cpSync, readdirSync, statSync, rmSync, } from "node:fs";
|
|
2
|
-
import { join, dirname } from "node:path";
|
|
2
|
+
import { join, dirname, relative } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
3
4
|
import { execFileSync } from "node:child_process";
|
|
4
5
|
const PLUGIN_KEY = "devflow@devflow-local";
|
|
5
6
|
const MARKETPLACE = "devflow-local";
|
|
@@ -9,19 +10,27 @@ const PLUGIN_NAME = "devflow";
|
|
|
9
10
|
* Priority: bundled dist/plugin-files (npm) -> monorepo plugins/claude-code (dev)
|
|
10
11
|
*/
|
|
11
12
|
export function getPluginFilesDir() {
|
|
12
|
-
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
13
|
+
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
const candidates = [
|
|
15
|
+
// @devflow-tools/cli: dist/lib/plugin-setup.js -> dist/plugin-files
|
|
16
|
+
join(moduleDir, "..", "plugin-files"),
|
|
17
|
+
// @devflow-tools/devflow: bundled dist/cli.js -> dist/plugin
|
|
18
|
+
join(moduleDir, "plugin"),
|
|
19
|
+
// CLI source execution: src/lib/plugin-setup.ts -> dist/plugin-files
|
|
20
|
+
join(moduleDir, "..", "..", "dist", "plugin-files"),
|
|
21
|
+
// Monorepo fallback.
|
|
22
|
+
join(moduleDir, "..", "..", "..", "..", "plugins", "claude-code"),
|
|
23
|
+
];
|
|
24
|
+
for (const candidate of candidates) {
|
|
25
|
+
if (existsSync(join(candidate, ".claude-plugin", "plugin.json"))) {
|
|
26
|
+
return candidate;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
20
29
|
throw new Error("Plugin files not found. Run `npm run build` first.");
|
|
21
30
|
}
|
|
22
31
|
/**
|
|
23
|
-
* Ensure the devflow plugin
|
|
24
|
-
*
|
|
32
|
+
* Ensure the devflow plugin and its local marketplace are configured in
|
|
33
|
+
* ~/.claude/settings.json. Existing unrelated settings are preserved.
|
|
25
34
|
*/
|
|
26
35
|
export function ensurePluginEnabled(settingsPath) {
|
|
27
36
|
let settings = {};
|
|
@@ -37,12 +46,20 @@ export function ensurePluginEnabled(settingsPath) {
|
|
|
37
46
|
else {
|
|
38
47
|
mkdirSync(dirname(settingsPath), { recursive: true });
|
|
39
48
|
}
|
|
40
|
-
const enabledPlugins = settings.enabledPlugins
|
|
41
|
-
|
|
42
|
-
|
|
49
|
+
const enabledPlugins = isRecord(settings.enabledPlugins)
|
|
50
|
+
? settings.enabledPlugins
|
|
51
|
+
: {};
|
|
43
52
|
enabledPlugins[PLUGIN_KEY] = true;
|
|
44
53
|
settings.enabledPlugins = enabledPlugins;
|
|
45
|
-
|
|
54
|
+
const marketplaceRoot = join(dirname(settingsPath), "plugins", "marketplaces", MARKETPLACE);
|
|
55
|
+
const knownMarketplaces = isRecord(settings.extraKnownMarketplaces)
|
|
56
|
+
? settings.extraKnownMarketplaces
|
|
57
|
+
: {};
|
|
58
|
+
knownMarketplaces[MARKETPLACE] = {
|
|
59
|
+
source: { source: "directory", path: marketplaceRoot },
|
|
60
|
+
};
|
|
61
|
+
settings.extraKnownMarketplaces = knownMarketplaces;
|
|
62
|
+
writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
|
|
46
63
|
}
|
|
47
64
|
/**
|
|
48
65
|
* Write .claude/mcp.json for the project.
|
|
@@ -73,12 +90,12 @@ export function writeMcpConfig(projectRoot, mcpCommand) {
|
|
|
73
90
|
writeFileSync(mcpPath, JSON.stringify(existing, null, 2));
|
|
74
91
|
}
|
|
75
92
|
/**
|
|
76
|
-
* Deploy plugin files
|
|
77
|
-
*
|
|
78
|
-
* Also copies dist/skills/ to ~/.claude/skills/ (Claude Code's actual skill load location).
|
|
93
|
+
* Deploy plugin files and register the installation with Claude Code.
|
|
94
|
+
* Global user skills are left untouched; Claude discovers skills from the plugin cache.
|
|
79
95
|
*/
|
|
80
|
-
export function deployPlugin(pluginFilesDir, cacheBaseDir, version,
|
|
96
|
+
export function deployPlugin(pluginFilesDir, cacheBaseDir, version, _globalSkillsDir) {
|
|
81
97
|
const target = join(cacheBaseDir, MARKETPLACE, PLUGIN_NAME, version);
|
|
98
|
+
rmSync(target, { recursive: true, force: true });
|
|
82
99
|
mkdirSync(target, { recursive: true });
|
|
83
100
|
// Copy hooks/
|
|
84
101
|
const hooksSrc = join(pluginFilesDir, "hooks");
|
|
@@ -86,7 +103,7 @@ export function deployPlugin(pluginFilesDir, cacheBaseDir, version, globalSkills
|
|
|
86
103
|
copyDirSync(hooksSrc, join(target, "hooks"));
|
|
87
104
|
}
|
|
88
105
|
// Copy static files
|
|
89
|
-
for (const file of ["
|
|
106
|
+
for (const file of ["CLAUDE.md", "package.json"]) {
|
|
90
107
|
const src = join(pluginFilesDir, file);
|
|
91
108
|
if (existsSync(src))
|
|
92
109
|
cpSync(src, join(target, file), { force: true });
|
|
@@ -102,16 +119,104 @@ export function deployPlugin(pluginFilesDir, cacheBaseDir, version, globalSkills
|
|
|
102
119
|
if (existsSync(distSrc)) {
|
|
103
120
|
copyDirSync(distSrc, join(target, "dist"));
|
|
104
121
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
const skillsSrc = join(pluginFilesDir, "dist", "skills");
|
|
109
|
-
if (existsSync(skillsSrc)) {
|
|
110
|
-
copyDirSync(skillsSrc, globalSkillsDir);
|
|
111
|
-
}
|
|
122
|
+
const pluginSkillsSrc = join(pluginFilesDir, "skills");
|
|
123
|
+
if (existsSync(pluginSkillsSrc)) {
|
|
124
|
+
copyDirSync(pluginSkillsSrc, join(target, "skills"));
|
|
112
125
|
}
|
|
126
|
+
installRuntimeDependencies(target, pluginFilesDir);
|
|
113
127
|
// Clean old versions
|
|
114
128
|
cleanOldVersions(target);
|
|
129
|
+
registerLocalMarketplace(cacheBaseDir, target);
|
|
130
|
+
registerPluginInstallation(cacheBaseDir, target, version);
|
|
131
|
+
}
|
|
132
|
+
function registerLocalMarketplace(cacheBaseDir, installPath) {
|
|
133
|
+
const pluginsDir = join(cacheBaseDir, "..");
|
|
134
|
+
const marketplaceRoot = join(pluginsDir, "marketplaces", MARKETPLACE);
|
|
135
|
+
const marketplaceMetadataDir = join(marketplaceRoot, ".claude-plugin");
|
|
136
|
+
mkdirSync(marketplaceMetadataDir, { recursive: true });
|
|
137
|
+
let pluginSource = relative(marketplaceRoot, installPath).replaceAll("\\", "/");
|
|
138
|
+
if (!pluginSource.startsWith("."))
|
|
139
|
+
pluginSource = `./${pluginSource}`;
|
|
140
|
+
writeFileSync(join(marketplaceMetadataDir, "marketplace.json"), `${JSON.stringify({
|
|
141
|
+
name: MARKETPLACE,
|
|
142
|
+
description: "DevFlow local Claude Code plugin",
|
|
143
|
+
owner: { name: "DevFlow" },
|
|
144
|
+
plugins: [{ name: PLUGIN_NAME, source: pluginSource }],
|
|
145
|
+
}, null, 2)}\n`);
|
|
146
|
+
const registryPath = join(pluginsDir, "known_marketplaces.json");
|
|
147
|
+
let marketplaces = {};
|
|
148
|
+
if (existsSync(registryPath)) {
|
|
149
|
+
let parsed;
|
|
150
|
+
try {
|
|
151
|
+
parsed = JSON.parse(readFileSync(registryPath, "utf-8"));
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
throw new Error(`Could not parse Claude marketplace registry: ${registryPath}`);
|
|
155
|
+
}
|
|
156
|
+
if (!isRecord(parsed)) {
|
|
157
|
+
throw new Error(`Invalid Claude marketplace registry: ${registryPath}`);
|
|
158
|
+
}
|
|
159
|
+
marketplaces = parsed;
|
|
160
|
+
}
|
|
161
|
+
marketplaces[MARKETPLACE] = {
|
|
162
|
+
source: { source: "directory", path: marketplaceRoot },
|
|
163
|
+
installLocation: marketplaceRoot,
|
|
164
|
+
lastUpdated: new Date().toISOString(),
|
|
165
|
+
};
|
|
166
|
+
writeFileSync(registryPath, `${JSON.stringify(marketplaces, null, 2)}\n`);
|
|
167
|
+
}
|
|
168
|
+
function registerPluginInstallation(cacheBaseDir, installPath, version) {
|
|
169
|
+
const registryPath = join(cacheBaseDir, "..", "installed_plugins.json");
|
|
170
|
+
let registry = { version: 2, plugins: {} };
|
|
171
|
+
if (existsSync(registryPath)) {
|
|
172
|
+
let parsed;
|
|
173
|
+
try {
|
|
174
|
+
parsed = JSON.parse(readFileSync(registryPath, "utf-8"));
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
throw new Error(`Could not parse Claude plugin registry: ${registryPath}`);
|
|
178
|
+
}
|
|
179
|
+
if (!isRecord(parsed)) {
|
|
180
|
+
throw new Error(`Invalid Claude plugin registry: ${registryPath}`);
|
|
181
|
+
}
|
|
182
|
+
registry = parsed;
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
mkdirSync(dirname(registryPath), { recursive: true });
|
|
186
|
+
}
|
|
187
|
+
const pluginsValue = registry.plugins;
|
|
188
|
+
if (pluginsValue !== undefined && !isRecord(pluginsValue)) {
|
|
189
|
+
throw new Error(`Invalid Claude plugin registry plugins: ${registryPath}`);
|
|
190
|
+
}
|
|
191
|
+
const plugins = pluginsValue ?? {};
|
|
192
|
+
const existingValue = plugins[PLUGIN_KEY];
|
|
193
|
+
if (existingValue !== undefined && !Array.isArray(existingValue)) {
|
|
194
|
+
throw new Error(`Invalid Claude plugin registration for ${PLUGIN_KEY}`);
|
|
195
|
+
}
|
|
196
|
+
const existingEntries = existingValue ?? [];
|
|
197
|
+
const existingUserEntry = existingEntries.find((entry) => isRecord(entry) && entry.scope === "user");
|
|
198
|
+
const now = new Date().toISOString();
|
|
199
|
+
const installedAt = isRecord(existingUserEntry)
|
|
200
|
+
&& typeof existingUserEntry.installedAt === "string"
|
|
201
|
+
? existingUserEntry.installedAt
|
|
202
|
+
: now;
|
|
203
|
+
const otherScopeEntries = existingEntries.filter((entry) => !isRecord(entry) || entry.scope !== "user");
|
|
204
|
+
plugins[PLUGIN_KEY] = [
|
|
205
|
+
...otherScopeEntries,
|
|
206
|
+
{
|
|
207
|
+
scope: "user",
|
|
208
|
+
installPath,
|
|
209
|
+
version,
|
|
210
|
+
installedAt,
|
|
211
|
+
lastUpdated: now,
|
|
212
|
+
},
|
|
213
|
+
];
|
|
214
|
+
registry.version = 2;
|
|
215
|
+
registry.plugins = plugins;
|
|
216
|
+
writeFileSync(registryPath, `${JSON.stringify(registry, null, 2)}\n`);
|
|
217
|
+
}
|
|
218
|
+
function isRecord(value) {
|
|
219
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
115
220
|
}
|
|
116
221
|
function installRuntimeDependencies(target, pluginFilesDir) {
|
|
117
222
|
const packagePath = join(target, "package.json");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-setup.js","sourceRoot":"","sources":["../../src/lib/plugin-setup.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,SAAS,EACT,YAAY,EACZ,aAAa,EACb,MAAM,EACN,WAAW,EACX,QAAQ,EACR,MAAM,GACP,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,MAAM,UAAU,GAAG,uBAAuB,CAAC;AAC3C,MAAM,WAAW,GAAG,eAAe,CAAC;AACpC,MAAM,WAAW,GAAG,SAAS,CAAC;AAE9B;;;GAGG;AACH,MAAM,UAAU,iBAAiB;IAC/B,mEAAmE;IACnE,MAAM,OAAO,GAAG,IAAI,CAClB,OAAO,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAA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EAAE,KAAK,CAAC,CAAC;QACnC,IAAI,QAAQ,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC;YACpC,WAAW,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACjC,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,OAAO,EAAE,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAC7C,CAAC;IACH,CAAC;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,aAAqB;IAC7C,MAAM,SAAS,GAAG,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;IAC5C,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC;QAAE,OAAO;IACnC,MAAM,cAAc,GAAG,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC;IAC5D,KAAK,MAAM,KAAK,IAAI,WAAW,CAAC,SAAS,CAAC,EAAE,CAAC;QAC3C,IAAI,KAAK,KAAK,cAAc,EAAE,CAAC;YAC7B,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;YACzC,IAAI,QAAQ,CAAC,SAAS,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC;gBACtC,MAAM,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YACtD,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC"}
|
package/dist/lib/with-server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import chalk from "chalk";
|
|
2
2
|
import { DevFlowApiClient } from "@devflow-tools/sdk";
|
|
3
|
-
const DEFAULT_SERVER_URL = process.env.DEVFLOW_SERVER_URL ?? "http://
|
|
3
|
+
const DEFAULT_SERVER_URL = process.env.DEVFLOW_SERVER_URL ?? "http://127.0.0.1:13337";
|
|
4
4
|
const pingCache = new Map();
|
|
5
5
|
const PING_TTL_MS = 30_000;
|
|
6
6
|
export async function withServer(projectRoot, serverFn, localFn, opts = {}) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "devflow",
|
|
3
3
|
"description": "DevFlow \u2014 Developer Intelligence Platform: project context, code graph, knowledge base, memory engine, and workflow automation with 14 domain plugins",
|
|
4
|
-
"version": "0.16.
|
|
4
|
+
"version": "0.16.2",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "DevFlow"
|
|
7
7
|
},
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {createConnection}from'node:net';import {getDaemonSocketPath}from'@devflow-tools/sdk';import {mkdirSync,appendFileSync}from'node:fs';import {homedir}from'node:os';import {join,dirname}from'node:path';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';function d(e,o,t){try{let r=openGlobalDevFlowDatabase();try{r.insertEvent({kind:e,timestamp:Date.now(),duration:t,success:o.success!==!1,metadata:o});}finally{r.close();}}catch{}}var E=["4-Gate enforcement","memory prefetch cache","daemon-shared hook state"];function
|
|
2
|
-
`,{mode:384});}catch{}}function R(e){try{let o=JSON.parse(e);return typeof o.tool_name=="string"&&o.tool_name?o.tool_name:null}catch{return null}}var i=process.env.CLAUDE_PROJECT_DIR||process.cwd(),v=getDaemonSocketPath(i),n=process.argv[2],S=process.argv[3],m=Number(process.env.DEVFLOW_HOOK_CLIENT_TIMEOUT_MS),N=Number.isFinite(m)&&m>0?m:4e3,l=Number(process.env.DEVFLOW_HOOK_CLIENT_RETRY_DELAY_MS),k=Number.isFinite(l)&&l>=0?l:1e3;async function q(){let e=n==="
|
|
3
|
-
`),0;t===0&&await A(k);}return process.env.DEVFLOW_HOOK_CLIENT_SUPPRESS_FALLBACK_LOG!=="1"&&
|
|
1
|
+
import {createConnection}from'node:net';import {getDaemonSocketPath}from'@devflow-tools/sdk';import {mkdirSync,appendFileSync}from'node:fs';import {homedir}from'node:os';import {join,dirname}from'node:path';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';function d(e,o,t){try{let r=openGlobalDevFlowDatabase();try{r.insertEvent({kind:e,timestamp:Date.now(),duration:t,success:o.success!==!1,metadata:o});}finally{r.close();}}catch{}}var E=["4-Gate enforcement","memory prefetch cache","daemon-shared hook state"];function u(e){let o=R(e.input)??e.requestType;if(d("hook_daemon_request",{success:e.success,projectRoot:e.projectRoot,requestType:e.requestType,tool:o,attempts:e.attempts},e.durationMs),!e.success)try{let t=Date.now(),r=join(homedir(),".devflow","logs","hook-fallback",`${new Date(t).toISOString().slice(0,10)}.log`);mkdirSync(dirname(r),{recursive:!0,mode:448}),appendFileSync(r,`${JSON.stringify({ts:t,tool:o,requestType:e.requestType,projectRoot:e.projectRoot,reason:"daemon-unreachable",durationMs:e.durationMs,attempts:e.attempts,bypassCountLost:!0,disabledFeatures:E})}
|
|
2
|
+
`,{mode:384});}catch{}}function R(e){try{let o=JSON.parse(e);return typeof o.tool_name=="string"&&o.tool_name?o.tool_name:null}catch{return null}}var i=process.env.CLAUDE_PROJECT_DIR||process.cwd(),v=getDaemonSocketPath(i),n=process.argv[2],S=process.argv[3],m=Number(process.env.DEVFLOW_HOOK_CLIENT_TIMEOUT_MS),N=Number.isFinite(m)&&m>0?m:4e3,l=Number(process.env.DEVFLOW_HOOK_CLIENT_RETRY_DELAY_MS),k=Number.isFinite(l)&&l>=0?l:1e3;async function q(){let e=S??(n==="memory-snapshot"?"":await P()),o=Date.now();for(let t=0;t<2;t+=1){let r=await L(e);if(r!==null)return u({projectRoot:i,requestType:n,input:e,durationMs:Date.now()-o,success:true,attempts:t+1}),process.stdout.write(`${r}
|
|
3
|
+
`),0;t===0&&await A(k);}return process.env.DEVFLOW_HOOK_CLIENT_SUPPRESS_FALLBACK_LOG!=="1"&&u({projectRoot:i,requestType:n,input:e,durationMs:Date.now()-o,success:false,attempts:2}),1}function L(e){return new Promise(o=>{let t=createConnection(v),r=false,a="",c=s=>{r||(r=true,clearTimeout(f),t.destroy(),o(s));},f=setTimeout(()=>c(null),N);t.setEncoding("utf8"),t.on("connect",()=>{t.write(`${JSON.stringify({type:"hello",rootPath:i})}
|
|
4
4
|
`);let s=M(e);if(!s){c(null);return}t.write(`${JSON.stringify(s)}
|
|
5
|
-
`);}),t.on("data",s=>{
|
|
6
|
-
`);if(p<0)return;let g=
|
|
5
|
+
`);}),t.on("data",s=>{a+=s;let p=a.indexOf(`
|
|
6
|
+
`);if(p<0)return;let g=a.slice(0,p).trim();c(g||null);}),t.on("error",()=>c(null)),t.on("close",()=>c(null));})}function M(e){return n==="stop"?{type:"stop",input:e}:n==="memory-snapshot"?{type:"memory-snapshot"}:["session-start","session-end","post-tool-use","post-tool-use-failure","pre-tool-use","user-prompt-submit","pre-compact"].includes(n)?{type:n,input:e}:null}function P(){return new Promise(e=>{let o="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{o+=t;}),process.stdin.on("end",()=>e(o)),process.stdin.on("error",()=>e(""));})}function A(e){return new Promise(o=>setTimeout(o,e))}q().then(e=>process.exit(e)).catch(()=>process.exit(1));
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import {createServer,createConnection}from'net';import {join,dirname}from'path';import {existsSync,readFileSync,mkdirSync,lstatSync,openSync,writeFileSync,fstatSync,closeSync,unlinkSync,readdirSync,appendFileSync as appendFileSync$1}from'fs';import {getLocalApiKey,getDaemonSocketPath,getDaemonPidPath,loadConfig,getProjectStateDir,getDaemonRegistryPath,getProjectHash}from'@devflow-tools/sdk';import {request}from'http';import {homedir}from'os';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {fileURLToPath}from'url';import {spawn}from'child_process';import {mkdirSync as mkdirSync$1,appendFileSync,readdirSync as readdirSync$1,renameSync,unlinkSync as unlinkSync$1,writeFileSync as writeFileSync$1,readFileSync as readFileSync$1,openSync as openSync$1,closeSync as closeSync$1,rmSync,statSync,existsSync as existsSync$1}from'node:fs';import {dirname as dirname$1,basename,join as join$1}from'node:path';import {createHash}from'crypto';import {MemoryGate}from'@devflow-tools/memory-engine';import {createHash as createHash$1}from'node:crypto';import {homedir as homedir$1}from'node:os';var de=1e4,at=3e4,M=500;function ct(r,e,t){return new Promise(n=>{try{let o=new URL(r),s=request({hostname:o.hostname,port:o.port||80,path:o.pathname+o.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":t,"Content-Length":Buffer.byteLength(e)},timeout:5e3},i=>{let c=[];i.on("data",a=>c.push(a)),i.on("end",()=>{let a=Buffer.concat(c).toString();n(i.statusCode!=null&&i.statusCode>=200&&i.statusCode<300?a:null);});});s.on("error",()=>n(null)),s.on("timeout",()=>{s.destroy(),n(null);}),s.write(e),s.end();}catch{n(null);}})}var R=class{constructor(e){this.retryScheduled=false;this.apiUrl=e?.apiUrl??process.env.DEVFLOW_API_URL??"http://127.0.0.1:13337",this.apiKey=e?.apiKey??getLocalApiKey(),this.cacheDir=e?.cacheDir??join(process.env.DEVFLOW_STATE_DIR??join(homedir(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=e?.legacyCacheDir??(e?.cacheDir?null:join(homedir(),".devflow","telemetry-cache")),this.database=e?.database??null,this.ownsDatabase=!e?.database;}async sendEvent(e){let t={...e,input:this.truncateInput(e.input)};return this.commitOrCache("tool_call",t)?(this.postHttp("/api/telemetry/tool-call",t),e.eventId):null}async sendExecutionStart(e,t,n,o){let s={executionId:e,sessionId:t,skillName:n,startedAt:o};this.commitOrCache("execution_start",s)&&this.postHttp("/api/telemetry/skill-execution/start",s);}async sendSessionStart(e,t,n){let o={id:e,projectRoot:t,startedAt:n,label:t.split("/").pop()??"unknown"},s=this.commitOrCache("session_start",o);return s&&this.postHttp("/api/telemetry/sessions",o),s}async completeEvent(e){let t=this.commitOrCache("complete_event",e);return t&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp("/api/telemetry/tool-call/output",e)),t}async endSession(e,t=Date.now()){let n={sessionId:e,finishedAt:t},o=this.commitOrCache("session_end",n);return o&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(e)}/close`,{finishedAt:t})),o}async flushCache(){try{let n=this.getDatabase(),o=n.listTelemetryFailures({unresolvedOnly:!0,limit:M}).reverse();for(let s of o)try{this.applyOperation(s.operation,s.payload),n.resolveTelemetryFailure(s.id);}catch{}n.trimTelemetryFailures(M);}catch{}let t=[...new Set([this.cacheDir,this.legacyCacheDir].filter(n=>!!n))].filter(n=>existsSync(n)).flatMap(n=>readdirSync(n).filter(o=>o.endsWith(".json")).map(o=>{let s=join(n,o);try{return {cacheFile:s,envelope:lt(JSON.parse(readFileSync(s,"utf8")),o)}}catch{return null}})).filter(n=>n!==null).sort((n,o)=>n.envelope.timestamp-o.envelope.timestamp||me(n.envelope.operation)-me(o.envelope.operation));for(let{cacheFile:n,envelope:o}of t)try{let s=this.getDatabase();s.insertTelemetryFailure({id:o.id,operation:o.operation,payload:o.payload,error:o.failure,createdAt:o.timestamp}),this.applyOperation(o.operation,o.payload),s.resolveTelemetryFailure(o.id),unlinkSync(n);}catch{}this.database?.aggregatePendingToolMetrics();}aggregateMetrics(){return this.getDatabase().aggregatePendingToolMetrics()}async flushAndAggregate(){await this.flushCache(),this.aggregateMetrics();}close(){this.ownsDatabase&&this.database?.close(),this.database=null;}getDatabase(){return this.database??=openGlobalDevFlowDatabase(),this.database}commitOrCache(e,t){try{return this.applyOperation(e,t),!0}catch(n){return this.cacheOperation(e,t,n),false}}applyOperation(e,t){let n=this.getDatabase();switch(e){case "tool_call":n.insertToolCallEvent(t);return;case "execution_start":n.insertSkillExecution({executionId:t.executionId,sessionId:t.sessionId,skillName:t.skillName,startedAt:t.startedAt,status:"running"});return;case "session_start":n.insertSession(t),n.insertRun({id:he(t.id),source:"hook",tool:"session",input:{projectRoot:t.projectRoot},status:"active",startedAt:t.startedAt,tokenUsed:0,metadata:{sessionId:t.id,projectRoot:t.projectRoot}});return;case "complete_event":if(!n.updateToolCallEvent(t.eventId,{output:t.output===void 0?void 0:JSON.stringify(t.output),error:t.error,duration:t.duration}))throw new Error(`Tool call event ${t.eventId} is not available for completion`);return;case "session_end":n.closeSession(t.sessionId,t.finishedAt),n.updateRun(he(t.sessionId),{status:"completed",finishedAt:t.finishedAt});return}}cacheOperation(e,t,n){let o=Date.now(),s={id:`failure:${o}:${Math.random().toString(36).slice(2,11)}`,operation:e,payload:t,failure:n instanceof Error?n.message:String(n),timestamp:o};try{let i=this.getDatabase();i.insertTelemetryFailure({id:s.id,operation:e,payload:t,error:s.failure,createdAt:o}),i.trimTelemetryFailures(M),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let i=join(this.cacheDir,`${o}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(i,JSON.stringify(s,null,2),{mode:384}),this.trimCompatibilityCache(),this.scheduleRetry();}catch{}}trimCompatibilityCache(){try{let e=readdirSync(this.cacheDir).filter(t=>t.endsWith(".json")).sort();for(let t of e.slice(0,Math.max(0,e.length-M)))unlinkSync(join(this.cacheDir,t));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},at).unref());}postHttp(e,t){ct(`${this.apiUrl}${e}`,JSON.stringify(t),this.apiKey);}truncateInput(e){let t=JSON.stringify(e);return t===void 0||t.length<=de?e:{_truncated:true,_original_size:t.length,_preview:`${t.substring(0,de)}...`}}};function me(r){return ["session_start","execution_start","tool_call","complete_event","session_end"].indexOf(r)}function he(r){return `hook-run:${r}`}function lt(r,e){if(!r||typeof r!="object")throw new Error("Invalid telemetry cache envelope");let t=r;if(typeof t.operation=="string"&&t.payload!==void 0)return t;let n=t.type==="tool_call"?"tool_call":t.type==="execution_start"?"execution_start":null;if(!n)throw new Error("Unknown legacy telemetry cache operation");let o=t.payload??{},s=Number(o.timestamp??o.startedAt??Date.now());return {id:`legacy-cache:${e}`,operation:n,payload:o,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:s}}function J(r){return r??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function S(r){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(J(r))}var ft=1;function yt(){if(process.env.CLAUDE_PLUGIN_ROOT)return process.env.CLAUDE_PLUGIN_ROOT;try{return join(dirname(fileURLToPath(import.meta.url)),"..","..")}catch{return process.cwd()}}function ye(r=yt()){let e=[join(r,"dist","command-registry.json"),join(r,"command-registry.json")];for(let t of e)try{if(!existsSync(t))continue;let n=JSON.parse(readFileSync(t,"utf8"));if(n.version!==ft||!gt(n.commands)){console.error(`[devflow] command registry contract mismatch: ${t}`);continue}return n.commands}catch(n){console.error(`[devflow] command registry load failed: ${n.message}`);}return null}function gt(r){return !r||typeof r!="object"||Array.isArray(r)?false:Object.values(r).every(e=>{if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return fe(t.mcpTools)&&fe(t.blockedNative)})}function fe(r){return Array.isArray(r)&&r.every(e=>typeof e=="string"&&e.length>0)}var wt=1800*1e3,St=300*1e3;function W(r){let e=ye();return e?e[r]?.mcpTools??[]:[]}var C=class{constructor(e){this.stateDir=S(e);}detect(){let e=join(this.stateDir,"current-skill.json");if(!existsSync(e))return null;try{let t=readFileSync(e,"utf8"),n=JSON.parse(t);return !n.registeredAt||Date.now()-n.registeredAt>wt?(this.endExecution(),null):(Date.now()-n.registeredAt>St&&(n.registeredAt=Date.now(),writeFileSync(e,JSON.stringify(n))),n)}catch{return null}}startExecution(e,t){existsSync(this.stateDir)||mkdirSync(this.stateDir,{recursive:true});let n=this.getCurrentExecutionId();if(n)return n;let o=`exec_${Date.now()}_${Math.random().toString(36).slice(2,11)}`;return writeFileSync(join(this.stateDir,"current-execution-id"),o),writeFileSync(join(this.stateDir,"current-skill.json"),JSON.stringify({name:e,required_mcp_tools:t?.required_mcp_tools??[],registeredAt:Date.now()})),o}getCurrentExecutionId(){let e=join(this.stateDir,"current-execution-id");if(!existsSync(e))return null;try{return readFileSync(e,"utf8").trim()}catch{return null}}endExecution(){let e=join(this.stateDir,"current-skill.json"),t=join(this.stateDir,"current-execution-id");try{existsSync(e)&&unlinkSync(e);}catch{}try{existsSync(t)&&unlinkSync(t);}catch{}}};var B=join(homedir(),".devflow"),K=join(B,"server-refs.json"),It="http://127.0.0.1:13337/api/health",Dt=600*1e3,Mt=500;function Ct(){existsSync(B)||mkdirSync(B,{recursive:true});}function P(){try{if(existsSync(K))return JSON.parse(readFileSync(K,"utf-8"))}catch{}return {sessions:[],lastActivity:0}}function we(r){Ct(),writeFileSync(K,JSON.stringify(r));}var O=class{constructor(e){this.process=null;this.idleTimer=null;this.onShutdown=null;this.projectRoot=e;}setOnShutdown(e){this.onShutdown=e;}addRef(e){let t=P();t.sessions.includes(e)||t.sessions.push(e),t.lastActivity=Date.now(),we(t),this.resetIdleTimer();}removeRef(e){let t=P();t.sessions=t.sessions.filter(n=>n!==e),t.lastActivity=Date.now(),we(t),t.sessions.length===0&&this.resetIdleTimer();}get activeSessions(){return P().sessions.length}async ensureRunning(){return await this.healthCheck()?true:(await this.startServer(),this.waitForReady())}get isRunning(){return this.process!==null&&!this.process.killed}async stop(){this.idleTimer&&clearTimeout(this.idleTimer),this.process&&(this.process.kill("SIGTERM"),await new Promise(e=>{let t=setTimeout(()=>{this.process&&!this.process.killed&&this.process.kill("SIGKILL"),e();},5e3);this.process?this.process.on("exit",()=>{clearTimeout(t),e();}):(clearTimeout(t),e());}),this.process=null);}async startServer(){let e=join(this.projectRoot,"apps","server","dist","main.js"),t=join(this.projectRoot,"node_modules","@devflow-tools","server","dist","main.js"),n=existsSync(e)?e:t;this.process=spawn("node",[n],{cwd:this.projectRoot,env:{...process.env,NODE_ENV:process.env.NODE_ENV||"development"},stdio:["ignore","pipe","pipe"]}),this.process.stdout?.on("data",o=>{}),this.process.stderr?.on("data",o=>{}),this.process.on("exit",o=>{this.process=null,this.onShutdown&&this.onShutdown();}),this.process.on("error",()=>{this.process=null;});}async waitForReady(){let e=Date.now()+3e4;for(;Date.now()<e;){if(await this.healthCheck())return true;await new Promise(t=>setTimeout(t,Mt));}return false}healthCheck(){return new Promise(e=>{let t=new URL(It),n=request({hostname:t.hostname,port:t.port,path:t.pathname,method:"GET",timeout:2e3},o=>{e(o.statusCode===200);});n.on("error",()=>e(false)),n.on("timeout",()=>{n.destroy(),e(false);}),n.end();})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),!(P().sessions.length>0)&&(this.idleTimer=setTimeout(()=>{this.stop();},Dt).unref());}};function Se(r,e,t){try{let n=openGlobalDevFlowDatabase();try{n.insertEvent({kind:r,timestamp:Date.now(),duration:t,success:e.success!==!1,metadata:e});}finally{n.close();}}catch{}}var X=process.env.DEVFLOW_SERVER_URL||"http://127.0.0.1:13337",Lt=getLocalApiKey(),Ut=8,$t=6e4,_e=new Map;function qt(r){let e=new URL(r,X).pathname,t=_e.get(e);return t||(t={failures:0,lastFailure:0,openUntil:0,status:"closed"},_e.set(e,t)),t}function Q(r,e,t){if(e.status===t)return;let n=e.status;e.status=t,Se("http_circuit_transition",{path:new URL(r,X).pathname,previous:n,status:t,failures:e.failures,openUntil:e.openUntil});}function z(r,e){e.failures++,e.lastFailure=Date.now(),e.failures>=Ut&&(e.openUntil=Date.now()+$t,Q(r,e,"open"));}function Jt(r,e){let t=e.status!=="closed";e.failures=0,e.openUntil=0,t&&Q(r,e,"closed");}var Y=join(homedir(),".devflow","errors");function Ee(r,e){try{existsSync(Y)||mkdirSync(Y,{recursive:!0});let t=`${new Date().toISOString()} | ${r} | ${e?.message??String(e)}
|
|
2
|
-
`;appendFileSync$1(join(Y,"http-errors.log"),t);}catch{}}function Re(r,e,t={}){let n=t.timeout??5e3,o=t.maxRetries??2,s=t.circuitBreaker??true,i=qt(r);if(s&&i.openUntil>Date.now())return Promise.resolve();s&&i.status==="open"&&Q(r,i,"half_open");let c=a=>new Promise(d=>{let l=JSON.stringify(e),f=new URL(r,X),h=request({hostname:f.hostname,port:f.port,path:f.pathname+f.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":Lt,"Content-Length":Buffer.byteLength(l)},timeout:n},u=>{if(u.resume(),u.statusCode&&u.statusCode>=400){let p=new Error(`HTTP ${u.statusCode}`);if(Ee(r,p),a>0){let m=Math.min(1e3*Math.pow(2,o-a),8e3);setTimeout(()=>{c(a-1).then(d);},m);}else z(r,i),d();return}Jt(r,i),d();});h.on("error",u=>{if(Ee(r,u),a>0){let p=Math.min(1e3*Math.pow(2,o-a),8e3);setTimeout(()=>{c(a-1).then(d);},p);}else z(r,i),d();}),h.on("timeout",()=>{h.destroy(),a>0?c(a-1).then(d):(z(r,i),d());}),h.write(l),h.end();});return c(o)}function I(r){if(!r||typeof r!="object"||Array.isArray(r))return {};let e=r,t={};for(let n of ["lastMcpCall","bypassCount"])if(n in e){let o=e[n];if(o==null)continue;t[n]=typeof o=="number"&&Number.isFinite(o)&&o>=0?o:0;}return t}function Ht(r,e){return r.lastMcpCall===e.lastMcpCall&&r.bypassCount===e.bypassCount}function Wt(r){try{return existsSync(r)?I(JSON.parse(readFileSync(r,"utf-8"))):{}}catch{return {}}}function De(r,e){let t=e instanceof Error?e.message:String(e);console.error(`[devflow] Receipt ${r} skipped: ${t}`);}function Te(r){let e=S(r);for(let t of ["receipt.json","receipt-lock.sqlite","receipt-lock.sqlite-shm","receipt-lock.sqlite-wal"])try{existsSync(join(e,t))&&unlinkSync(join(e,t));}catch{}}function Me(r,e){if(r.getHookReceipt(e)){Te(e);return}let t=join(S(e),"receipt.json");if(!existsSync(t))return;let n=Wt(t);r.updateHookReceipt(e,()=>n),Te(e);}function Ce(r,e,t){let n;try{n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),Me(n,r);let o={},s=n.updateHookReceipt(r,c=>(o=I(c),I(e(o)))),i=I(s);return {receipt:i,applied:!0,changed:!Ht(o,i)}}catch(o){return De(t,o),{receipt:{},applied:false,changed:false}}finally{try{n?.close();}catch{}}}function Bt(r){let e;try{return e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),Me(e,r),I(e.getHookReceipt(r))}catch(t){return De("update",t),{}}finally{try{e?.close();}catch{}}}function F(r,e){return Ce(r,()=>e,"write").applied}function Z(r,e){return Ce(r,e,"update")}var Kt={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function Vt(r){switch(r){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var D=class{constructor(e){this.projectRoot=e;}getPhase(){let t=Bt(this.projectRoot).lastMcpCall??0;if(Math.floor(Date.now()/1e3)-t<30)return "context_ready";let o=join(S(this.projectRoot),"current-skill.json");if(existsSync(o))try{let c=JSON.parse(readFileSync(o,"utf-8")).registeredAt??0;if(Date.now()-c<300*1e3)return "context_gathering"}catch{}return "idle"}evaluate(e,t){let n=this.getPhase();if(t||e==="Skill")return {permissionDecision:"allow"};if(n==="context_gathering")return {permissionDecision:"deny",reason:"DevFlow skill requires MCP context first. The context is being gathered automatically \u2014 retry this tool after the MCP call completes."};if(n==="context_ready")return {permissionDecision:"allow"};let o=Kt[e];if(!o)return {permissionDecision:"allow"};let s=Z(this.projectRoot,a=>({...a,bypassCount:(a.bypassCount??0)+1}));if(!s.applied)return {permissionDecision:"allow"};let i=s.receipt.bypassCount??0,c=Vt(e);return i>=c?{permissionDecision:"allow",additionalContext:`\u5DF2 ${i} \u6B21\u76F4\u63A5\u4F7F\u7528 ${e}\uFF0C\u5EFA\u8BAE\u7528 mcp__devflow__${o} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){F(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}};var en=10,tn=5e3,nn=3e4,rn=new Int32Array(new SharedArrayBuffer(4)),Fe=0;function on(r){if(typeof r!="object"||r===null)return false;let e=r;return typeof e.rootPath=="string"&&e.rootPath.length>0&&typeof e.projectHash=="string"&&e.projectHash.length>0&&typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.startedAt=="number"&&Number.isFinite(e.startedAt)&&e.startedAt>=0}function Ne(r){if(!existsSync$1(r))return {entries:[],needsRepair:false};try{let e=JSON.parse(readFileSync$1(r,"utf8"));if(!Array.isArray(e))return {entries:[],needsRepair:!0};let t=e.filter(on);return {entries:t,needsRepair:t.length!==e.length}}catch{return {entries:[],needsRepair:true}}}function Le(r,e){mkdirSync$1(dirname$1(r),{recursive:true});let t=`${r}.${process.pid}.${Date.now()}.${Fe++}.tmp`,n;try{n=openSync$1(t,"wx"),writeFileSync$1(n,JSON.stringify(e,null,2)),closeSync$1(n),n=void 0,renameSync(t,r);}finally{try{n!==void 0&&closeSync$1(n);}finally{rmSync(t,{force:true});}}}function Ue(r){try{return process.kill(r,0),!0}catch(e){return e.code!=="ESRCH"}}function $e(r){if(typeof r!="object"||r===null)return false;let e=r;return typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)&&typeof e.token=="string"&&e.token.length>0}function Pe(r,e){try{return readFileSync$1(r,"utf8")!==e?!1:(rmSync(r),!0)}catch(t){return t.code==="ENOENT"}}function sn(r){try{let e=readFileSync$1(r,"utf8"),t;try{let o=JSON.parse(e);$e(o)&&(t=o);}catch{}return t?Ue(t.pid)?!1:Pe(r,e):Date.now()-statSync(r).mtimeMs>nn&&Pe(r,e)}catch(e){return e.code==="ENOENT"}}function an(r){mkdirSync$1(dirname$1(r),{recursive:true});let e=`${r}.lock`,t=Date.now()+tn;for(;;){let n=`${process.pid}:${Date.now()}:${Fe++}`,o;try{return o=openSync$1(e,"wx"),writeFileSync$1(o,JSON.stringify({pid:process.pid,createdAt:Date.now(),token:n})),closeSync$1(o),o=void 0,{path:e,token:n}}catch(s){if(o!==void 0)try{closeSync$1(o);}finally{rmSync(e,{force:true});}if(s.code!=="EEXIST")throw s}if(!sn(e)){if(Date.now()>=t)throw new Error(`Timed out acquiring daemon registry lock: ${e}`);Atomics.wait(rn,0,0,en);}}}function cn(r){try{let e=readFileSync$1(r.path,"utf8"),t=JSON.parse(e);$e(t)&&t.token===r.token&&rmSync(r.path);}catch(e){if(e.code!=="ENOENT")throw e}}function qe(r){let e=getDaemonRegistryPath(),t=an(e);try{return r(e)}finally{cn(t);}}function Je(r,e){qe(t=>{let n=Ne(t).entries.filter(o=>o.rootPath!==r&&Ue(o.pid));n.push({rootPath:r,projectHash:getProjectHash(r),pid:e,startedAt:Date.now()}),Le(t,n);});}function Ge(r,e){qe(t=>{let n=Ne(t).entries.filter(o=>o.rootPath!==r||e!==void 0&&o.pid!==e);Le(t,n);});}async function $(r){let e=!r.memory,t=r.memory??new MemoryGate(r.projectRoot),n=0,o=0;try{await t.forceWarmUp(),r.trigger==="session_end"&&(n=await t.releasePendingDistillLeases(r.sessionId)),o=t.getPendingEventCount();}finally{e&&t.close();}let s={pendingEvents:o,releasedLeases:n,trigger:r.trigger,sessionId:r.sessionId};try{let i=openGlobalDevFlowDatabase();try{let c=Date.now(),a=`distill:${c}:${Math.random().toString(36).slice(2,10)}`;i.recordMemoryDistillCheckpoint({id:a,projectRoot:r.projectRoot,sessionId:r.sessionId,trigger:r.trigger,pendingEvents:o,releasedLeases:n,createdAt:c}),i.insertEvent({kind:"memory_distill_requested",timestamp:c,success:!0,metadata:{...s,projectRoot:r.projectRoot}});}finally{i.close();}}catch{}return s}function He(r){if(r.pendingEvents===0)return "";let e=r.sessionId?`\uFF0CsessionId=${r.sessionId}`:"";return `Memory distill checkpoint: ${r.pendingEvents} \u4E2A\u4E8B\u4EF6\u5F85\u63D0\u70BC${e}\u3002\u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210\u540E\uFF0C\u8C03\u7528 mcp__devflow__memory_request_distill\uFF1B\u6309\u8FD4\u56DE prompt \u63D0\u70BC observations\uFF0C\u518D\u8C03\u7528 mcp__devflow__memory_save_distilled\u3002`}var yn=process.env.DEVFLOW_SERVER_URL||"http://127.0.0.1:13337",gn=getLocalApiKey();function vn(r,e){return new Promise(t=>{let n=JSON.stringify(e),o=new URL(r,yn),s=request({hostname:o.hostname,port:o.port,path:o.pathname,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":gn,"Content-Length":Buffer.byteLength(n)},timeout:5e3},()=>t());s.on("error",()=>t()),s.write(n),s.end();})}function te(r){let e=S(r),t=createHash("sha256").update(r).digest("hex").slice(0,12);return [join(e,`session-id-${t}`),join(e,"current-execution-id"),join(e,"current-skill.json"),join(e,"event-map.json")]}function wn(r){try{let e=te(r)[0];if(existsSync(e))return readFileSync(e,"utf-8").trim()}catch{}return null}function Sn(r){for(let e of te(r))try{existsSync(e)&&unlinkSync(e);}catch{}}async function ne(r,e=J(),t=true,n){let o;try{o=JSON.parse(r);}catch{return}let s=o.session_id||wn(e);if(!s)return;let i=n?.telemetry??new R,c=!n?.telemetry;try{try{await i.flushAndAggregate();}catch{}let a;try{a=openGlobalDevFlowDatabase();let d=a.listToolCallEventsBySession(s),l=te(e)[1];if(t&&existsSync(l)){let f="";try{f=readFileSync(l,"utf-8").trim();}catch{}if(f){let h=d.filter(w=>w.executionId===f),u=h.length,p=h.filter(w=>w.isMcpTool).length,m=u-p,g=h.filter(w=>w.toolType==="subagent").length,y=h.map(w=>w.timestamp).filter(Boolean),_=y.length>=2?Math.max(...y)-Math.min(...y):0;try{a.updateSkillExecution(f,{status:"completed",finishedAt:Date.now(),totalToolCalls:u,mcpToolCalls:p,directToolCalls:m,subagentCount:g,totalDuration:_,mcpComplianceRate:u>0?Math.round(p/u*1e4)/100:0}),await vn("/api/telemetry/skill-execution/complete",{executionId:f,finishedAt:Date.now(),status:"completed",summary:{totalToolCalls:u,mcpToolCalls:p,directToolCalls:m,subagentCount:g,totalDuration:_,mcpComplianceRate:u>0?Math.round(p/u*1e4)/100:0}});}catch{}}}t&&a.deleteHookReceipt(e);}catch{}finally{a?.close();}try{await $({projectRoot:e,sessionId:s,trigger:"session_end",memory:n?.memory});}catch{}try{await i.endSession(s),await i.flushAndAggregate();}catch{}}finally{c&&i.close(),t&&Sn(e);}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let r="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{r+=e;}),process.stdin.on("end",async()=>{await ne(r.trim()||process.argv[2]||""),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var Mn=/(?:^|[.!?。!?]\s*)(?:(?:please\s+)?(?:remember|memorize)\b|(?:请记|(?:请)?记住))/iu,Cn=/\b(?:(?:do\s+not|don't|dont|never|not)(?:\s+need\s+to)?|no\s+need\s+to)\s+(?:please\s+)?(?:remember|memorize)\b|(?:不要|别|不用|无需|不必|不需要)(?:再)?(?:记住|记|记忆)/iu;function Ve(r){let e=r.trim();return e&&Mn.test(e)&&!Cn.test(e)?e:null}function ze(r){let e=createHash$1("sha256").update(r).digest("hex").slice(0,16),t=process.env.DEVFLOW_STATE_DIR||join$1(homedir$1(),".devflow","state",e);return join$1(t,"memory-intents.jsonl")}function Pn(r){try{return readFileSync$1(r,"utf8").split(`
|
|
3
|
-
`).filter(Boolean).flatMap(e=>{try{let t=JSON.parse(e);return typeof t.content=="string"&&typeof t.createdAt=="number"?[t]:[]}catch{return []}})}catch{return []}}function
|
|
4
|
-
`,{mode:384});}function
|
|
1
|
+
import {createServer,createConnection}from'net';import {join,dirname}from'path';import {mkdirSync,lstatSync,openSync,writeFileSync,fstatSync,closeSync,readFileSync,unlinkSync,existsSync,rmSync,renameSync,readdirSync,appendFileSync as appendFileSync$1}from'fs';import {getLocalApiKey,getDaemonSocketPath,getDaemonPidPath,loadConfig,getProjectStateDir,getDaemonRegistryPath,getProjectHash}from'@devflow-tools/sdk';import {request}from'http';import {homedir}from'os';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {fileURLToPath}from'url';import {spawn}from'child_process';import {mkdirSync as mkdirSync$1,appendFileSync,readdirSync as readdirSync$1,renameSync as renameSync$1,unlinkSync as unlinkSync$1,writeFileSync as writeFileSync$1,readFileSync as readFileSync$1,openSync as openSync$1,closeSync as closeSync$1,rmSync as rmSync$1,statSync,existsSync as existsSync$1}from'node:fs';import {dirname as dirname$1,basename,join as join$1}from'node:path';import {MemoryGate}from'@devflow-tools/memory-engine';import {randomUUID,createHash}from'crypto';import {createHash as createHash$1}from'node:crypto';import {homedir as homedir$1}from'node:os';var ce=1e4,et=3e4,D=500;function tt(r,e,t){return new Promise(n=>{try{let o=new URL(r),s=request({hostname:o.hostname,port:o.port||80,path:o.pathname+o.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":t,"Content-Length":Buffer.byteLength(e)},timeout:5e3},i=>{let a=[];i.on("data",c=>a.push(c)),i.on("end",()=>{let c=Buffer.concat(a).toString();n(i.statusCode!=null&&i.statusCode>=200&&i.statusCode<300?c:null);});});s.on("error",()=>n(null)),s.on("timeout",()=>{s.destroy(),n(null);}),s.write(e),s.end();}catch{n(null);}})}var E=class{constructor(e){this.retryScheduled=false;this.apiUrl=e?.apiUrl??process.env.DEVFLOW_API_URL??"http://127.0.0.1:13337",this.apiKey=e?.apiKey??getLocalApiKey(),this.cacheDir=e?.cacheDir??join(process.env.DEVFLOW_STATE_DIR??join(homedir(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=e?.legacyCacheDir??(e?.cacheDir?null:join(homedir(),".devflow","telemetry-cache")),this.database=e?.database??null,this.ownsDatabase=!e?.database;}async sendEvent(e){let t={...e,input:this.truncateInput(e.input)};return this.commitOrCache("tool_call",t)?(this.postHttp("/api/telemetry/tool-call",t),e.eventId):null}async sendExecutionStart(e,t,n,o,s=process.env.CLAUDE_PROJECT_DIR??process.cwd()){let i={executionId:e,sessionId:t,skillName:n,startedAt:o,projectRoot:s};this.commitOrCache("execution_start",i)&&this.postHttp("/api/telemetry/skill-execution/start",i);}async sendExecutionComplete(e,t="completed",n=Date.now(),o){let s={executionId:e,status:t,finishedAt:n,metadata:o},i=this.commitOrCache("execution_complete",s);return i&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",s),i}async sendSessionStart(e,t,n){let o={id:e,projectRoot:t,startedAt:n,label:t.split("/").pop()??"unknown"},s=this.commitOrCache("session_start",o);return s&&this.postHttp("/api/telemetry/sessions",o),s}async completeEvent(e){let t=this.commitOrCache("complete_event",e);return t&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp("/api/telemetry/tool-call/output",e)),t}async endSession(e,t=Date.now()){let n={sessionId:e,finishedAt:t},o=this.commitOrCache("session_end",n);return o&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(e)}/close`,{finishedAt:t})),o}async flushCache(){try{let n=this.getDatabase(),o=n.listTelemetryFailures({unresolvedOnly:!0,limit:D}).reverse();for(let s of o)try{this.applyOperation(s.operation,s.payload),n.resolveTelemetryFailure(s.id);}catch{}n.trimTelemetryFailures(D);}catch{}let t=[...new Set([this.cacheDir,this.legacyCacheDir].filter(n=>!!n))].filter(n=>existsSync(n)).flatMap(n=>readdirSync(n).filter(o=>o.endsWith(".json")).map(o=>{let s=join(n,o);try{return {cacheFile:s,envelope:nt(JSON.parse(readFileSync(s,"utf8")),o)}}catch{return null}})).filter(n=>n!==null).sort((n,o)=>n.envelope.timestamp-o.envelope.timestamp||le(n.envelope.operation)-le(o.envelope.operation));for(let{cacheFile:n,envelope:o}of t)try{let s=this.getDatabase();s.insertTelemetryFailure({id:o.id,operation:o.operation,payload:o.payload,error:o.failure,createdAt:o.timestamp}),this.applyOperation(o.operation,o.payload),s.resolveTelemetryFailure(o.id),unlinkSync(n);}catch{}this.database?.aggregatePendingToolMetrics();}aggregateMetrics(){return this.getDatabase().aggregatePendingToolMetrics()}async flushAndAggregate(){await this.flushCache(),this.aggregateMetrics();}close(){this.ownsDatabase&&this.database?.close(),this.database=null;}getDatabase(){return this.database??=openGlobalDevFlowDatabase(),this.database}commitOrCache(e,t){try{return this.applyOperation(e,t),!0}catch(n){return this.cacheOperation(e,t,n),false}}applyOperation(e,t){let n=this.getDatabase();switch(e){case "tool_call":this.ensureParentSession(n,t),n.insertToolCallEvent(t);return;case "execution_start":this.ensureParentSession(n,t),n.insertSkillExecution({executionId:t.executionId,sessionId:t.sessionId,skillName:t.skillName,startedAt:t.startedAt,status:"running"});return;case "execution_complete":n.reconcileSkillExecution(t.executionId,t.status,t.finishedAt,t.metadata);return;case "session_start":n.ensureSession(t),n.insertRun({id:ue(t.id),source:"hook",tool:"session",input:{projectRoot:t.projectRoot},status:"active",startedAt:t.startedAt,tokenUsed:0,metadata:{sessionId:t.id,projectRoot:t.projectRoot}});return;case "complete_event":if(!n.updateToolCallEvent(t.eventId,{output:t.output===void 0?void 0:JSON.stringify(t.output),error:t.error,duration:t.duration}))throw new Error(`Tool call event ${t.eventId} is not available for completion`);return;case "session_end":n.closeSession(t.sessionId,t.finishedAt),n.updateRun(ue(t.sessionId),{status:"completed",finishedAt:t.finishedAt});return}}ensureParentSession(e,t){let n=typeof t.sessionId=="string"?t.sessionId.trim():"";if(!n)throw new Error("Canonical session ID is required for telemetry");let o=typeof t.projectRoot=="string"&&t.projectRoot.trim()?t.projectRoot:typeof t.input?.projectRoot=="string"&&t.input.projectRoot.trim()?t.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";e.ensureSession({id:n,projectRoot:o,label:o==="unknown"?void 0:o.split("/").pop(),startedAt:Number(t.startedAt??t.timestamp??Date.now())});}cacheOperation(e,t,n){let o=Date.now(),s={id:`failure:${o}:${Math.random().toString(36).slice(2,11)}`,operation:e,payload:t,failure:n instanceof Error?n.message:String(n),timestamp:o};try{let i=this.getDatabase();i.insertTelemetryFailure({id:s.id,operation:e,payload:t,error:s.failure,createdAt:o}),i.trimTelemetryFailures(D),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let i=join(this.cacheDir,`${o}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(i,JSON.stringify(s,null,2),{mode:384}),this.trimCompatibilityCache(),this.scheduleRetry();}catch{}}trimCompatibilityCache(){try{let e=readdirSync(this.cacheDir).filter(t=>t.endsWith(".json")).sort();for(let t of e.slice(0,Math.max(0,e.length-D)))unlinkSync(join(this.cacheDir,t));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},et).unref());}postHttp(e,t){tt(`${this.apiUrl}${e}`,JSON.stringify(t),this.apiKey);}truncateInput(e){let t=JSON.stringify(e);return t===void 0||t.length<=ce?e:{_truncated:true,_original_size:t.length,_preview:`${t.substring(0,ce)}...`}}};function le(r){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(r)}function ue(r){return `hook-run:${r}`}function nt(r,e){if(!r||typeof r!="object")throw new Error("Invalid telemetry cache envelope");let t=r;if(typeof t.operation=="string"&&t.payload!==void 0)return t;let n=t.type==="tool_call"?"tool_call":t.type==="execution_start"?"execution_start":null;if(!n)throw new Error("Unknown legacy telemetry cache operation");let o=t.payload??{},s=Number(o.timestamp??o.startedAt??Date.now());return {id:`legacy-cache:${e}`,operation:n,payload:o,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:s}}function L(r){return r??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function b(r){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(L(r))}var ct=1;function lt(){if(process.env.CLAUDE_PLUGIN_ROOT)return process.env.CLAUDE_PLUGIN_ROOT;try{return join(dirname(fileURLToPath(import.meta.url)),"..","..")}catch{return process.cwd()}}function pe(r=lt()){let e=[join(r,"dist","command-registry.json"),join(r,"command-registry.json")];for(let t of e)try{if(!existsSync(t))continue;let n=JSON.parse(readFileSync(t,"utf8"));if(n.version!==ct||!ut(n.commands)){console.error(`[devflow] command registry contract mismatch: ${t}`);continue}return n.commands}catch(n){console.error(`[devflow] command registry load failed: ${n.message}`);}return null}function ut(r){return !r||typeof r!="object"||Array.isArray(r)?false:Object.values(r).every(e=>{if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return de(t.mcpTools)&&de(t.blockedNative)})}function de(r){return Array.isArray(r)&&r.every(e=>typeof e=="string"&&e.length>0)}function me(r){let e=pe();return e?e[r]?.mcpTools??[]:[]}var q=join(homedir(),".devflow"),J=join(q,"server-refs.json"),gt="http://127.0.0.1:13337/api/health",vt=600*1e3,wt=500;function _t(){existsSync(q)||mkdirSync(q,{recursive:true});}function x(){try{if(existsSync(J))return JSON.parse(readFileSync(J,"utf-8"))}catch{}return {sessions:[],lastActivity:0}}function he(r){_t(),writeFileSync(J,JSON.stringify(r));}var P=class{constructor(e){this.process=null;this.idleTimer=null;this.onShutdown=null;this.projectRoot=e;}setOnShutdown(e){this.onShutdown=e;}addRef(e){let t=x();t.sessions.includes(e)||t.sessions.push(e),t.lastActivity=Date.now(),he(t),this.resetIdleTimer();}removeRef(e){let t=x();t.sessions=t.sessions.filter(n=>n!==e),t.lastActivity=Date.now(),he(t),t.sessions.length===0&&this.resetIdleTimer();}get activeSessions(){return x().sessions.length}async ensureRunning(){return await this.healthCheck()?true:(await this.startServer(),this.waitForReady())}get isRunning(){return this.process!==null&&!this.process.killed}async stop(){this.idleTimer&&clearTimeout(this.idleTimer),this.process&&(this.process.kill("SIGTERM"),await new Promise(e=>{let t=setTimeout(()=>{this.process&&!this.process.killed&&this.process.kill("SIGKILL"),e();},5e3);this.process?this.process.on("exit",()=>{clearTimeout(t),e();}):(clearTimeout(t),e());}),this.process=null);}async startServer(){let e=join(this.projectRoot,"apps","server","dist","main.js"),t=join(this.projectRoot,"node_modules","@devflow-tools","server","dist","main.js"),n=existsSync(e)?e:t;this.process=spawn("node",[n],{cwd:this.projectRoot,env:{...process.env,NODE_ENV:process.env.NODE_ENV||"development"},stdio:["ignore","pipe","pipe"]}),this.process.stdout?.on("data",o=>{}),this.process.stderr?.on("data",o=>{}),this.process.on("exit",o=>{this.process=null,this.onShutdown&&this.onShutdown();}),this.process.on("error",()=>{this.process=null;});}async waitForReady(){let e=Date.now()+3e4;for(;Date.now()<e;){if(await this.healthCheck())return true;await new Promise(t=>setTimeout(t,wt));}return false}healthCheck(){return new Promise(e=>{let t=new URL(gt),n=request({hostname:t.hostname,port:t.port,path:t.pathname,method:"GET",timeout:2e3},o=>{e(o.statusCode===200);});n.on("error",()=>e(false)),n.on("timeout",()=>{n.destroy(),e(false);}),n.end();})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),!(x().sessions.length>0)&&(this.idleTimer=setTimeout(()=>{this.stop();},vt).unref());}};function fe(r,e,t){try{let n=openGlobalDevFlowDatabase();try{n.insertEvent({kind:r,timestamp:Date.now(),duration:t,success:e.success!==!1,metadata:e});}finally{n.close();}}catch{}}var B=process.env.DEVFLOW_SERVER_URL||"http://127.0.0.1:13337",Dt=getLocalApiKey(),xt=8,Ct=6e4,ye=new Map;function Pt(r){let e=new URL(r,B).pathname,t=ye.get(e);return t||(t={failures:0,lastFailure:0,openUntil:0,status:"closed"},ye.set(e,t)),t}function z(r,e,t){if(e.status===t)return;let n=e.status;e.status=t,fe("http_circuit_transition",{path:new URL(r,B).pathname,previous:n,status:t,failures:e.failures,openUntil:e.openUntil});}function W(r,e){e.failures++,e.lastFailure=Date.now(),e.failures>=xt&&(e.openUntil=Date.now()+Ct,z(r,e,"open"));}function Mt(r,e){let t=e.status!=="closed";e.failures=0,e.openUntil=0,t&&z(r,e,"closed");}var H=join(homedir(),".devflow","errors");function ge(r,e){try{existsSync(H)||mkdirSync(H,{recursive:!0});let t=`${new Date().toISOString()} | ${r} | ${e?.message??String(e)}
|
|
2
|
+
`;appendFileSync$1(join(H,"http-errors.log"),t);}catch{}}function we(r,e,t={}){let n=t.timeout??5e3,o=t.maxRetries??2,s=t.circuitBreaker??true,i=Pt(r);if(s&&i.openUntil>Date.now())return Promise.resolve();s&&i.status==="open"&&z(r,i,"half_open");let a=c=>new Promise(d=>{let l=JSON.stringify(e),f=new URL(r,B),h=request({hostname:f.hostname,port:f.port,path:f.pathname+f.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":Dt,"Content-Length":Buffer.byteLength(l)},timeout:n},p=>{if(p.resume(),p.statusCode&&p.statusCode>=400){let u=new Error(`HTTP ${p.statusCode}`);if(ge(r,u),c>0){let m=Math.min(1e3*Math.pow(2,o-c),8e3);setTimeout(()=>{a(c-1).then(d);},m);}else W(r,i),d();return}Mt(r,i),d();});h.on("error",p=>{if(ge(r,p),c>0){let u=Math.min(1e3*Math.pow(2,o-c),8e3);setTimeout(()=>{a(c-1).then(d);},u);}else W(r,i),d();}),h.on("timeout",()=>{h.destroy(),c>0?a(c-1).then(d):(W(r,i),d());}),h.write(l),h.end();});return a(o)}function M(r){if(!r||typeof r!="object"||Array.isArray(r))return {};let e=r,t={};for(let n of ["lastMcpCall","bypassCount"])if(n in e){let o=e[n];if(o==null)continue;t[n]=typeof o=="number"&&Number.isFinite(o)&&o>=0?o:0;}return t}function jt(r,e){return r.lastMcpCall===e.lastMcpCall&&r.bypassCount===e.bypassCount}function Ft(r){try{return existsSync(r)?M(JSON.parse(readFileSync(r,"utf-8"))):{}}catch{return {}}}function Nt(r,e){let t=e instanceof Error?e.message:String(e);console.error(`[devflow] Receipt ${r} skipped: ${t}`);}function _e(r){let e=b(r);for(let t of ["receipt.json","receipt-lock.sqlite","receipt-lock.sqlite-shm","receipt-lock.sqlite-wal"])try{existsSync(join(e,t))&&unlinkSync(join(e,t));}catch{}}function Ut(r,e){if(r.getHookReceipt(e)){_e(e);return}let t=join(b(e),"receipt.json");if(!existsSync(t))return;let n=Ft(t);r.updateHookReceipt(e,()=>n),_e(e);}function Ee(r,e,t){let n;try{n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),Ut(n,r);let o={},s=n.updateHookReceipt(r,a=>(o=M(a),M(e(o)))),i=M(s);return {receipt:i,applied:!0,changed:!jt(o,i)}}catch(o){return Nt(t,o),{receipt:{},applied:false,changed:false}}finally{try{n?.close();}catch{}}}function O(r,e){return Ee(r,()=>e,"write").applied}function Y(r,e){return Ee(r,e,"update")}var Se={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function Lt(r){switch(r){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var I=class{constructor(e,t,n){this.projectRoot=e;this.sessionId=t;this.executionId=n;}getPhase(){if(!this.sessionId||!this.executionId)return "idle";let e;try{e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250});let t=e.getContextReceipt(this.projectRoot,this.sessionId,this.executionId);if(t&&t.expiresAt>Date.now())return "context_ready";t&&e.deleteContextReceipt(this.projectRoot,this.sessionId,this.executionId);}catch{}finally{try{e?.close();}catch{}}return "context_gathering"}evaluate(e,t){let n=this.getPhase();if(t||e==="Skill")return {permissionDecision:"allow"};if(n==="context_gathering"&&Se[e])return {permissionDecision:"deny",reason:`DevFlow context required. Call mcp__devflow__get_project_context, then retry ${e}.`};if(n==="context_ready")return {permissionDecision:"allow"};let o=Se[e];if(!o)return {permissionDecision:"allow"};let s=Y(this.projectRoot,c=>({...c,bypassCount:(c.bypassCount??0)+1}));if(!s.applied)return {permissionDecision:"allow"};let i=s.receipt.bypassCount??0,a=Lt(e);return i>=a?{permissionDecision:"allow",additionalContext:`\u5DF2 ${i} \u6B21\u76F4\u63A5\u4F7F\u7528 ${e}\uFF0C\u5EFA\u8BAE\u7528 mcp__devflow__${o} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`}:{permissionDecision:"allow"}}recordMcpCall(){O(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}};var Ht=10,Bt=5e3,zt=3e4,Kt=new Int32Array(new SharedArrayBuffer(4)),xe=0;function Vt(r){if(typeof r!="object"||r===null)return false;let e=r;return typeof e.rootPath=="string"&&e.rootPath.length>0&&typeof e.projectHash=="string"&&e.projectHash.length>0&&typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.startedAt=="number"&&Number.isFinite(e.startedAt)&&e.startedAt>=0}function Ce(r){if(!existsSync$1(r))return {entries:[],needsRepair:false};try{let e=JSON.parse(readFileSync$1(r,"utf8"));if(!Array.isArray(e))return {entries:[],needsRepair:!0};let t=e.filter(Vt);return {entries:t,needsRepair:t.length!==e.length}}catch{return {entries:[],needsRepair:true}}}function Pe(r,e){mkdirSync$1(dirname$1(r),{recursive:true});let t=`${r}.${process.pid}.${Date.now()}.${xe++}.tmp`,n;try{n=openSync$1(t,"wx"),writeFileSync$1(n,JSON.stringify(e,null,2)),closeSync$1(n),n=void 0,renameSync$1(t,r);}finally{try{n!==void 0&&closeSync$1(n);}finally{rmSync$1(t,{force:true});}}}function Me(r){try{return process.kill(r,0),!0}catch(e){return e.code!=="ESRCH"}}function Oe(r){if(typeof r!="object"||r===null)return false;let e=r;return typeof e.pid=="number"&&Number.isInteger(e.pid)&&e.pid>0&&typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)&&typeof e.token=="string"&&e.token.length>0}function be(r,e){try{return readFileSync$1(r,"utf8")!==e?!1:(rmSync$1(r),!0)}catch(t){return t.code==="ENOENT"}}function Yt(r){try{let e=readFileSync$1(r,"utf8"),t;try{let o=JSON.parse(e);Oe(o)&&(t=o);}catch{}return t?Me(t.pid)?!1:be(r,e):Date.now()-statSync(r).mtimeMs>zt&&be(r,e)}catch(e){return e.code==="ENOENT"}}function Xt(r){mkdirSync$1(dirname$1(r),{recursive:true});let e=`${r}.lock`,t=Date.now()+Bt;for(;;){let n=`${process.pid}:${Date.now()}:${xe++}`,o;try{return o=openSync$1(e,"wx"),writeFileSync$1(o,JSON.stringify({pid:process.pid,createdAt:Date.now(),token:n})),closeSync$1(o),o=void 0,{path:e,token:n}}catch(s){if(o!==void 0)try{closeSync$1(o);}finally{rmSync$1(e,{force:true});}if(s.code!=="EEXIST")throw s}if(!Yt(e)){if(Date.now()>=t)throw new Error(`Timed out acquiring daemon registry lock: ${e}`);Atomics.wait(Kt,0,0,Ht);}}}function Qt(r){try{let e=readFileSync$1(r.path,"utf8"),t=JSON.parse(e);Oe(t)&&t.token===r.token&&rmSync$1(r.path);}catch(e){if(e.code!=="ENOENT")throw e}}function Ae(r){let e=getDaemonRegistryPath(),t=Xt(e);try{return r(e)}finally{Qt(t);}}function je(r,e){Ae(t=>{let n=Ce(t).entries.filter(o=>o.rootPath!==r&&Me(o.pid));n.push({rootPath:r,projectHash:getProjectHash(r),pid:e,startedAt:Date.now()}),Pe(t,n);});}function Fe(r,e){Ae(t=>{let n=Ce(t).entries.filter(o=>o.rootPath!==r||e!==void 0&&o.pid!==e);Pe(t,n);});}async function N(r){let e=!r.memory,t=r.memory??new MemoryGate(r.projectRoot),n=0,o=0;try{await t.forceWarmUp(),r.trigger==="session_end"&&(n=await t.releasePendingDistillLeases(r.sessionId)),o=t.getPendingEventCount();}finally{e&&t.close();}let s={pendingEvents:o,releasedLeases:n,trigger:r.trigger,sessionId:r.sessionId};try{let i=openGlobalDevFlowDatabase();try{let a=Date.now(),c=`distill:${a}:${Math.random().toString(36).slice(2,10)}`;i.recordMemoryDistillCheckpoint({id:c,projectRoot:r.projectRoot,sessionId:r.sessionId,trigger:r.trigger,pendingEvents:o,releasedLeases:n,createdAt:a}),i.insertEvent({kind:"memory_distill_requested",timestamp:a,success:!0,metadata:{...s,projectRoot:r.projectRoot}});}finally{i.close();}}catch{}return s}function X(r){if(r.pendingEvents===0)return "";let e=r.sessionId?`\uFF0CsessionId=${r.sessionId}`:"";return `Memory distill checkpoint: ${r.pendingEvents} \u4E2A\u4E8B\u4EF6\u5F85\u63D0\u70BC${e}\u3002\u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210\u540E\uFF0C\u8C03\u7528 mcp__devflow__memory_request_distill\uFF1B\u6309\u8FD4\u56DE prompt \u63D0\u70BC observations\uFF0C\u518D\u8C03\u7528 mcp__devflow__memory_save_distilled\u3002`}function ln(r){return Buffer.from(r,"utf8").toString("base64url")}var T=class{constructor(e){this.projectRoot=e;this.sessions=new Map;this.sessionsDir=join(b(e),"hook-sessions");}registerSession(e){let t=e.trim();if(!t)throw new Error("session_id_required");let n=this.get(t);if(n)return n.lastActivityAt=Date.now(),this.persist(n),n;let o=Date.now(),s={sessionId:t,projectRoot:this.projectRoot,requiredMcpTools:[],startedAt:o,lastActivityAt:o};return this.sessions.set(t,s),this.persist(s),s}startExecution(e,t,n){let o=this.registerSession(e);return (!o.executionId||o.skillName!==t)&&(o.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),o.skillName=t,o.requiredMcpTools=[...new Set(n)],o.lastActivityAt=Date.now(),this.persist(o),o}get(e){let t=e.trim();if(!t)return null;let n=this.sessions.get(t);if(n)return n;let o=this.snapshotPath(t);if(!existsSync(o))return null;try{let s=JSON.parse(readFileSync(o,"utf8"));return s.sessionId!==t||s.projectRoot!==this.projectRoot?null:(s.requiredMcpTools=Array.isArray(s.requiredMcpTools)?s.requiredMcpTools:[],this.sessions.set(t,s),s)}catch{return null}}completeExecution(e){let t=this.get(e);if(!t)return null;let n={...t,requiredMcpTools:[...t.requiredMcpTools]};return delete t.executionId,delete t.skillName,t.requiredMcpTools=[],t.lastActivityAt=Date.now(),this.persist(t),n}removeSession(e){let t=e.trim();t&&(this.sessions.delete(t),rmSync(this.snapshotPath(t),{force:true}));}list(){return [...this.sessions.values()]}snapshotPath(e){return join(this.sessionsDir,`${ln(e)}.json`)}persist(e){mkdirSync(this.sessionsDir,{recursive:true,mode:448});let t=this.snapshotPath(e.sessionId),n=`${t}.${process.pid}.tmp`;writeFileSync(n,JSON.stringify(e),{mode:384}),renameSync(n,t);}};var mn=process.env.DEVFLOW_SERVER_URL||"http://127.0.0.1:13337",hn=getLocalApiKey();function fn(r,e){return new Promise(t=>{let n=JSON.stringify(e),o=new URL(r,mn),s=request({hostname:o.hostname,port:o.port,path:o.pathname,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":hn,"Content-Length":Buffer.byteLength(n)},timeout:5e3},()=>t());s.on("error",()=>t()),s.write(n),s.end();})}async function Q(r,e=L(),t=true,n){let o;try{o=JSON.parse(r);}catch{return}let s=o.session_id?.trim();if(!s)return;let i=new T(e),a=i.get(s),c=n?.telemetry??new E,d=!n?.telemetry;try{try{await c.flushAndAggregate();}catch{}let l;try{l=openGlobalDevFlowDatabase();let f=l.listToolCallEventsBySession(s),h=a?.executionId;if(h){let p=f.filter(y=>y.executionId===h),u=p.length,m=p.filter(y=>y.isMcpTool).length,g=u-m,v=p.filter(y=>y.toolType==="subagent").length,w=p.map(y=>y.timestamp).filter(Boolean),S=w.length>=2?Math.max(...w)-Math.min(...w):0;try{l.updateSkillExecution(h,{status:"completed",finishedAt:Date.now(),totalToolCalls:u,mcpToolCalls:m,directToolCalls:g,subagentCount:v,totalDuration:S,mcpComplianceRate:u>0?Math.round(m/u*1e4)/100:0}),await fn("/api/telemetry/skill-execution/complete",{executionId:h,finishedAt:Date.now(),status:"completed",summary:{totalToolCalls:u,mcpToolCalls:m,directToolCalls:g,subagentCount:v,totalDuration:S,mcpComplianceRate:u>0?Math.round(m/u*1e4)/100:0}});}catch{}}t&&l.deleteHookReceipt(e),l.deleteContextReceipt(e,s);}catch{}finally{l?.close();}try{if(await N({projectRoot:e,sessionId:s,trigger:"session_end",memory:n?.memory}),n?.memory)await n.memory.closeSession(s);else {let f=new(await import('@devflow-tools/memory-engine')).MemoryGate(e);try{await f.closeSession(s);}finally{f.close();}}}catch{}try{await c.endSession(s),await c.flushAndAggregate();}catch{}}finally{d&&c.close(),i.removeSession(s);}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let r="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{r+=e;}),process.stdin.on("end",async()=>{await Q(r.trim()||process.argv[2]||""),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}var bn=/(?:^|[.!?。!?]\s*)(?:(?:please\s+)?(?:remember|memorize)\b|(?:请记|(?:请)?记住))/iu,Tn=/\b(?:(?:do\s+not|don't|dont|never|not)(?:\s+need\s+to)?|no\s+need\s+to)\s+(?:please\s+)?(?:remember|memorize)\b|(?:不要|别|不用|无需|不必|不需要)(?:再)?(?:记住|记|记忆)/iu;function $e(r){let e=r.trim();return e&&bn.test(e)&&!Tn.test(e)?e:null}function qe(r){let e=createHash$1("sha256").update(r).digest("hex").slice(0,16),t=process.env.DEVFLOW_STATE_DIR||join$1(homedir$1(),".devflow","state",e);return join$1(t,"memory-intents.jsonl")}function In(r){try{return readFileSync$1(r,"utf8").split(`
|
|
3
|
+
`).filter(Boolean).flatMap(e=>{try{let t=JSON.parse(e);return typeof t.content=="string"&&typeof t.createdAt=="number"?[t]:[]}catch{return []}})}catch{return []}}function Je(r,e){let t=qe(r);mkdirSync$1(dirname$1(t),{recursive:true}),appendFileSync(t,`${JSON.stringify(e)}
|
|
4
|
+
`,{mode:384});}function Ge(r){let e=qe(r),t=`${e}.claim-`,n=`${basename(e)}.claim-`,o=(()=>{try{return readdirSync$1(dirname$1(e)).filter(a=>a.startsWith(n)&&!a.includes(".tmp-")).sort()[0]}catch{return}})(),s=o?join$1(dirname$1(e),o):`${t}${Date.now()}-${process.pid}`;if(!o)try{renameSync$1(e,s);}catch{return null}let i=In(s);if(i.length===0){try{unlinkSync$1(s);}catch{}return null}return {path:s,intents:i}}function We(r){if(r.intents.shift(),r.intents.length===0){try{unlinkSync$1(r.path);}catch{}return}let e=`${r.path}.tmp-${process.pid}`;writeFileSync$1(e,r.intents.map(t=>JSON.stringify(t)).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`,{mode:384}),renameSync(e,r.path);}var
|
|
7
|
-
`);if(t=f.pop()??"",Buffer.byteLength(t,"utf8")>
|
|
8
|
-
`,m=>{if(m){l(m);return}s=true,l();})||(i=false,e.once("drain",
|
|
9
|
-
`);let t=fstatSync(e);this.pidIdentity={dev:t.dev,ino:t.ino};}finally{closeSync(e);}}removePathIfOwned(e,t,n,o){try{return !this.pathMatchesIdentity(e,t)||o!==void 0&&readFileSync(e,"utf8")!==o||!this.pathMatchesIdentity(e,t)?!1:(unlinkSync(e),!0)}catch(s){return s.code!=="ENOENT"&&console.error(`[devflow-daemon] Failed to remove ${n}:`,s.message),false}}isSocketAcceptingConnections(){return new Promise((e,t)=>{let n=createConnection(this.socketPath),o=setTimeout(()=>{n.destroy(),t(new Error(`Timed out probing daemon socket ${this.socketPath}`));},Vn),s=i=>{clearTimeout(o),n.destroy(),e(i);};n.once("connect",()=>s(true)),n.once("error",i=>{let c=i.code;c==="ENOENT"||c==="ECONNREFUSED"?s(false):(clearTimeout(o),t(i));});})}listen(){return new Promise((e,t)=>{let n=this.server;if(!n){t(new Error("Daemon server is not initialized"));return}let o=i=>{n.off("listening",s),t(i);},s=()=>{n.off("error",o);try{let i=this.getPathIdentity(this.socketPath);if(!i)throw new Error(`Daemon socket missing after listen: ${this.socketPath}`);this.socketIdentity=i,e();}catch(i){t(i);}};n.once("error",o),n.once("listening",s),n.listen(this.socketPath);})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{console.error("[devflow-daemon] Idle timeout, exiting"),this.shutdown();},Bn).unref();}async handleRequest(e){switch(e.type){case "pre-tool-use":return this.handlePreToolUse(e.input);case "post-tool-use":return this.handlePostToolUse(e.input);case "stop":return this.startExplicitIntentFlush(),{status:"ok"};case "memory-snapshot":return this.handleMemorySnapshot();case "session-start":return this.handleSessionStart(e.input??"");case "session-end":return await this.handleSessionEnd(e.input??""),{status:"ok"};case "user-prompt-submit":return this.handleUserPromptSubmit(e.input);case "pre-compact":return this.handlePreCompact(e.input);default:return {error:"unknown request type"}}}async handlePreToolUse(e){try{if(!e||e.trim()==="")return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};let t=JSON.parse(e);t.tool_input=nr(t.tool_name,t.tool_input,process.env,this.projectRoot);let n=this.trackSession(t.session_id);if(t.tool_name==="Skill"){let m=t.tool_input?.skill;if(m&&m.startsWith("devflow:")){let g=W(m),y=this.skillManager.startExecution(m,{required_mcp_tools:g});this.telemetry.sendExecutionStart(y,n,m,Date.now()).catch(()=>{});}}let o=this.skillManager.detect(),s=t.tool_name.startsWith("mcp__"),i=s?t.tool_name.replace(/^mcp__[^_]+__/,""):void 0,c=new D(this.projectRoot),a=c.getPhase(),d=c.evaluate(t.tool_name,s),l;d.permissionDecision==="deny"?l={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:d.reason??"MCP context required"}}:d.additionalContext?l={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:d.additionalContext}}:l={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}},t.tool_name.startsWith("mcp__devflow__")&&(l.hookSpecificOutput.updatedInput=t.tool_input);let f=this.skillManager.getCurrentExecutionId()??n,u={eventId:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,executionId:f,sessionId:n,timestamp:Date.now(),toolName:t.tool_name,toolType:s?"mcp":t.tool_name==="Agent"?"subagent":"direct",isMcpTool:s,mcpToolName:i,mcpEnforced:s&&a==="context_gathering",mcpFallback:!s&&a==="context_gathering",kind:tr(t.tool_name),input:t.tool_input,duration:0,blocked:l&&l.hookSpecificOutput?.permissionDecision==="deny"},p=await this.telemetry.sendEvent(u);return p&&(this.eventMap.push({toolName:t.tool_name,eventId:p,sessionId:n,timestamp:u.timestamp}),this.noteTelemetryOperation()),l}catch{return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}}trackSession(e){let t=e?.trim()||this.sessionId||`session:${this.projectName}:${Date.now().toString(36)}`;return this.registerSession(t),t}registerSession(e){this.activeSessionIds.has(e)||(this.activeSessionIds.size===0&&F(this.projectRoot,{bypassCount:0}),this.activeSessionIds.add(e),this.serverManager.addRef(e),this.telemetry.sendSessionStart(e,this.projectRoot,Date.now()).catch(()=>{})),this.sessionId=e;}handleSessionStart(e){try{let t=JSON.parse(e);return typeof t.session_id!="string"||!t.session_id.trim()?{error:"session_id_required"}:(this.registerSession(t.session_id.trim()),{status:"ok"})}catch{return {error:"session_start_invalid"}}}popEventFromMap(e,t){let n=this.eventMap.filter(s=>s.toolName===e&&s.sessionId===t);if(n.length===0)return null;n.sort((s,i)=>Math.abs(s.timestamp-Date.now())-Math.abs(i.timestamp-Date.now()));let o=n[0];return this.eventMap=this.eventMap.filter(s=>s.eventId!==o.eventId),o}enforcePostToolUse(e){if(!er[e])return null;let t=Math.floor(Date.now()/1e3),n=Z(this.projectRoot,i=>t-(i.lastMcpCall??0)<30?i:{...i,bypassCount:(i.bypassCount??0)+1});if(!n.applied||!n.changed)return null;let o=n.receipt.bypassCount??0;if(o===1)return null;let s;switch(e){case "Agent":s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u4F7F\u7528\u4E86 Agent \u5B50\u4EE3\u7406\u6267\u884C\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Bash":s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Bash \u547D\u4EE4\u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Glob":s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Glob \u5339\u914D\u6587\u4EF6\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Grep":s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Grep \u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "WebSearch":case "WebFetch":s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86\u7F51\u7EDC\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_knowledge MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;default:s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u8BF7\u4F7F\u7528 DevFlow MCP \u5DE5\u5177\u66FF\u4EE3\u76F4\u63A5\u8C03\u7528\u3002`;}return o>=3?s=`${s} \u5DF2\u8FBE\u5230\u6700\u5927\u8FDD\u89C4\u6B21\u6570\uFF0C\u540E\u7EED\u7ED5\u8FC7\u5C06\u88AB\u786C\u963B\u6B62\u3002`:o>=2?s=`${s} \u4E0B\u6B21\u8FDD\u89C4\u5C06\u88AB\u963B\u6B62\u3002`:s=`${s} \u8BF7\u7ACB\u5373\u7EA0\u6B63\u3002`,s}async handlePostToolUse(e){if(!e)return null;let t;try{t=JSON.parse(e);}catch{return null}let n=t.tool_name||"",o=t.tool_input||{},s=t.tool_response,i=this.trackSession(t.session_id);if(n==="Skill"){let v=o?.skill;if(v&&v.startsWith("devflow:")){let E=W(v);this.skillManager.startExecution(v,{required_mcp_tools:E}),F(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}}n.startsWith("mcp__")&&new D(this.projectRoot).recordMcpCall();let c=this.popEventFromMap(n,i);if(c){let v=typeof s=="string"?s:JSON.stringify(s),E=v.length>5e3?{_truncated:true,_originalSize:v.length,text:v.slice(0,5e3)}:s,et=Date.now()-c.timestamp;await this.telemetry.completeEvent({eventId:c.eventId,sessionId:i,output:E,duration:et,completedAt:Date.now()})&&this.noteTelemetryOperation();}let a=typeof s=="object"&&s!==null?s:null,d=a?.exitCode,l=a?.stderr,f=/^\s*(ls|cat|pwd|cd|echo|head|tail|wc|which|whoami|date|env|printenv|id|hostname|uname)\b/,h=o.command||"",u=JSON.stringify(s),p=Buffer.byteLength(u,"utf8"),m=this.countResults(s),g,y,_=true;if(n.startsWith("mcp__"))g="mcp_call",y={mcpTool:n.replace(/^mcp__[^_]+__/,""),query:o.query??null,resultCount:m,resultSizeBytes:p};else if(n==="Read"||n==="Write"||n==="Edit")g=n==="Read"?"file_read":"file_write",y={filePath:o.file_path??null,fileContentSize:p};else if(n==="Bash"){let v=f.test(h),E=d!==void 0&&d!==0;_=!v||E,g=E?"bash_error":"bash_command",y={command:h||n,exitCode:d??null,stderr:l??null};}else n==="Agent"?(g="subagent",y={subagentType:o.subagent_type??null,description:typeof o.description=="string"?o.description.slice(0,200):null}):n==="WebSearch"||n==="WebFetch"?(g=n==="WebSearch"?"web_search":"web_fetch",y={query:typeof o.query=="string"?o.query.slice(0,200):null}):(_=false,g="tool_use",y={});if(_){let v={id:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:i,tool:n,kind:g,payload:y,command:h||void 0,exitCode:d,stderr:l??void 0,durationMs:0,createdAt:Date.now()};await this.postMemoryEvent(v);}let w=this.enforcePostToolUse(n);return w?(console.error("[devflow-daemon] Enforcement:",w),{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:JSON.stringify(w)}}):null}countResults(e){if(!e)return 0;let t=e;if(typeof e=="string")try{t=JSON.parse(e);}catch{return 1}let n=t,o=["files","results","data","result","memories","nodes","chunks","findings","symbols"],s=n.data??n.structuredContent??n;if(Array.isArray(s))return s.length;if(typeof s=="object"&&s!==null){let i=s,c=0;for(let a of o)Array.isArray(i[a])&&(c+=i[a].length);for(let[,a]of Object.entries(i))a&&typeof a=="object"&&!Array.isArray(a)&&(c+=this.countResults(a));return c>0?c:Object.keys(i).length>0?1:0}return 0}async postMemoryEvent(e){try{await(await this.getMemoryGate()).recordEvent(e);}catch(t){console.error("[devflow-daemon] Local memory event write failed:",t.message);}Re(`/api/memory/session-events?rootPath=${encodeURIComponent(this.projectRoot)}`,e);}async getMemoryGate(){let e=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return this.memoryWarmup??=e.forceWarmUp().catch(t=>{throw this.memoryWarmup=null,t}),await this.memoryWarmup,e}async handleUserPromptSubmit(e){try{let t=JSON.parse(e),n=typeof t.prompt=="string"?t.prompt:"";if(n.trim()){let o=typeof t.session_id=="string"?t.session_id:void 0,s=Ve(n);s&&Ye(this.projectRoot,{content:s,sessionId:o,createdAt:Date.now()}),await(await this.getMemoryGate()).recordUserMessage(n.slice(0,2e3));}}catch{}return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow"}}}async handlePreCompact(e){let t=this.sessionId??void 0;try{let i=JSON.parse(e);typeof i.session_id=="string"&&i.session_id.trim()&&(t=i.session_id.trim());}catch{}await this.flushTelemetry(),this.startExplicitIntentFlush(),await this.explicitIntentFlush;let n=await this.getMemoryGate(),o=await $({projectRoot:this.projectRoot,sessionId:t,trigger:"pre_compact",memory:n}),s=He(o);return {hookSpecificOutput:{hookEventName:"PreCompact",...s?{additionalContext:s}:{}}}}noteTelemetryOperation(){this.successfulTelemetryOperations++,this.successfulTelemetryOperations>=Zn&&this.flushTelemetry();}async flushTelemetry(){this.successfulTelemetryOperations=0,await this.telemetry.flushAndAggregate();}startExplicitIntentFlush(){this.explicitIntentFlush||(this.explicitIntentFlush=this.handleStop().finally(()=>{this.explicitIntentFlush=null;}));}async handleStop(){this.flushTelemetry();let e=Xe(this.projectRoot);if(e)try{let t=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);for(await t.forceWarmUp();e.intents.length>0;){let n=e.intents[0];await t.saveExplicitMemoryIntent(n.content,n.sessionId),Qe(e);}}catch(t){console.error("[devflow-daemon] Explicit memory intent save failed:",t.message);}}async handleMemorySnapshot(){let e=loadConfig(this.projectRoot).sessionStart?.injectMemories??true;if(e===false)return {status:"ok",enabled:false,markdown:""};let t=typeof e=="object"?e.topN:void 0,n=typeof e=="object"?e.budgetTokens:void 0,o=Number.isFinite(t)?Math.max(0,Math.floor(t)):10,s=Number.isFinite(n)?Math.max(1,Math.floor(n)):800;try{let a={...await(this.explicitMemoryGate??=new MemoryGate(this.projectRoot)).getAll({purpose:"session_bootstrap",budgetTokens:s,limit:o}),_devflow_unique:{memory_version:1,structured_storage:!0,project_context_included:!0},_accuracy:{data_freshness_ms:0,source_layer:"memory",degradation:"none"}};if(a.memories.length===0)return {status:"ok",enabled:!0,markdown:`## Project memory
|
|
10
|
-
\u672C\u9879\u76EE\u6682\u65E0\u8BB0\u5FC6`};let d=
|
|
6
|
+
`,{mode:384}),renameSync$1(e,r.path);}function U(r){let e=r.trim().replace(/^\//,"");if(!e.startsWith("devflow:"))return null;let t=e.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(t)?`devflow:${t.toLowerCase()}`:null}function He(r){let e=r.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!e)return null;let t=U(e[1]);return t?{rawName:e[1],skillName:t}:null}function k(r,e){return e?`evt_tool_${createHash("sha256").update(`${r}\0${e}`).digest("hex").slice(0,24)}`:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}var Gn=600*1e3,Wn=2e3,Hn=250,Bn=2e3,zn=1e3,Be=1024*1024,Kn=2*1024*1024,Vn=6e4,Yn=100,Xn={Agent:"get_project_context",Bash:"get_project_context",Glob:"get_project_context",Grep:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function Qn(r){switch(r){case "Read":case "Glob":return "file_read";case "Write":case "Edit":case "NotebookEdit":return "file_write";case "Bash":return "bash_command";case "Agent":return "subagent";case "Skill":return "skill_invoke";default:return "tool_use"}}function ne(r){return typeof r=="string"&&r.trim().length>0}function Zn(r,e,t=process.env,n){if(!r.startsWith("mcp__devflow__"))return e;let o=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};if(ne(o.projectRoot))return o;let s=ne(t.CLAUDE_PROJECT_DIR)?t.CLAUDE_PROJECT_DIR:n;return ne(s)&&(o.projectRoot=s),o}var oe=class{constructor(e,t){this.socketIdentity=null;this.pidIdentity=null;this.server=null;this.activeSessionIds=new Set;this.eventMap=[];this.idleTimer=null;this.telemetryFlushTimer=null;this.successfulTelemetryOperations=0;this.shutdownPromise=null;this.explicitMemoryGate=null;this.memoryWarmup=null;this.explicitIntentFlush=null;this.projectRoot=e,this.socketPath=getDaemonSocketPath(e),this.pidPath=getDaemonPidPath(e),this.telemetry=new E,this.runtimeStore=new T(this.projectRoot),this.serverManager=new P(e),t&&this.handleSessionStart(t);}async start(){mkdirSync(dirname(this.socketPath),{recursive:true,mode:448}),await this.cleanStaleStartupResources(),this.server=createServer(e=>this.handleConnection(e));try{await this.listen(),this.writePidFile(),je(this.projectRoot,process.pid);}catch(e){throw await this.closeServer(),this.cleanupOwnedResources(),e}this.server.on("error",e=>{console.error("[devflow-daemon] Server error:",e.message);}),console.error("[devflow-daemon] Listening on",this.socketPath),await this.telemetry.flushAndAggregate(),this.telemetryFlushTimer=setInterval(()=>{this.flushTelemetry();},Vn),this.telemetryFlushTimer.unref(),this.resetIdleTimer();}handleConnection(e){let t="",n=false,o=false,s=0,i=Promise.resolve();e.setEncoding("utf8");let a=()=>{o||(o=true,clearTimeout(c),e.destroy());},c=setTimeout(()=>{a();},Wn).unref(),d=async l=>{if(!o){o=true,clearTimeout(c);try{await this.writeFrame(e,l);}catch{}finally{e.destroy();}}};e.on("data",l=>{if(o)return;t+=l;let f=t.split(`
|
|
7
|
+
`);if(t=f.pop()??"",Buffer.byteLength(t,"utf8")>Be){a();return}if(f.length===0)return;let h=0;for(let p of f){let u=Buffer.byteLength(p,"utf8");if(u>Be){a();return}h+=u+1;}if(s+h>Kn){a();return}s+=h,i=i.then(async()=>{for(let p of f){if(o)return;if(!n){let u;try{u=JSON.parse(p);}catch{await d({error:"handshake_invalid"});return}if(u?.type!=="hello"||typeof u.rootPath!="string"){await d({error:"handshake_invalid"});return}if(u.rootPath!==this.projectRoot){await d({error:"handshake_root_mismatch",expected:this.projectRoot});return}n=true,clearTimeout(c),this.resetIdleTimer();continue}if(p.trim())try{let u=JSON.parse(p),m=await this.handleRequest(u);m!==null&&!o&&await this.writeFrame(e,m);}catch(u){o||await this.writeFrame(e,{error:u.message});}}}).catch(()=>{a();}).finally(()=>{s-=h;});}),e.on("close",()=>clearTimeout(c)),e.on("error",()=>{});}writeFrame(e,t){return new Promise((n,o)=>{if(e.destroyed||!e.writable){o(new Error("Socket is not writable"));return}let s=false,i=true,a=false,c=setTimeout(()=>{e.destroy(),l(new Error("Timed out writing daemon response"));},zn),d=()=>{clearTimeout(c),e.off("close",f),e.off("error",h),e.off("drain",p);},l=m=>{a||!m&&(!s||!i)||(a=true,d(),m?o(m):n());},f=()=>l(new Error("Socket closed during write")),h=m=>l(m),p=()=>{i=true,l();};e.once("close",f),e.once("error",h),e.write(`${JSON.stringify(t)}
|
|
8
|
+
`,m=>{if(m){l(m);return}s=true,l();})||(i=false,e.once("drain",p));})}async cleanStaleStartupResources(){let e=this.getPathIdentity(this.socketPath);if(e){if(await this.isSocketAcceptingConnections())throw new Error(`Daemon socket already active for ${this.projectRoot}`);this.removePathIfOwned(this.socketPath,e,"stale socket");}let t=this.getPathIdentity(this.pidPath);t&&this.removePathIfOwned(this.pidPath,t,"stale PID file");}getPathIdentity(e){try{let t=lstatSync(e);return {dev:t.dev,ino:t.ino}}catch(t){if(t.code==="ENOENT")return null;throw t}}pathMatchesIdentity(e,t){if(!t)return false;try{let n=this.getPathIdentity(e);return n?.dev===t.dev&&n.ino===t.ino}catch(n){return console.error("[devflow-daemon] Failed to verify path ownership:",n.message),false}}writePidFile(){let e=openSync(this.pidPath,"wx",384);try{writeFileSync(e,`${process.pid}
|
|
9
|
+
`);let t=fstatSync(e);this.pidIdentity={dev:t.dev,ino:t.ino};}finally{closeSync(e);}}removePathIfOwned(e,t,n,o){try{return !this.pathMatchesIdentity(e,t)||o!==void 0&&readFileSync(e,"utf8")!==o||!this.pathMatchesIdentity(e,t)?!1:(unlinkSync(e),!0)}catch(s){return s.code!=="ENOENT"&&console.error(`[devflow-daemon] Failed to remove ${n}:`,s.message),false}}isSocketAcceptingConnections(){return new Promise((e,t)=>{let n=createConnection(this.socketPath),o=setTimeout(()=>{n.destroy(),t(new Error(`Timed out probing daemon socket ${this.socketPath}`));},Hn),s=i=>{clearTimeout(o),n.destroy(),e(i);};n.once("connect",()=>s(true)),n.once("error",i=>{let a=i.code;a==="ENOENT"||a==="ECONNREFUSED"?s(false):(clearTimeout(o),t(i));});})}listen(){return new Promise((e,t)=>{let n=this.server;if(!n){t(new Error("Daemon server is not initialized"));return}let o=i=>{n.off("listening",s),t(i);},s=()=>{n.off("error",o);try{let i=this.getPathIdentity(this.socketPath);if(!i)throw new Error(`Daemon socket missing after listen: ${this.socketPath}`);this.socketIdentity=i,e();}catch(i){t(i);}};n.once("error",o),n.once("listening",s),n.listen(this.socketPath);})}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!(this.activeSessionIds.size>0)&&(this.idleTimer=setTimeout(()=>{console.error("[devflow-daemon] Idle timeout, exiting"),this.shutdown();},Gn).unref());}async handleRequest(e){switch(e.type){case "pre-tool-use":return this.handlePreToolUse(e.input);case "post-tool-use":return this.handlePostToolUse(e.input);case "post-tool-use-failure":return this.handlePostToolUseFailure(e.input);case "stop":return await this.handleStop(e.input??""),{status:"ok"};case "memory-snapshot":return this.handleMemorySnapshot();case "session-start":return this.handleSessionStart(e.input??"");case "session-end":return await this.handleSessionEnd(e.input??""),{status:"ok"};case "user-prompt-submit":return this.handleUserPromptSubmit(e.input);case "pre-compact":return this.handlePreCompact(e.input);default:return {error:"unknown request type"}}}async handlePreToolUse(e){try{if(!e||e.trim()==="")return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};let t=JSON.parse(e);t.tool_input=Zn(t.tool_name,t.tool_input,process.env,this.projectRoot);let n=this.trackSession(t.session_id);if(t.tool_name==="Skill"){let m=t.tool_input?.skill,g=m?U(m):null;g&&this.startSkillExecution(n,g);}let o=this.runtimeStore.get(n);t.tool_name.startsWith("mcp__devflow__")&&(t.tool_input._devflow_session_id=n,t.tool_input._devflow_execution_id=o?.executionId??n,t.tool_use_id&&(t.tool_input._devflow_tool_use_id=t.tool_use_id));let s=t.tool_name.startsWith("mcp__"),i=s?t.tool_name.replace(/^mcp__[^_]+__/,""):void 0,a=new I(this.projectRoot,n,o?.executionId),c=a.getPhase(),d=a.evaluate(t.tool_name,s),l;d.permissionDecision==="deny"?l={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:d.reason??"MCP context required"}}:d.additionalContext?l={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:d.additionalContext}}:l={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}},t.tool_name.startsWith("mcp__devflow__")&&(l.hookSpecificOutput.updatedInput=t.tool_input);let f=o?.executionId??n,p={eventId:k(n,t.tool_use_id),executionId:f,sessionId:n,projectRoot:this.projectRoot,toolUseId:t.tool_use_id,timestamp:Date.now(),toolName:t.tool_name,toolType:s?"mcp":t.tool_name==="Agent"?"subagent":"direct",isMcpTool:s,mcpToolName:i,mcpEnforced:s&&c==="context_gathering",mcpFallback:!s&&c==="context_gathering",kind:Qn(t.tool_name),input:t.tool_input,duration:0,blocked:l&&l.hookSpecificOutput?.permissionDecision==="deny"},u=await this.telemetry.sendEvent(p);return u&&(this.eventMap.push({toolName:t.tool_name,toolUseId:t.tool_use_id,eventId:u,sessionId:n,timestamp:p.timestamp}),this.noteTelemetryOperation()),l}catch{return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}}trackSession(e){let t=e?.trim()||(this.activeSessionIds.size===1?[...this.activeSessionIds][0]:"");if(!t)throw new Error("session_id_required");return this.registerSession(t),t}registerSession(e){this.activeSessionIds.has(e)||(this.activeSessionIds.size===0&&O(this.projectRoot,{bypassCount:0}),this.activeSessionIds.add(e),this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.serverManager.addRef(e),this.telemetry.sendSessionStart(e,this.projectRoot,Date.now()).catch(()=>{})),this.runtimeStore.registerSession(e);}startSkillExecution(e,t){let n=this.runtimeStore.get(e)?.executionId,o=this.runtimeStore.startExecution(e,t,me(t));o.executionId&&o.executionId!==n&&this.telemetry.sendExecutionStart(o.executionId,e,t,o.lastActivityAt,this.projectRoot).catch(()=>{});}async handleSessionStart(e){try{let t=JSON.parse(e);if(typeof t.session_id!="string"||!t.session_id.trim())return {error:"session_id_required"};let n=t.session_id.trim();this.registerSession(n);let o=await this.getMemoryGate();await o.ensureSession(n,this.projectRoot,"Claude Code session"),await o.releasePendingDistillLeases();let s=o.getPendingEventCount();return {status:"ok",...s>0?{additionalContext:X({pendingEvents:s,releasedLeases:0,trigger:"session_end"})}:{}}}catch{return {error:"session_start_invalid"}}}popEventFromMap(e,t,n){let o=this.eventMap.filter(a=>a.toolName===e&&a.sessionId===t);if(o.length===0)return null;let i=(n?o.find(a=>a.toolUseId===n):void 0)??o.sort((a,c)=>a.timestamp-c.timestamp)[0];return this.eventMap=this.eventMap.filter(a=>a.eventId!==i.eventId),i}enforcePostToolUse(e){if(!Xn[e])return null;let t=Math.floor(Date.now()/1e3),n=Y(this.projectRoot,i=>t-(i.lastMcpCall??0)<30?i:{...i,bypassCount:(i.bypassCount??0)+1});if(!n.applied||!n.changed)return null;let o=n.receipt.bypassCount??0;if(o===1)return null;let s;switch(e){case "Agent":s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u4F7F\u7528\u4E86 Agent \u5B50\u4EE3\u7406\u6267\u884C\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Bash":s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Bash \u547D\u4EE4\u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Glob":s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Glob \u5339\u914D\u6587\u4EF6\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "Grep":s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86 Grep \u641C\u7D22\u4EE3\u7801\u3002\u4E0B\u6B21\u8BF7\u7528 get_project_context MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;case "WebSearch":case "WebFetch":s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u4F60\u521A\u624D\u7528\u4E86\u7F51\u7EDC\u641C\u7D22\u3002\u4E0B\u6B21\u8BF7\u7528 get_knowledge MCP \u5DE5\u5177\u66FF\u4EE3\u3002`;break;default:s=`\u7B2C ${o} \u6B21\u8FDD\u89C4\uFF1A\u8BF7\u4F7F\u7528 DevFlow MCP \u5DE5\u5177\u66FF\u4EE3\u76F4\u63A5\u8C03\u7528\u3002`;}return o>=3?s=`${s} \u5DF2\u8FBE\u5230\u6700\u5927\u8FDD\u89C4\u6B21\u6570\uFF0C\u540E\u7EED\u7ED5\u8FC7\u5C06\u88AB\u786C\u963B\u6B62\u3002`:o>=2?s=`${s} \u4E0B\u6B21\u8FDD\u89C4\u5C06\u88AB\u963B\u6B62\u3002`:s=`${s} \u8BF7\u7ACB\u5373\u7EA0\u6B63\u3002`,s}async handlePostToolUse(e){if(!e)return null;let t;try{t=JSON.parse(e);}catch{return null}let n=t.tool_name||"",o=t.tool_input||{},s=t.tool_response,i=this.trackSession(t.session_id);if(n==="Skill"){let y=o?.skill,_=y?U(y):null;_&&(this.startSkillExecution(i,_),O(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0}));}n.startsWith("mcp__")&&new I(this.projectRoot).recordMcpCall();let a=this.popEventFromMap(n,i,t.tool_use_id);if(a){let y=typeof s=="string"?s:JSON.stringify(s),_=y.length>5e3?{_truncated:true,_originalSize:y.length,text:y.slice(0,5e3)}:s,ze=Date.now()-a.timestamp;await this.telemetry.completeEvent({eventId:a.eventId,sessionId:i,output:_,duration:ze,completedAt:Date.now()})&&this.noteTelemetryOperation();}let c=typeof s=="object"&&s!==null?s:null,d=c?.exitCode,l=c?.stderr,f=/^\s*(ls|cat|pwd|cd|echo|head|tail|wc|which|whoami|date|env|printenv|id|hostname|uname)\b/,h=o.command||"",p=JSON.stringify(s),u=Buffer.byteLength(p,"utf8"),m=this.countResults(s),g,v,w=true;if(n.startsWith("mcp__"))g="mcp_call",v={mcpTool:n.replace(/^mcp__[^_]+__/,""),query:o.query??null,resultCount:m,resultSizeBytes:u};else if(n==="Read"||n==="Write"||n==="Edit")g=n==="Read"?"file_read":"file_write",v={filePath:o.file_path??null,fileContentSize:u};else if(n==="Bash"){let y=f.test(h),_=d!==void 0&&d!==0;w=!y||_,g=_?"bash_error":"bash_command",v={command:h||n,exitCode:d??null,stderr:l??null};}else n==="Agent"?(g="subagent",v={subagentType:o.subagent_type??null,description:typeof o.description=="string"?o.description.slice(0,200):null}):n==="WebSearch"||n==="WebFetch"?(g=n==="WebSearch"?"web_search":"web_fetch",v={query:typeof o.query=="string"?o.query.slice(0,200):null}):(w=false,g="tool_use",v={});if(w){let y={id:t.tool_use_id?`memory:${k(i,t.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:i,tool:n,kind:g,payload:v,command:h||void 0,exitCode:d,stderr:l??void 0,durationMs:0,createdAt:Date.now()};await this.postMemoryEvent(y);}let S=this.enforcePostToolUse(n);return S?(console.error("[devflow-daemon] Enforcement:",S),{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:JSON.stringify(S)}}):null}async handlePostToolUseFailure(e){let t;try{t=JSON.parse(e);}catch{return null}let n=this.trackSession(t.session_id),o=t.tool_name??"unknown",s=t.error??`${o} failed`,i=this.popEventFromMap(o,n,t.tool_use_id);if(i)await this.telemetry.completeEvent({eventId:i.eventId,sessionId:n,error:s,duration:Date.now()-i.timestamp,completedAt:Date.now()})&&this.noteTelemetryOperation();else {let a=k(n,t.tool_use_id);await this.telemetry.sendEvent({eventId:a,executionId:this.runtimeStore.get(n)?.executionId??n,sessionId:n,projectRoot:this.projectRoot,toolUseId:t.tool_use_id,timestamp:Date.now(),toolName:o,toolType:o.startsWith("mcp__")?"mcp":"direct",isMcpTool:o.startsWith("mcp__"),mcpToolName:o.startsWith("mcp__")?o.replace(/^mcp__[^_]+__/,""):void 0,mcpEnforced:false,mcpFallback:false,kind:"error",input:t.tool_input??{},duration:0,error:s,blocked:false});}return await this.postMemoryEvent({id:t.tool_use_id?`memory:${k(n,t.tool_use_id)}`:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:n,tool:o,command:typeof t.tool_input?.command=="string"?t.tool_input.command:o,exitCode:-1,stderr:s,durationMs:i?Date.now()-i.timestamp:0,createdAt:Date.now(),kind:o==="Bash"?"bash_error":"tool_use",payload:{command:t.tool_input?.command??o,exitCode:-1,stderr:s}}),null}countResults(e){if(!e)return 0;let t=e;if(typeof e=="string")try{t=JSON.parse(e);}catch{return 1}let n=t,o=["files","results","data","result","memories","nodes","chunks","findings","symbols"],s=n.data??n.structuredContent??n;if(Array.isArray(s))return s.length;if(typeof s=="object"&&s!==null){let i=s,a=0;for(let c of o)Array.isArray(i[c])&&(a+=i[c].length);for(let[,c]of Object.entries(i))c&&typeof c=="object"&&!Array.isArray(c)&&(a+=this.countResults(c));return a>0?a:Object.keys(i).length>0?1:0}return 0}async postMemoryEvent(e){try{await(await this.getMemoryGate()).recordEvent(e);}catch(t){console.error("[devflow-daemon] Local memory event write failed:",t.message);}we(`/api/memory/session-events?rootPath=${encodeURIComponent(this.projectRoot)}`,e);}async getMemoryGate(){let e=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);return this.memoryWarmup??=e.forceWarmUp().catch(t=>{throw this.memoryWarmup=null,t}),await this.memoryWarmup,e}async handleUserPromptSubmit(e){try{let t=JSON.parse(e),n=typeof t.prompt=="string"?t.prompt:"",o=typeof t.session_id=="string"&&t.session_id.trim()?this.trackSession(t.session_id):null,s=He(n);if(o&&s&&this.startSkillExecution(o,s.skillName),n.trim()){let i=$e(n);i&&Je(this.projectRoot,{content:i,sessionId:o??void 0,createdAt:Date.now()}),o&&await(await this.getMemoryGate()).recordUserMessage(n.slice(0,2e3),o,n.slice(0,200));}}catch{}return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow"}}}async handlePreCompact(e){let t;try{let i=JSON.parse(e);typeof i.session_id=="string"&&i.session_id.trim()&&(t=i.session_id.trim());}catch{}await this.flushTelemetry(),this.startExplicitIntentFlush(),await this.explicitIntentFlush;let n=await this.getMemoryGate(),o=await N({projectRoot:this.projectRoot,sessionId:t,trigger:"pre_compact",memory:n}),s=X(o);return {hookSpecificOutput:{hookEventName:"PreCompact",...s?{additionalContext:s}:{}}}}noteTelemetryOperation(){this.successfulTelemetryOperations++,this.successfulTelemetryOperations>=Yn&&this.flushTelemetry();}async flushTelemetry(){this.successfulTelemetryOperations=0,await this.telemetry.flushAndAggregate();}startExplicitIntentFlush(){this.explicitIntentFlush||(this.explicitIntentFlush=this.flushExplicitMemoryIntents().finally(()=>{this.explicitIntentFlush=null;}));}async handleStop(e){let t=null;try{let n=JSON.parse(e);typeof n.session_id=="string"&&n.session_id.trim()&&(t=n.session_id.trim());}catch{}if(t??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null,t){let n=this.runtimeStore.completeExecution(t);n?.executionId&&(await this.telemetry.sendExecutionComplete(n.executionId),this.deleteContextReceipt(t,n.executionId));}this.startExplicitIntentFlush(),await this.explicitIntentFlush;}async flushExplicitMemoryIntents(){this.flushTelemetry();let e=Ge(this.projectRoot);if(e)try{let t=this.explicitMemoryGate??=new MemoryGate(this.projectRoot);for(await t.forceWarmUp();e.intents.length>0;){let n=e.intents[0];await t.saveExplicitMemoryIntent(n.content,n.sessionId),We(e);}}catch(t){console.error("[devflow-daemon] Explicit memory intent save failed:",t.message);}}deleteContextReceipt(e,t){let n;try{n=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),n.deleteContextReceipt(this.projectRoot,e,t);}catch{}finally{n?.close();}}async handleMemorySnapshot(){let e=loadConfig(this.projectRoot).sessionStart?.injectMemories??true;if(e===false)return {status:"ok",enabled:false,markdown:""};let t=typeof e=="object"?e.topN:void 0,n=typeof e=="object"?e.budgetTokens:void 0,o=Number.isFinite(t)?Math.max(0,Math.floor(t)):10,s=Number.isFinite(n)?Math.max(1,Math.floor(n)):800;try{let c={...await(this.explicitMemoryGate??=new MemoryGate(this.projectRoot)).getAll({purpose:"session_bootstrap",budgetTokens:s,limit:o}),_devflow_unique:{memory_version:1,structured_storage:!0,project_context_included:!0},_accuracy:{data_freshness_ms:0,source_layer:"memory",degradation:"none"}};if(c.memories.length===0)return {status:"ok",enabled:!0,markdown:`## Project memory
|
|
10
|
+
\u672C\u9879\u76EE\u6682\u65E0\u8BB0\u5FC6`};let d=c.memories.map(l=>`- **${l.title||l.type}**: ${l.content} (confidence ${l.confidence.toFixed(2)}, ${l.source})`);return {status:"ok",enabled:!0,markdown:`## Project memory (auto-injected, ${c.memories.length} items, ${c.tokenCount} tokens)
|
|
11
11
|
${d.join(`
|
|
12
12
|
`)}`}}catch(i){return console.error("[devflow-daemon] Memory snapshot failed:",i.message),{status:"degraded",enabled:true,markdown:`## Project memory
|
|
13
|
-
\u672C\u9879\u76EE\u6682\u65E0\u8BB0\u5FC6`}}}async handleSessionEnd(e){let t=null;try{let
|
|
14
|
-
`);}};if(process.env.DEVFLOW_HOOK_DAEMON_DISABLE_AUTOSTART!=="1"){let r=process.argv[2]||process.env.CLAUDE_PROJECT_DIR||process.cwd(),e=new
|
|
13
|
+
\u672C\u9879\u76EE\u6682\u65E0\u8BB0\u5FC6`}}}async handleSessionEnd(e){let t=null;try{let i=JSON.parse(e);typeof i.session_id=="string"&&i.session_id.trim()&&(t=i.session_id.trim());}catch{}t??=this.activeSessionIds.size===1?[...this.activeSessionIds][0]:null;let n=t===null?this.activeSessionIds.size<=1:this.activeSessionIds.size<=1&&this.activeSessionIds.has(t);this.startExplicitIntentFlush(),await this.explicitIntentFlush;let o=await this.getMemoryGate(),s=t?this.runtimeStore.get(t)?.executionId:void 0;s&&await this.telemetry.sendExecutionComplete(s),t&&this.deleteContextReceipt(t,s),await Q(e,this.projectRoot,n,{telemetry:this.telemetry,memory:o}),t&&(this.serverManager.removeRef(t),this.activeSessionIds.delete(t),this.eventMap=this.eventMap.filter(i=>i.sessionId!==t),this.runtimeStore.removeSession(t)),this.activeSessionIds.size===0?setImmediate(()=>{this.shutdown();}):this.resetIdleTimer();}shutdown(){return this.shutdownPromise?this.shutdownPromise:(this.shutdownPromise=this.performShutdown(),this.shutdownPromise)}async performShutdown(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.telemetryFlushTimer&&(clearInterval(this.telemetryFlushTimer),this.telemetryFlushTimer=null),await this.flushTelemetry(),await this.closeServer(),this.cleanupOwnedResources(),await this.serverManager.stop(),await this.explicitIntentFlush,this.explicitMemoryGate?.close(),this.explicitMemoryGate=null,this.telemetry.close(),process.exit(0);}closeServer(){let e=this.server;return !e||!e.listening||!this.pathMatchesIdentity(this.socketPath,this.socketIdentity)?Promise.resolve():(this.server=null,new Promise(t=>{let n=false,o=()=>{n||(n=true,clearTimeout(s),t());},s=setTimeout(o,Bn);e.close(o);}))}cleanupOwnedResources(){try{Fe(this.projectRoot,process.pid);}catch(e){console.error("[devflow-daemon] Failed to unregister:",e.message);}this.removePathIfOwned(this.socketPath,this.socketIdentity,"socket"),this.removePathIfOwned(this.pidPath,this.pidIdentity,"PID file",`${process.pid}
|
|
14
|
+
`);}};if(process.env.DEVFLOW_HOOK_DAEMON_DISABLE_AUTOSTART!=="1"){let r=process.argv[2]||process.env.CLAUDE_PROJECT_DIR||process.cwd(),e=new oe(r,process.argv[3]);process.once("SIGTERM",()=>{e.shutdown();}),process.once("SIGINT",()=>{e.shutdown();}),e.start().catch(t=>{console.error("[devflow-daemon] Failed to start:",t),process.exit(1);});}export{oe as HookDaemon,Zn as injectProjectRootIfMissing};
|