@devflow-tools/cli 0.15.0 → 0.16.1
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/benchmark-cmd.d.ts +17 -4
- package/dist/commands/benchmark-cmd.d.ts.map +1 -1
- package/dist/commands/benchmark-cmd.js +71 -14
- package/dist/commands/benchmark-cmd.js.map +1 -1
- package/dist/commands/connect.d.ts +0 -1
- package/dist/commands/connect.d.ts.map +1 -1
- package/dist/commands/connect.js +4 -10
- package/dist/commands/connect.js.map +1 -1
- package/dist/commands/context.d.ts +2 -2
- package/dist/commands/context.d.ts.map +1 -1
- package/dist/commands/context.js +5 -3
- package/dist/commands/context.js.map +1 -1
- package/dist/commands/db.d.ts +25 -0
- package/dist/commands/db.d.ts.map +1 -0
- package/dist/commands/db.js +258 -0
- package/dist/commands/db.js.map +1 -0
- package/dist/commands/docs.d.ts +20 -0
- package/dist/commands/docs.d.ts.map +1 -0
- package/dist/commands/docs.js +37 -0
- package/dist/commands/docs.js.map +1 -0
- package/dist/commands/doctor.d.ts +59 -1
- package/dist/commands/doctor.d.ts.map +1 -1
- package/dist/commands/doctor.js +3912 -50
- package/dist/commands/doctor.js.map +1 -1
- package/dist/commands/index-cmd.d.ts +1 -0
- package/dist/commands/index-cmd.d.ts.map +1 -1
- package/dist/commands/index-cmd.js +7 -0
- package/dist/commands/index-cmd.js.map +1 -1
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +3 -6
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/knowledge.d.ts +2 -1
- package/dist/commands/knowledge.d.ts.map +1 -1
- package/dist/commands/knowledge.js +11 -8
- package/dist/commands/knowledge.js.map +1 -1
- package/dist/commands/memory.d.ts +17 -1
- package/dist/commands/memory.d.ts.map +1 -1
- package/dist/commands/memory.js +22 -3
- package/dist/commands/memory.js.map +1 -1
- package/dist/commands/plugin-loader.d.ts +1 -1
- package/dist/commands/plugin-loader.d.ts.map +1 -1
- package/dist/commands/plugin-loader.js +1 -1
- package/dist/commands/plugin-loader.js.map +1 -1
- package/dist/commands/plugin-memory-hints.d.ts +23 -0
- package/dist/commands/plugin-memory-hints.d.ts.map +1 -0
- package/dist/commands/plugin-memory-hints.js +58 -0
- package/dist/commands/plugin-memory-hints.js.map +1 -0
- package/dist/commands/reset.d.ts +32 -0
- package/dist/commands/reset.d.ts.map +1 -0
- package/dist/commands/reset.js +316 -0
- package/dist/commands/reset.js.map +1 -0
- package/dist/commands/server.js +1 -1
- package/dist/commands/session.d.ts.map +1 -1
- package/dist/commands/session.js +2 -1
- package/dist/commands/session.js.map +1 -1
- package/dist/commands/start.js +1 -1
- package/dist/commands/status.d.ts.map +1 -1
- package/dist/commands/status.js +33 -6
- package/dist/commands/status.js.map +1 -1
- package/dist/index.js +225 -96
- package/dist/index.js.map +1 -1
- package/dist/lib/plugin-setup.d.ts +3 -4
- package/dist/lib/plugin-setup.d.ts.map +1 -1
- package/dist/lib/plugin-setup.js +165 -19
- 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/command-registry.json +34 -36
- package/dist/plugin-files/dist/hooks/enforcer-summary.js +6 -0
- package/dist/plugin-files/dist/hooks/hook-client.js +6 -0
- package/dist/plugin-files/dist/hooks/hook-daemon.js +14 -0
- package/dist/plugin-files/dist/hooks/post-tool-use-failure.js +2 -0
- package/dist/plugin-files/dist/hooks/post-tool-use.js +3 -0
- package/dist/plugin-files/dist/hooks/pre-compact.js +3 -0
- package/dist/plugin-files/dist/hooks/pre-tool-use.js +2 -0
- package/dist/plugin-files/dist/hooks/server-bootstrap.js +109 -0
- package/dist/plugin-files/dist/hooks/session-end.js +2 -0
- package/dist/plugin-files/dist/hooks/stop.js +2 -0
- package/dist/plugin-files/dist/hooks/user-prompt-submit.js +2 -0
- package/dist/plugin-files/dist/skills/devflow:graphql/SKILL.md +2 -4
- package/dist/plugin-files/dist/skills/devflow:nest/SKILL.md +4 -4
- package/dist/plugin-files/dist/skills/devflow:nextjs/SKILL.md +4 -4
- package/dist/plugin-files/dist/skills/devflow:react/SKILL.md +6 -8
- package/dist/plugin-files/dist/skills/devflow:tailwind/SKILL.md +4 -2
- package/dist/plugin-files/dist/skills/devflow:vue/SKILL.md +2 -4
- package/dist/plugin-files/hooks/post-tool-use +2 -2
- package/dist/plugin-files/hooks/post-tool-use-failure +2 -2
- package/dist/plugin-files/hooks/pre-compact +2 -2
- package/dist/plugin-files/hooks/pre-tool-use +4 -4
- package/dist/plugin-files/hooks/session-end +2 -2
- package/dist/plugin-files/hooks/session-start +160 -77
- package/dist/plugin-files/hooks/stop +2 -8
- package/dist/plugin-files/hooks/user-prompt-submit +2 -2
- package/dist/plugin-files/package.json +15 -2
- package/dist/plugin-files/skills/devflow/SKILL.md +20 -0
- package/dist/plugin-files/skills/devflow:animation/SKILL.md +38 -0
- package/dist/plugin-files/skills/devflow:context/SKILL.md +63 -0
- package/dist/plugin-files/skills/devflow:css/SKILL.md +38 -0
- package/dist/plugin-files/skills/devflow:docker/SKILL.md +42 -0
- package/dist/plugin-files/skills/devflow:doctor/SKILL.md +17 -0
- package/dist/plugin-files/skills/devflow:electron/SKILL.md +42 -0
- package/dist/plugin-files/skills/devflow:git/SKILL.md +42 -0
- package/dist/plugin-files/skills/devflow:graph/SKILL.md +55 -0
- package/dist/plugin-files/skills/devflow:graphql/SKILL.md +41 -0
- package/dist/plugin-files/skills/devflow:knowledge/SKILL.md +55 -0
- package/dist/plugin-files/skills/devflow:memory/SKILL.md +54 -0
- package/dist/plugin-files/skills/devflow:nest/SKILL.md +41 -0
- package/dist/plugin-files/skills/devflow:nextjs/SKILL.md +38 -0
- package/dist/plugin-files/skills/devflow:performance/SKILL.md +42 -0
- package/dist/plugin-files/skills/devflow:react/SKILL.md +50 -0
- package/dist/plugin-files/skills/devflow:start/SKILL.md +50 -0
- package/dist/plugin-files/skills/devflow:tailwind/SKILL.md +38 -0
- package/dist/plugin-files/skills/devflow:taro/SKILL.md +41 -0
- package/dist/plugin-files/skills/devflow:ui-layout/SKILL.md +38 -0
- package/dist/plugin-files/skills/devflow:vue/SKILL.md +45 -0
- package/dist/plugin-files/skills/devflow:workflow/SKILL.md +55 -0
- package/package.json +27 -27
- package/dist/commands/dashboard.d.ts +0 -3
- package/dist/commands/dashboard.d.ts.map +0 -1
- package/dist/commands/dashboard.js +0 -10
- package/dist/commands/dashboard.js.map +0 -1
|
@@ -0,0 +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 Ye(r,e){let t=ze(r);mkdirSync$1(dirname$1(t),{recursive:true}),appendFileSync(t,`${JSON.stringify(e)}
|
|
4
|
+
`,{mode:384});}function Xe(r){let e=ze(r),t=`${e}.claim-`,n=`${basename(e)}.claim-`,o=(()=>{try{return readdirSync$1(dirname$1(e)).filter(c=>c.startsWith(n)&&!c.includes(".tmp-")).sort()[0]}catch{return}})(),s=o?join$1(dirname$1(e),o):`${t}${Date.now()}-${process.pid}`;if(!o)try{renameSync(e,s);}catch{return null}let i=Pn(s);if(i.length===0){try{unlinkSync$1(s);}catch{}return null}return {path:s,intents:i}}function Qe(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
|
+
`)+`
|
|
6
|
+
`,{mode:384}),renameSync(e,r.path);}var Bn=600*1e3,Kn=2e3,Vn=250,zn=2e3,Yn=1e3,Ze=1024*1024,Xn=2*1024*1024,Qn=6e4,Zn=100,er={Agent:"get_project_context",Bash:"get_project_context",Glob:"get_project_context",Grep:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function tr(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 ie(r){return typeof r=="string"&&r.trim().length>0}function nr(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(ie(o.projectRoot))return o;let s=ie(t.CLAUDE_PROJECT_DIR)?t.CLAUDE_PROJECT_DIR:n;return ie(s)&&(o.projectRoot=s),o}var ae=class{constructor(e,t){this.socketIdentity=null;this.pidIdentity=null;this.server=null;this.sessionId=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.projectName=e.split("/").pop()||"unknown",this.socketPath=getDaemonSocketPath(e),this.pidPath=getDaemonPidPath(e),this.telemetry=new R,this.skillManager=new C(this.projectRoot),this.serverManager=new O(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();},Qn),this.telemetryFlushTimer.unref(),this.resetIdleTimer();}handleConnection(e){let t="",n=false,o=false,s=0,i=Promise.resolve();e.setEncoding("utf8");let c=()=>{o||(o=true,clearTimeout(a),e.destroy());},a=setTimeout(()=>{c();},Kn).unref(),d=async l=>{if(!o){o=true,clearTimeout(a);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")>Ze){c();return}if(f.length===0)return;let h=0;for(let u of f){let p=Buffer.byteLength(u,"utf8");if(p>Ze){c();return}h+=p+1;}if(s+h>Xn){c();return}s+=h,i=i.then(async()=>{for(let u of f){if(o)return;if(!n){let p;try{p=JSON.parse(u);}catch{await d({error:"handshake_invalid"});return}if(p?.type!=="hello"||typeof p.rootPath!="string"){await d({error:"handshake_invalid"});return}if(p.rootPath!==this.projectRoot){await d({error:"handshake_root_mismatch",expected:this.projectRoot});return}n=true,clearTimeout(a),this.resetIdleTimer();continue}if(u.trim())try{let p=JSON.parse(u),m=await this.handleRequest(p);m!==null&&!o&&await this.writeFrame(e,m);}catch(p){o||await this.writeFrame(e,{error:p.message});}}}).catch(()=>{c();}).finally(()=>{s-=h;});}),e.on("close",()=>clearTimeout(a)),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,c=false,a=setTimeout(()=>{e.destroy(),l(new Error("Timed out writing daemon response"));},Yn),d=()=>{clearTimeout(a),e.off("close",f),e.off("error",h),e.off("drain",u);},l=m=>{c||!m&&(!s||!i)||(c=true,d(),m?o(m):n());},f=()=>l(new Error("Socket closed during write")),h=m=>l(m),u=()=>{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",u));})}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}`));},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=a.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, ${a.memories.length} items, ${a.tokenCount} tokens)
|
|
11
|
+
${d.join(`
|
|
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 s=JSON.parse(e);typeof s.session_id=="string"&&s.session_id.trim()&&(t=s.session_id.trim());}catch{}t??=this.sessionId;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();await ne(e,this.projectRoot,n,{telemetry:this.telemetry,memory:o}),t&&(this.serverManager.removeRef(t),this.activeSessionIds.delete(t),this.eventMap=this.eventMap.filter(s=>s.sessionId!==t)),this.sessionId=[...this.activeSessionIds].at(-1)??null,this.activeSessionIds.size===0&&setImmediate(()=>{this.shutdown();});}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,zn);e.close(o);}))}cleanupOwnedResources(){try{Ge(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 ae(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{ae as HookDaemon,nr as injectProjectRootIfMissing};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {request}from'http';import {getLocalApiKey}from'@devflow-tools/sdk/auth';import {classifyWorkflowFailure}from'@devflow-tools/workflow-engine/failure-classifier';import {existsSync,readdirSync,readFileSync,unlinkSync,mkdirSync,writeFileSync}from'fs';import {join}from'path';import {homedir}from'os';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {getLocalApiKey as getLocalApiKey$1}from'@devflow-tools/sdk';var _=1e4,F=3e4,m=500;function k(s,t,e){return new Promise(r=>{try{let n=new URL(s),o=request({hostname:n.hostname,port:n.port||80,path:n.pathname+n.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":e,"Content-Length":Buffer.byteLength(t)},timeout:5e3},i=>{let l=[];i.on("data",a=>l.push(a)),i.on("end",()=>{let a=Buffer.concat(l).toString();r(i.statusCode!=null&&i.statusCode>=200&&i.statusCode<300?a:null);});});o.on("error",()=>r(null)),o.on("timeout",()=>{o.destroy(),r(null);}),o.write(t),o.end();}catch{r(null);}})}var h=class{constructor(t){this.retryScheduled=false;this.apiUrl=t?.apiUrl??process.env.DEVFLOW_API_URL??"http://127.0.0.1:13337",this.apiKey=t?.apiKey??getLocalApiKey$1(),this.cacheDir=t?.cacheDir??join(process.env.DEVFLOW_STATE_DIR??join(homedir(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=t?.legacyCacheDir??(t?.cacheDir?null:join(homedir(),".devflow","telemetry-cache")),this.database=t?.database??null,this.ownsDatabase=!t?.database;}async sendEvent(t){let e={...t,input:this.truncateInput(t.input)};return this.commitOrCache("tool_call",e)?(this.postHttp("/api/telemetry/tool-call",e),t.eventId):null}async sendExecutionStart(t,e,r,n){let o={executionId:t,sessionId:e,skillName:r,startedAt:n};this.commitOrCache("execution_start",o)&&this.postHttp("/api/telemetry/skill-execution/start",o);}async sendSessionStart(t,e,r){let n={id:t,projectRoot:e,startedAt:r,label:e.split("/").pop()??"unknown"},o=this.commitOrCache("session_start",n);return o&&this.postHttp("/api/telemetry/sessions",n),o}async completeEvent(t){let e=this.commitOrCache("complete_event",t);return e&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp("/api/telemetry/tool-call/output",t)),e}async endSession(t,e=Date.now()){let r={sessionId:t,finishedAt:e},n=this.commitOrCache("session_end",r);return n&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:e})),n}async flushCache(){try{let r=this.getDatabase(),n=r.listTelemetryFailures({unresolvedOnly:!0,limit:m}).reverse();for(let o of n)try{this.applyOperation(o.operation,o.payload),r.resolveTelemetryFailure(o.id);}catch{}r.trimTelemetryFailures(m);}catch{}let e=[...new Set([this.cacheDir,this.legacyCacheDir].filter(r=>!!r))].filter(r=>existsSync(r)).flatMap(r=>readdirSync(r).filter(n=>n.endsWith(".json")).map(n=>{let o=join(r,n);try{return {cacheFile:o,envelope:A(JSON.parse(readFileSync(o,"utf8")),n)}}catch{return null}})).filter(r=>r!==null).sort((r,n)=>r.envelope.timestamp-n.envelope.timestamp||E(r.envelope.operation)-E(n.envelope.operation));for(let{cacheFile:r,envelope:n}of e)try{let o=this.getDatabase();o.insertTelemetryFailure({id:n.id,operation:n.operation,payload:n.payload,error:n.failure,createdAt:n.timestamp}),this.applyOperation(n.operation,n.payload),o.resolveTelemetryFailure(n.id),unlinkSync(r);}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(t,e){try{return this.applyOperation(t,e),!0}catch(r){return this.cacheOperation(t,e,r),false}}applyOperation(t,e){let r=this.getDatabase();switch(t){case "tool_call":r.insertToolCallEvent(e);return;case "execution_start":r.insertSkillExecution({executionId:e.executionId,sessionId:e.sessionId,skillName:e.skillName,startedAt:e.startedAt,status:"running"});return;case "session_start":r.insertSession(e),r.insertRun({id:T(e.id),source:"hook",tool:"session",input:{projectRoot:e.projectRoot},status:"active",startedAt:e.startedAt,tokenUsed:0,metadata:{sessionId:e.id,projectRoot:e.projectRoot}});return;case "complete_event":if(!r.updateToolCallEvent(e.eventId,{output:e.output===void 0?void 0:JSON.stringify(e.output),error:e.error,duration:e.duration}))throw new Error(`Tool call event ${e.eventId} is not available for completion`);return;case "session_end":r.closeSession(e.sessionId,e.finishedAt),r.updateRun(T(e.sessionId),{status:"completed",finishedAt:e.finishedAt});return}}cacheOperation(t,e,r){let n=Date.now(),o={id:`failure:${n}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:e,failure:r instanceof Error?r.message:String(r),timestamp:n};try{let i=this.getDatabase();i.insertTelemetryFailure({id:o.id,operation:t,payload:e,error:o.failure,createdAt:n}),i.trimTelemetryFailures(m),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let i=join(this.cacheDir,`${n}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(i,JSON.stringify(o,null,2),{mode:384}),this.trimCompatibilityCache(),this.scheduleRetry();}catch{}}trimCompatibilityCache(){try{let t=readdirSync(this.cacheDir).filter(e=>e.endsWith(".json")).sort();for(let e of t.slice(0,Math.max(0,t.length-m)))unlinkSync(join(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},F).unref());}postHttp(t,e){k(`${this.apiUrl}${t}`,JSON.stringify(e),this.apiKey);}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=_?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,_)}...`}}};function E(s){return ["session_start","execution_start","tool_call","complete_event","session_end"].indexOf(s)}function T(s){return `hook-run:${s}`}function A(s,t){if(!s||typeof s!="object")throw new Error("Invalid telemetry cache envelope");let e=s;if(typeof e.operation=="string"&&e.payload!==void 0)return e;let r=e.type==="tool_call"?"tool_call":e.type==="execution_start"?"execution_start":null;if(!r)throw new Error("Unknown legacy telemetry cache operation");let n=e.payload??{},o=Number(n.timestamp??n.startedAt??Date.now());return {id:`legacy-cache:${t}`,operation:r,payload:n,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:o}}var L=process.env.DEVFLOW_SERVER_URL||"http://127.0.0.1:13337",N=getLocalApiKey(),w=process.env.CLAUDE_PROJECT_DIR||process.cwd();function y(s,t){let e=Number(s);return Number.isInteger(e)&&e>=0?e:t}function $(s,t,e){return new Promise((r,n)=>{let o=JSON.stringify(t),i=new URL(s,L),l=false,a=c=>{l||(l=true,c?n(c):r());},d=request({hostname:i.hostname,port:i.port,path:i.pathname+i.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":N,"Content-Length":Buffer.byteLength(o)},timeout:e},c=>{c.on("error",a),c.on("end",()=>{let u=c.statusCode??0;if(u<200||u>=300){a(new Error(`HTTP ${u}`));return}a();}),c.resume();});d.on("error",a),d.on("timeout",()=>{d.destroy(new Error(`PostToolUseFailure request timed out after ${e}ms`));}),d.write(o),d.end();})}function j(s){return new Promise(t=>setTimeout(t,s))}async function W(s,t){let e=t.timeoutMs??y(process.env.DEVFLOW_FAILURE_TIMEOUT_MS,1500),r=t.maxRetries??y(process.env.DEVFLOW_FAILURE_MAX_RETRIES,2),n=t.retryDelayMs??y(process.env.DEVFLOW_FAILURE_RETRY_DELAY_MS,100),o=`/api/memory/session-events?rootPath=${encodeURIComponent(w)}`;for(let i=0;i<=r;i+=1)try{await $(o,s,e);return}catch(l){if(i===r)throw l;await j(n*2**i);}}async function K(s,t={}){let e;try{e=JSON.parse(s);}catch{return}let r=e.tool_name||"",n=e.tool_input||{},o=e.error||"",i=classifyWorkflowFailure({stepId:r,toolName:r,error:new Error(o||`${r||"tool"} failed`),errorStack:o||void 0}),l=typeof n=="object"&&n.command?n.command:r,a={id:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:e.session_id??`session:${w.split("/").pop()||"default"}`,tool:r,command:l,exitCode:-1,stderr:o,durationMs:0,createdAt:Date.now(),kind:r==="Bash"?"bash_error":"tool_use",payload:{command:l,exitCode:-1,stderr:o,failureSource:"PostToolUseFailure",failureCategory:i.category}},d=!t.telemetryClient,c=t.telemetryClient??new h,u=r.startsWith("mcp__"),D={eventId:a.id,executionId:a.sessionId,sessionId:a.sessionId,timestamp:a.createdAt,toolName:r,toolType:u?"mcp":"direct",isMcpTool:u,mcpToolName:u?r:void 0,mcpEnforced:u,mcpFallback:false,kind:"error",input:n,duration:0,error:o,blocked:false,failureCategory:i.category};try{await c.sendEvent(D);}finally{d&&c.close();}t.eventDelivery?await t.eventDelivery(a):await W(a,t);}if(process.argv[1]?.endsWith("post-tool-use-failure")||process.argv[1]?.endsWith("post-tool-use-failure.js")){let s="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{s+=t;}),process.stdin.on("end",()=>{K(s.trim()||process.argv[2]||"").catch(t=>{console.error("[devflow] PostToolUseFailure delivery failed:",t.message),process.exitCode=1;});}),process.stdin.on("error",t=>{console.error("[devflow] PostToolUseFailure input failed:",t.message),process.exitCode=1;});}
|
|
2
|
+
export{K as handlePostToolUseFailure};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {existsSync,readFileSync,writeFileSync,readdirSync,unlinkSync,mkdirSync,appendFileSync}from'fs';import {join,dirname}from'path';import {createHash}from'crypto';import {getLogWriter}from'@devflow-tools/telemetry';import {request}from'http';import {homedir}from'os';import {getLocalApiKey,getProjectStateDir}from'@devflow-tools/sdk';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {fileURLToPath}from'url';import {MemoryGate}from'@devflow-tools/memory-engine';function q(n,e,t){try{let r=openGlobalDevFlowDatabase();try{r.insertEvent({kind:n,timestamp:Date.now(),duration:t,success:e.success!==!1,metadata:e});}finally{r.close();}}catch{}}var M=process.env.DEVFLOW_SERVER_URL||"http://127.0.0.1:13337",ve=getLocalApiKey(),we=8,_e=6e4,G=new Map;function Re(n){let e=new URL(n,M).pathname,t=G.get(e);return t||(t={failures:0,lastFailure:0,openUntil:0,status:"closed"},G.set(e,t)),t}function j(n,e,t){if(e.status===t)return;let r=e.status;e.status=t,q("http_circuit_transition",{path:new URL(n,M).pathname,previous:r,status:t,failures:e.failures,openUntil:e.openUntil});}function A(n,e){e.failures++,e.lastFailure=Date.now(),e.failures>=we&&(e.openUntil=Date.now()+_e,j(n,e,"open"));}function Ce(n,e){let t=e.status!=="closed";e.failures=0,e.openUntil=0,t&&j(n,e,"closed");}var F=join(homedir(),".devflow","errors");function J(n,e){try{existsSync(F)||mkdirSync(F,{recursive:!0});let t=`${new Date().toISOString()} | ${n} | ${e?.message??String(e)}
|
|
2
|
+
`;appendFileSync(join(F,"http-errors.log"),t);}catch{}}function K(n,e,t={}){let r=t.timeout??5e3,o=t.maxRetries??2,s=t.circuitBreaker??true,i=Re(n);if(s&&i.openUntil>Date.now())return Promise.resolve();s&&i.status==="open"&&j(n,i,"half_open");let c=l=>new Promise(a=>{let v=JSON.stringify(e),m=new URL(n,M),f=request({hostname:m.hostname,port:m.port,path:m.pathname+m.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":ve,"Content-Length":Buffer.byteLength(v)},timeout:r},g=>{if(g.resume(),g.statusCode&&g.statusCode>=400){let y=new Error(`HTTP ${g.statusCode}`);if(J(n,y),l>0){let w=Math.min(1e3*Math.pow(2,o-l),8e3);setTimeout(()=>{c(l-1).then(a);},w);}else A(n,i),a();return}Ce(n,i),a();});f.on("error",g=>{if(J(n,g),l>0){let y=Math.min(1e3*Math.pow(2,o-l),8e3);setTimeout(()=>{c(l-1).then(a);},y);}else A(n,i),a();}),f.on("timeout",()=>{f.destroy(),l>0?c(l-1).then(a):(A(n,i),a());}),f.write(v),f.end();});return c(o)}function P(n){return n??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function d(n){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(P(n))}function C(n){if(!n||typeof n!="object"||Array.isArray(n))return {};let e=n,t={};for(let r of ["lastMcpCall","bypassCount"])if(r in e){let o=e[r];if(o==null)continue;t[r]=typeof o=="number"&&Number.isFinite(o)&&o>=0?o:0;}return t}function ke(n,e){return n.lastMcpCall===e.lastMcpCall&&n.bypassCount===e.bypassCount}function Ee(n){try{return existsSync(n)?C(JSON.parse(readFileSync(n,"utf-8"))):{}}catch{return {}}}function X(n,e){let t=e instanceof Error?e.message:String(e);console.error(`[devflow] Receipt ${n} skipped: ${t}`);}function V(n){let e=d(n);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 Z(n,e){if(n.getHookReceipt(e)){V(e);return}let t=join(d(e),"receipt.json");if(!existsSync(t))return;let r=Ee(t);n.updateHookReceipt(e,()=>r),V(e);}function Q(n,e,t){let r;try{r=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),Z(r,n);let o={},s=r.updateHookReceipt(n,c=>(o=C(c),C(e(o)))),i=C(s);return {receipt:i,applied:!0,changed:!ke(o,i)}}catch(o){return X(t,o),{receipt:{},applied:false,changed:false}}finally{try{r?.close();}catch{}}}function Te(n){let e;try{return e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),Z(e,n),C(e.getHookReceipt(n))}catch(t){return X("update",t),{}}finally{try{e?.close();}catch{}}}function N(n,e){return Q(n,()=>e,"write").applied}function U(n,e){return Q(n,e,"update")}var xe={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function Oe(n){switch(n){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var k=class{constructor(e){this.projectRoot=e;}getPhase(){let t=Te(this.projectRoot).lastMcpCall??0;if(Math.floor(Date.now()/1e3)-t<30)return "context_ready";let o=join(d(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 r=this.getPhase();if(t||e==="Skill")return {permissionDecision:"allow"};if(r==="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(r==="context_ready")return {permissionDecision:"allow"};let o=xe[e];if(!o)return {permissionDecision:"allow"};let s=U(this.projectRoot,l=>({...l,bypassCount:(l.bypassCount??0)+1}));if(!s.applied)return {permissionDecision:"allow"};let i=s.receipt.bypassCount??0,c=Oe(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(){N(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}};var oe=1e4,Ne=3e4,T=500;function Ue(n,e,t){return new Promise(r=>{try{let o=new URL(n),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",l=>c.push(l)),i.on("end",()=>{let l=Buffer.concat(c).toString();r(i.statusCode!=null&&i.statusCode>=200&&i.statusCode<300?l:null);});});s.on("error",()=>r(null)),s.on("timeout",()=>{s.destroy(),r(null);}),s.write(e),s.end();}catch{r(null);}})}var x=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,r,o){let s={executionId:e,sessionId:t,skillName:r,startedAt:o};this.commitOrCache("execution_start",s)&&this.postHttp("/api/telemetry/skill-execution/start",s);}async sendSessionStart(e,t,r){let o={id:e,projectRoot:t,startedAt:r,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 r={sessionId:e,finishedAt:t},o=this.commitOrCache("session_end",r);return o&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(e)}/close`,{finishedAt:t})),o}async flushCache(){try{let r=this.getDatabase(),o=r.listTelemetryFailures({unresolvedOnly:!0,limit:T}).reverse();for(let s of o)try{this.applyOperation(s.operation,s.payload),r.resolveTelemetryFailure(s.id);}catch{}r.trimTelemetryFailures(T);}catch{}let t=[...new Set([this.cacheDir,this.legacyCacheDir].filter(r=>!!r))].filter(r=>existsSync(r)).flatMap(r=>readdirSync(r).filter(o=>o.endsWith(".json")).map(o=>{let s=join(r,o);try{return {cacheFile:s,envelope:Le(JSON.parse(readFileSync(s,"utf8")),o)}}catch{return null}})).filter(r=>r!==null).sort((r,o)=>r.envelope.timestamp-o.envelope.timestamp||se(r.envelope.operation)-se(o.envelope.operation));for(let{cacheFile:r,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(r);}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(r){return this.cacheOperation(e,t,r),false}}applyOperation(e,t){let r=this.getDatabase();switch(e){case "tool_call":r.insertToolCallEvent(t);return;case "execution_start":r.insertSkillExecution({executionId:t.executionId,sessionId:t.sessionId,skillName:t.skillName,startedAt:t.startedAt,status:"running"});return;case "session_start":r.insertSession(t),r.insertRun({id:ie(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(!r.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":r.closeSession(t.sessionId,t.finishedAt),r.updateRun(ie(t.sessionId),{status:"completed",finishedAt:t.finishedAt});return}}cacheOperation(e,t,r){let o=Date.now(),s={id:`failure:${o}:${Math.random().toString(36).slice(2,11)}`,operation:e,payload:t,failure:r instanceof Error?r.message:String(r),timestamp:o};try{let i=this.getDatabase();i.insertTelemetryFailure({id:s.id,operation:e,payload:t,error:s.failure,createdAt:o}),i.trimTelemetryFailures(T),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-T)))unlinkSync(join(this.cacheDir,t));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},Ne).unref());}postHttp(e,t){Ue(`${this.apiUrl}${e}`,JSON.stringify(t),this.apiKey);}truncateInput(e){let t=JSON.stringify(e);return t===void 0||t.length<=oe?e:{_truncated:true,_original_size:t.length,_preview:`${t.substring(0,oe)}...`}}};function se(n){return ["session_start","execution_start","tool_call","complete_event","session_end"].indexOf(n)}function ie(n){return `hook-run:${n}`}function Le(n,e){if(!n||typeof n!="object")throw new Error("Invalid telemetry cache envelope");let t=n;if(typeof t.operation=="string"&&t.payload!==void 0)return t;let r=t.type==="tool_call"?"tool_call":t.type==="execution_start"?"execution_start":null;if(!r)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:r,payload:o,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:s}}var Ge=1;function Je(){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 ce(n=Je()){let e=[join(n,"dist","command-registry.json"),join(n,"command-registry.json")];for(let t of e)try{if(!existsSync(t))continue;let r=JSON.parse(readFileSync(t,"utf8"));if(r.version!==Ge||!Be(r.commands)){console.error(`[devflow] command registry contract mismatch: ${t}`);continue}return r.commands}catch(r){console.error(`[devflow] command registry load failed: ${r.message}`);}return null}function Be(n){return !n||typeof n!="object"||Array.isArray(n)?false:Object.values(n).every(e=>{if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return ae(t.mcpTools)&&ae(t.blockedNative)})}function ae(n){return Array.isArray(n)&&n.every(e=>typeof e=="string"&&e.length>0)}var Xe=new Set(["Agent","Bash","Glob","Grep","WebSearch","WebFetch"]);function Ze(n){try{let e=createHash("sha256").update(n).digest("hex").slice(0,12),t=join(d(n),`session-id-${e}`);if(existsSync(t))return readFileSync(t,"utf-8").trim()}catch{}return null}function Qe(n,e,t){try{let r=join(d(n),"event-map.json");if(!existsSync(r))return null;let o=JSON.parse(readFileSync(r,"utf-8")),s=o.filter(a=>a.toolName===e);if(s.length===0)return null;let i=t??Date.now();s.sort((a,v)=>Math.abs(a.timestamp-i)-Math.abs(v.timestamp-i));let c=s[0],l=o.findIndex(a=>a.eventId===c.eventId);return l!==-1&&o.splice(l,1),writeFileSync(r,JSON.stringify(o)),{eventId:c.eventId,timestamp:c.timestamp}}catch{return null}}function le(n){if(!n)return 0;let e=n;if(typeof n=="string")try{e=JSON.parse(n);}catch{return 1}let t=e,r=["files","results","data","result","memories","nodes","chunks","findings","symbols","keySymbols"],o=["reasoning","riskHints","nextActions"],s=t.data??t.structuredContent??t;if(Array.isArray(s))return s.length;if(typeof s=="object"&&s!==null){let i=s,c=0;for(let a of r)Array.isArray(i[a])&&(c+=i[a].length);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+=le(a));let l=!!(i._devflow||i._devflow_unique||i.taskType);return c===0&&l?1:c>0?c:Object.keys(i).length>0?1:0}return 0}function et(n){let e=d(n);return existsSync(e)||mkdirSync(e,{recursive:true}),e}function tt(n){let e=ce();return e?e[n]?.mcpTools??[]:[]}function nt(n,e){let t=et(n),r=join(t,"current-execution-id");if(existsSync(r))return;let o=`exec_${Date.now()}_${Math.random().toString(36).slice(2,11)}`;writeFileSync(r,o),writeFileSync(join(t,"current-skill.json"),JSON.stringify({name:e,required_mcp_tools:tt(e),registeredAt:Date.now()}));}function rt(n,e){if(!Xe.has(e))return null;let t=U(n,o=>({...o,bypassCount:(o.bypassCount??0)+1}));if(!t.applied)return null;let r=t.receipt.bypassCount??0;return r>20&&r%10===0?`MCP \u5DE5\u5177\u4F7F\u7528\u7387\u4F4E\uFF1A${r} \u6B21\u76F4\u63A5\u5DE5\u5177\u8C03\u7528\u3002\u5EFA\u8BAE\u4F7F\u7528 get_project_context \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`:null}async function ot(n){if(!n)return null;let e;try{e=JSON.parse(n);}catch{return null}let t=e.tool_name||"",r=P(),o=e.tool_input||{},s=e.tool_response||{},i=Ze(r);if(t==="Skill"){let u=typeof o=="object"&&o.skill?o.skill:"";u&&u.startsWith("devflow:")&&(nt(r,u),N(r,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0}));}t.startsWith("mcp__")&&new k(r).recordMcpCall();let c=join(d(r),"current-execution-id"),l=Qe(r,t,Date.now()),a=typeof s=="object"&&s!==null?s:null,v=JSON.stringify(s),m=Buffer.byteLength(v,"utf8"),f=le(s);if(existsSync(c)||t.startsWith("mcp__devflow__")||t==="Skill"){let u=getLogWriter(r),p=existsSync(c)?readFileSync(c,"utf-8").trim():`auto-${Date.now()}`;u.toolCall({tool:t,runId:p,stepId:`step-${p}`,input:o,output:s,duration:l?Date.now()-l.timestamp:0,success:!a?.error,resultCount:f,resultSizeBytes:m,error:a?.error});}if(l&&i){let u=typeof s=="string"?s:JSON.stringify(s),p=u.length>5e3?{_truncated:true,_originalSize:u.length,text:u.slice(0,5e3)}:s,pe=Date.now()-l.timestamp;await new x().completeEvent({eventId:l.eventId,sessionId:i,output:p,duration:pe,completedAt:Date.now()});}let y=typeof o=="object"&&o.command?o.command:"",w=a?.exitCode,H=a?.stderr,ue=/^\s*(ls|cat|pwd|cd|echo|head|tail|wc|which|whoami|date|env|printenv|id|hostname|uname)\b/,h,b,O=true;if(t.startsWith("mcp__"))h="mcp_call",b={mcpTool:t.replace(/^mcp__[^_]+__/,""),query:typeof o=="object"&&o.query?o.query:null,resultCount:f,resultSizeBytes:m};else if(t==="Read"||t==="Write"||t==="Edit")h=t==="Read"?"file_read":"file_write",b={filePath:typeof o=="object"&&o.file_path?o.file_path:null,fileContentSize:m};else if(t==="Bash"){let u=ue.test(y),p=w!==void 0&&w!==0;O=!u||p,h=p?"bash_error":"bash_command",b={command:y||t,exitCode:w??null,stderr:H??null};}else t==="Agent"?(h="subagent",b={subagentType:typeof o=="object"&&o.subagent_type?o.subagent_type:null,description:typeof o=="object"&&o.description?String(o.description).slice(0,200):null}):t==="WebSearch"||t==="WebFetch"?(h=t==="WebSearch"?"web_search":"web_fetch",b={query:typeof o=="object"&&o.query?String(o.query).slice(0,200):null}):(O=false,h="tool_use",b={});if(O){let u={id:`evt:${Date.now()}:${Math.random().toString(36).slice(2,7)}`,sessionId:i??`session:${r.split("/").pop()||"default"}`,tool:t,kind:h,payload:b,command:y||void 0,exitCode:w,stderr:H??void 0,durationMs:l?Date.now()-l.timestamp:0,createdAt:Date.now()},p=new MemoryGate(r);try{await p.forceWarmUp(),await p.recordEvent(u);}catch{}finally{p.close();}K(`/api/memory/session-events?rootPath=${encodeURIComponent(r)}`,u);}let I=rt(r,t);return I&&console.error("[devflow] Enforcement:",I),I}if(process.argv[1]?.endsWith("post-tool-use")||process.argv[1]?.endsWith("post-tool-use.js")){let n="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e;}),process.stdin.on("end",async()=>{let e=await ot(n.trim()||process.argv[2]||"");if(e){let t=JSON.stringify(e);console.log(JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:t}}));}}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),5e3).unref();}
|
|
3
|
+
export{ot as handlePostToolUse};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {getLocalApiKey}from'@devflow-tools/sdk';import {existsSync,readdirSync,readFileSync,unlinkSync,mkdirSync,writeFileSync}from'fs';import {request}from'http';import {join}from'path';import {homedir}from'os';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {MemoryGate}from'@devflow-tools/memory-engine';function u(n){return n??process.env.CLAUDE_PROJECT_DIR??process.cwd()}var f=1e4,S=3e4,d=500;function x(n,r,e){return new Promise(t=>{try{let o=new URL(n),s=request({hostname:o.hostname,port:o.port||80,path:o.pathname+o.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":e,"Content-Length":Buffer.byteLength(r)},timeout:5e3},i=>{let a=[];i.on("data",l=>a.push(l)),i.on("end",()=>{let l=Buffer.concat(a).toString();t(i.statusCode!=null&&i.statusCode>=200&&i.statusCode<300?l:null);});});s.on("error",()=>t(null)),s.on("timeout",()=>{s.destroy(),t(null);}),s.write(r),s.end();}catch{t(null);}})}var m=class{constructor(r){this.retryScheduled=false;this.apiUrl=r?.apiUrl??process.env.DEVFLOW_API_URL??"http://127.0.0.1:13337",this.apiKey=r?.apiKey??getLocalApiKey(),this.cacheDir=r?.cacheDir??join(process.env.DEVFLOW_STATE_DIR??join(homedir(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=r?.legacyCacheDir??(r?.cacheDir?null:join(homedir(),".devflow","telemetry-cache")),this.database=r?.database??null,this.ownsDatabase=!r?.database;}async sendEvent(r){let e={...r,input:this.truncateInput(r.input)};return this.commitOrCache("tool_call",e)?(this.postHttp("/api/telemetry/tool-call",e),r.eventId):null}async sendExecutionStart(r,e,t,o){let s={executionId:r,sessionId:e,skillName:t,startedAt:o};this.commitOrCache("execution_start",s)&&this.postHttp("/api/telemetry/skill-execution/start",s);}async sendSessionStart(r,e,t){let o={id:r,projectRoot:e,startedAt:t,label:e.split("/").pop()??"unknown"},s=this.commitOrCache("session_start",o);return s&&this.postHttp("/api/telemetry/sessions",o),s}async completeEvent(r){let e=this.commitOrCache("complete_event",r);return e&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp("/api/telemetry/tool-call/output",r)),e}async endSession(r,e=Date.now()){let t={sessionId:r,finishedAt:e},o=this.commitOrCache("session_end",t);return o&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(r)}/close`,{finishedAt:e})),o}async flushCache(){try{let t=this.getDatabase(),o=t.listTelemetryFailures({unresolvedOnly:!0,limit:d}).reverse();for(let s of o)try{this.applyOperation(s.operation,s.payload),t.resolveTelemetryFailure(s.id);}catch{}t.trimTelemetryFailures(d);}catch{}let e=[...new Set([this.cacheDir,this.legacyCacheDir].filter(t=>!!t))].filter(t=>existsSync(t)).flatMap(t=>readdirSync(t).filter(o=>o.endsWith(".json")).map(o=>{let s=join(t,o);try{return {cacheFile:s,envelope:M(JSON.parse(readFileSync(s,"utf8")),o)}}catch{return null}})).filter(t=>t!==null).sort((t,o)=>t.envelope.timestamp-o.envelope.timestamp||v(t.envelope.operation)-v(o.envelope.operation));for(let{cacheFile:t,envelope:o}of e)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(t);}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(r,e){try{return this.applyOperation(r,e),!0}catch(t){return this.cacheOperation(r,e,t),false}}applyOperation(r,e){let t=this.getDatabase();switch(r){case "tool_call":t.insertToolCallEvent(e);return;case "execution_start":t.insertSkillExecution({executionId:e.executionId,sessionId:e.sessionId,skillName:e.skillName,startedAt:e.startedAt,status:"running"});return;case "session_start":t.insertSession(e),t.insertRun({id:D(e.id),source:"hook",tool:"session",input:{projectRoot:e.projectRoot},status:"active",startedAt:e.startedAt,tokenUsed:0,metadata:{sessionId:e.id,projectRoot:e.projectRoot}});return;case "complete_event":if(!t.updateToolCallEvent(e.eventId,{output:e.output===void 0?void 0:JSON.stringify(e.output),error:e.error,duration:e.duration}))throw new Error(`Tool call event ${e.eventId} is not available for completion`);return;case "session_end":t.closeSession(e.sessionId,e.finishedAt),t.updateRun(D(e.sessionId),{status:"completed",finishedAt:e.finishedAt});return}}cacheOperation(r,e,t){let o=Date.now(),s={id:`failure:${o}:${Math.random().toString(36).slice(2,11)}`,operation:r,payload:e,failure:t instanceof Error?t.message:String(t),timestamp:o};try{let i=this.getDatabase();i.insertTelemetryFailure({id:s.id,operation:r,payload:e,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 r=readdirSync(this.cacheDir).filter(e=>e.endsWith(".json")).sort();for(let e of r.slice(0,Math.max(0,r.length-d)))unlinkSync(join(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},S).unref());}postHttp(r,e){x(`${this.apiUrl}${r}`,JSON.stringify(e),this.apiKey);}truncateInput(r){let e=JSON.stringify(r);return e===void 0||e.length<=f?r:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,f)}...`}}};function v(n){return ["session_start","execution_start","tool_call","complete_event","session_end"].indexOf(n)}function D(n){return `hook-run:${n}`}function M(n,r){if(!n||typeof n!="object")throw new Error("Invalid telemetry cache envelope");let e=n;if(typeof e.operation=="string"&&e.payload!==void 0)return e;let t=e.type==="tool_call"?"tool_call":e.type==="execution_start"?"execution_start":null;if(!t)throw new Error("Unknown legacy telemetry cache operation");let o=e.payload??{},s=Number(o.timestamp??o.startedAt??Date.now());return {id:`legacy-cache:${r}`,operation:t,payload:o,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:s}}async function b(n){let r=!n.memory,e=n.memory??new MemoryGate(n.projectRoot),t=0,o=0;try{await e.forceWarmUp(),n.trigger==="session_end"&&(t=await e.releasePendingDistillLeases(n.sessionId)),o=e.getPendingEventCount();}finally{r&&e.close();}let s={pendingEvents:o,releasedLeases:t,trigger:n.trigger,sessionId:n.sessionId};try{let i=openGlobalDevFlowDatabase();try{let a=Date.now(),l=`distill:${a}:${Math.random().toString(36).slice(2,10)}`;i.recordMemoryDistillCheckpoint({id:l,projectRoot:n.projectRoot,sessionId:n.sessionId,trigger:n.trigger,pendingEvents:o,releasedLeases:t,createdAt:a}),i.insertEvent({kind:"memory_distill_requested",timestamp:a,success:!0,metadata:{...s,projectRoot:n.projectRoot}});}finally{i.close();}}catch{}return s}function _(n){if(n.pendingEvents===0)return "";let r=n.sessionId?`\uFF0CsessionId=${n.sessionId}`:"";return `Memory distill checkpoint: ${n.pendingEvents} \u4E2A\u4E8B\u4EF6\u5F85\u63D0\u70BC${r}\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 w="WARNING: DevFlow is in degraded mode (daemon unreachable): 4-Gate enforcement and memory prefetch cache are unavailable. Run `devflow doctor` for details.";function C(){return process.env.DEVFLOW_HOOK_DEGRADED==="1"}async function F(n="",r=u()){let e;try{let i=JSON.parse(n);typeof i.session_id=="string"&&i.session_id.trim()&&(e=i.session_id.trim());}catch{}let t=new m;try{await t.flushAndAggregate();}finally{t.close();}let o=await b({projectRoot:r,sessionId:e,trigger:"pre_compact"}),s=[C()?w:"",_(o)].filter(Boolean).join(`
|
|
2
|
+
|
|
3
|
+
`);return {hookSpecificOutput:{hookEventName:"PreCompact",...s?{additionalContext:s}:{}}}}if(process.argv[1]?.endsWith("pre-compact")||process.argv[1]?.endsWith("pre-compact.js")){let n=console.log,r=console.info,e=()=>{console.log=n,console.info=r;};console.log=console.error.bind(console),console.info=console.error.bind(console);let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",o=>{t+=o;}),process.stdin.on("end",()=>{F(t.trim()||process.argv[2]||"").then(o=>{e(),n(JSON.stringify(o)),process.exit(0);}).catch(()=>{e(),process.exit(0);});}),process.stdin.on("error",()=>{e(),process.exit(0);}),setTimeout(()=>process.exit(0),14e3).unref();}export{F as handlePreCompact};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {existsSync,readdirSync,readFileSync,unlinkSync,mkdirSync,writeFileSync}from'fs';import {join,dirname as dirname$1}from'path';import {createHash}from'crypto';import {request}from'http';import {homedir}from'os';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {getLocalApiKey,getProjectStateDir}from'@devflow-tools/sdk';import {fileURLToPath}from'url';import {mkdirSync as mkdirSync$1,existsSync as existsSync$1,statSync,appendFileSync,chmodSync,rmSync,renameSync}from'node:fs';import {createHash as createHash$1}from'node:crypto';import {homedir as homedir$1}from'node:os';import {dirname,join as join$1}from'node:path';var $=1e4,be=3e4,b=500;function De(n,e,t){return new Promise(r=>{try{let o=new URL(n),i=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},s=>{let c=[];s.on("data",u=>c.push(u)),s.on("end",()=>{let u=Buffer.concat(c).toString();r(s.statusCode!=null&&s.statusCode>=200&&s.statusCode<300?u:null);});});i.on("error",()=>r(null)),i.on("timeout",()=>{i.destroy(),r(null);}),i.write(e),i.end();}catch{r(null);}})}var D=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,r,o){let i={executionId:e,sessionId:t,skillName:r,startedAt:o};this.commitOrCache("execution_start",i)&&this.postHttp("/api/telemetry/skill-execution/start",i);}async sendSessionStart(e,t,r){let o={id:e,projectRoot:t,startedAt:r,label:t.split("/").pop()??"unknown"},i=this.commitOrCache("session_start",o);return i&&this.postHttp("/api/telemetry/sessions",o),i}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 r={sessionId:e,finishedAt:t},o=this.commitOrCache("session_end",r);return o&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(e)}/close`,{finishedAt:t})),o}async flushCache(){try{let r=this.getDatabase(),o=r.listTelemetryFailures({unresolvedOnly:!0,limit:b}).reverse();for(let i of o)try{this.applyOperation(i.operation,i.payload),r.resolveTelemetryFailure(i.id);}catch{}r.trimTelemetryFailures(b);}catch{}let t=[...new Set([this.cacheDir,this.legacyCacheDir].filter(r=>!!r))].filter(r=>existsSync(r)).flatMap(r=>readdirSync(r).filter(o=>o.endsWith(".json")).map(o=>{let i=join(r,o);try{return {cacheFile:i,envelope:ve(JSON.parse(readFileSync(i,"utf8")),o)}}catch{return null}})).filter(r=>r!==null).sort((r,o)=>r.envelope.timestamp-o.envelope.timestamp||L(r.envelope.operation)-L(o.envelope.operation));for(let{cacheFile:r,envelope:o}of t)try{let i=this.getDatabase();i.insertTelemetryFailure({id:o.id,operation:o.operation,payload:o.payload,error:o.failure,createdAt:o.timestamp}),this.applyOperation(o.operation,o.payload),i.resolveTelemetryFailure(o.id),unlinkSync(r);}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(r){return this.cacheOperation(e,t,r),false}}applyOperation(e,t){let r=this.getDatabase();switch(e){case "tool_call":r.insertToolCallEvent(t);return;case "execution_start":r.insertSkillExecution({executionId:t.executionId,sessionId:t.sessionId,skillName:t.skillName,startedAt:t.startedAt,status:"running"});return;case "session_start":r.insertSession(t),r.insertRun({id:U(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(!r.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":r.closeSession(t.sessionId,t.finishedAt),r.updateRun(U(t.sessionId),{status:"completed",finishedAt:t.finishedAt});return}}cacheOperation(e,t,r){let o=Date.now(),i={id:`failure:${o}:${Math.random().toString(36).slice(2,11)}`,operation:e,payload:t,failure:r instanceof Error?r.message:String(r),timestamp:o};try{let s=this.getDatabase();s.insertTelemetryFailure({id:i.id,operation:e,payload:t,error:i.failure,createdAt:o}),s.trimTelemetryFailures(b),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let s=join(this.cacheDir,`${o}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(s,JSON.stringify(i,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-b)))unlinkSync(join(this.cacheDir,t));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},be).unref());}postHttp(e,t){De(`${this.apiUrl}${e}`,JSON.stringify(t),this.apiKey);}truncateInput(e){let t=JSON.stringify(e);return t===void 0||t.length<=$?e:{_truncated:true,_original_size:t.length,_preview:`${t.substring(0,$)}...`}}};function L(n){return ["session_start","execution_start","tool_call","complete_event","session_end"].indexOf(n)}function U(n){return `hook-run:${n}`}function ve(n,e){if(!n||typeof n!="object")throw new Error("Invalid telemetry cache envelope");let t=n;if(typeof t.operation=="string"&&t.payload!==void 0)return t;let r=t.type==="tool_call"?"tool_call":t.type==="execution_start"?"execution_start":null;if(!r)throw new Error("Unknown legacy telemetry cache operation");let o=t.payload??{},i=Number(o.timestamp??o.startedAt??Date.now());return {id:`legacy-cache:${e}`,operation:r,payload:o,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:i}}function x(n){return n??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function l(n){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(x(n))}var Ee=1;function Ce(){if(process.env.CLAUDE_PLUGIN_ROOT)return process.env.CLAUDE_PLUGIN_ROOT;try{return join(dirname$1(fileURLToPath(import.meta.url)),"..","..")}catch{return process.cwd()}}function q(n=Ce()){let e=[join(n,"dist","command-registry.json"),join(n,"command-registry.json")];for(let t of e)try{if(!existsSync(t))continue;let r=JSON.parse(readFileSync(t,"utf8"));if(r.version!==Ee||!Oe(r.commands)){console.error(`[devflow] command registry contract mismatch: ${t}`);continue}return r.commands}catch(r){console.error(`[devflow] command registry load failed: ${r.message}`);}return null}function Oe(n){return !n||typeof n!="object"||Array.isArray(n)?false:Object.values(n).every(e=>{if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return G(t.mcpTools)&&G(t.blockedNative)})}function G(n){return Array.isArray(n)&&n.every(e=>typeof e=="string"&&e.length>0)}var Ae=1800*1e3,Fe=300*1e3;function B(n){let e=q();return e?e[n]?.mcpTools??[]:[]}var v=class{constructor(e){this.stateDir=l(e);}detect(){let e=join(this.stateDir,"current-skill.json");if(!existsSync(e))return null;try{let t=readFileSync(e,"utf8"),r=JSON.parse(t);return !r.registeredAt||Date.now()-r.registeredAt>Ae?(this.endExecution(),null):(Date.now()-r.registeredAt>Fe&&(r.registeredAt=Date.now(),writeFileSync(e,JSON.stringify(r))),r)}catch{return null}}startExecution(e,t){existsSync(this.stateDir)||mkdirSync(this.stateDir,{recursive:true});let r=this.getCurrentExecutionId();if(r)return r;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{}}};function h(n){if(!n||typeof n!="object"||Array.isArray(n))return {};let e=n,t={};for(let r of ["lastMcpCall","bypassCount"])if(r in e){let o=e[r];if(o==null)continue;t[r]=typeof o=="number"&&Number.isFinite(o)&&o>=0?o:0;}return t}function je(n,e){return n.lastMcpCall===e.lastMcpCall&&n.bypassCount===e.bypassCount}function Me(n){try{return existsSync(n)?h(JSON.parse(readFileSync(n,"utf-8"))):{}}catch{return {}}}function X(n,e){let t=e instanceof Error?e.message:String(e);console.error(`[devflow] Receipt ${n} skipped: ${t}`);}function K(n){let e=l(n);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 Y(n,e){if(n.getHookReceipt(e)){K(e);return}let t=join(l(e),"receipt.json");if(!existsSync(t))return;let r=Me(t);n.updateHookReceipt(e,()=>r),K(e);}function Z(n,e,t){let r;try{r=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),Y(r,n);let o={},i=r.updateHookReceipt(n,c=>(o=h(c),h(e(o)))),s=h(i);return {receipt:s,applied:!0,changed:!je(o,s)}}catch(o){return X(t,o),{receipt:{},applied:false,changed:false}}finally{try{r?.close();}catch{}}}function O(n){let e;try{return e=openGlobalDevFlowDatabase(void 0,{busyTimeoutMs:250}),Y(e,n),h(e.getHookReceipt(n))}catch(t){return X("update",t),{}}finally{try{e?.close();}catch{}}}function Ne(n,e){return Z(n,()=>e,"write").applied}function Pe(n,e){return Z(n,e,"update")}var He={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",Bash:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge"};function $e(n){switch(n){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}var w=class{constructor(e){this.projectRoot=e;}getPhase(){let t=O(this.projectRoot).lastMcpCall??0;if(Math.floor(Date.now()/1e3)-t<30)return "context_ready";let o=join(l(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 r=this.getPhase();if(t||e==="Skill")return {permissionDecision:"allow"};if(r==="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(r==="context_ready")return {permissionDecision:"allow"};let o=He[e];if(!o)return {permissionDecision:"allow"};let i=Pe(this.projectRoot,u=>({...u,bypassCount:(u.bypassCount??0)+1}));if(!i.applied)return {permissionDecision:"allow"};let s=i.receipt.bypassCount??0,c=$e(e);return s>=c?{permissionDecision:"allow",additionalContext:`\u5DF2 ${s} \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(){Ne(this.projectRoot,{lastMcpCall:Math.floor(Date.now()/1e3),bypassCount:0});}};var Ve=10*1024*1024,ze=5;function Xe(n){return createHash$1("sha256").update(n).digest("hex").slice(0,16)}function te(n){return join$1(homedir$1(),".devflow","logs","hook-debug",`${Xe(n)}.jsonl`)}function ne(n,e,t={}){let r=t.maxBytes??Ve,o=t.maxFiles??ze;mkdirSync$1(dirname(n),{recursive:true,mode:448});let i=Buffer.byteLength(e),s=existsSync$1(n)?statSync(n).size:0;s>0&&s+i>r&&Ye(n,o),appendFileSync(n,e,{mode:384}),chmodSync(n,384);}function Ye(n,e){if(e<=1){rmSync(n,{force:true});return}rmSync(`${n}.${e-1}`,{force:true});for(let t=e-2;t>=1;t-=1){let r=`${n}.${t}`;existsSync$1(r)&&renameSync(r,`${n}.${t+1}`);}existsSync$1(n)&&renameSync(n,`${n}.1`);}var re="WARNING: DevFlow is in degraded mode (daemon unreachable): 4-Gate enforcement and memory prefetch cache are unavailable. Run `devflow doctor` for details.";function oe(){return process.env.DEVFLOW_HOOK_DEGRADED==="1"}function y(){return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}function ie(n){return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:n}}}function le(n){let e=l(n);return existsSync(e)||mkdirSync(e,{recursive:true}),e}function ue(n){let e=createHash("sha256").update(n).digest("hex").slice(0,12);return join(l(n),`session-id-${e}`)}function et(n){try{let e=ue(n);if(existsSync(e))return readFileSync(e,"utf-8").trim()}catch{}return null}function tt(n,e){le(e),writeFileSync(ue(e),n);}function nt(n,e,t,r){let o=join(le(n),"event-map.json"),i=[];try{existsSync(o)&&(i=JSON.parse(readFileSync(o,"utf-8")));}catch{}i.push({toolName:e,eventId:t,timestamp:r}),writeFileSync(o,JSON.stringify(i));}function rt(n){switch(n){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"}}async function ot(n){if(oe())return ie(re);try{if(!n||n.trim()==="")return y();let e=JSON.parse(n),t=Date.now(),r=x(),o=r.split("/").pop()||"unknown",i=new D,s=et(r);s||(s=`session:${o}:${Date.now().toString(36)}`,tt(s,r),i.sendSessionStart(s,r,Date.now()).catch(()=>{}));let c=new v(r);if(e.tool_name==="Skill"){let a=e.tool_input?.skill;if(a&&a.startsWith("devflow:")){let R=c.startExecution(a,{required_mcp_tools:B(a)});i.sendExecutionStart(R,s,a,Date.now()).catch(()=>{});}}let u=c.detect(),p=e.tool_name.startsWith("mcp__"),pe=p?e.tool_name.replace(/^mcp__[^_]+__/,""):void 0,F=new w(r),I=F.getPhase(),d,_=F.evaluate(e.tool_name,p);_.permissionDecision==="deny"?d={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:_.reason??"MCP context required"}}:_.additionalContext?d=ie(_.additionalContext):d=y();let de=c.getCurrentExecutionId()??s,j={eventId:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,executionId:de,sessionId:s,timestamp:Date.now(),toolName:e.tool_name,toolType:p?"mcp":e.tool_name==="Agent"?"subagent":"direct",isMcpTool:p,mcpToolName:pe,mcpEnforced:p&&I==="context_gathering",mcpFallback:!p&&I==="context_gathering",kind:rt(e.tool_name),input:e.tool_input,duration:0,blocked:d.hookSpecificOutput.permissionDecision==="deny"};i.sendEvent(j).then(a=>{a&&nt(r,e.tool_name,a,j.timestamp);}).catch(()=>{});try{let a=O(r),R={ts:t,tool:e.tool_name,skill:u?.name??"(none)",requiredTools:requiredMcpTools,isMcp:p,enforce:shouldSkillEnforce,stateless:!shouldSkillEnforce&&!p&&e.tool_name!=="Skill",bypassCount:a.bypassCount??0,decision:d.hookSpecificOutput.permissionDecision,env_CLAUDE_PLUGIN_ROOT:process.env.CLAUDE_PLUGIN_ROOT??"(unset)",cwd:process.cwd()};ne(te(r),`${JSON.stringify(R)}
|
|
2
|
+
`);}catch{}return d}catch{return y()}}if(process.argv[1]?.endsWith("pre-tool-use")||process.argv[1]?.endsWith("pre-tool-use.js")){let n="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e;}),process.stdin.on("end",async()=>{let e=await ot(n);console.log(JSON.stringify(e));}),process.stdin.on("error",()=>{console.log(JSON.stringify(y())),process.exit(0);}),setTimeout(()=>{console.log(JSON.stringify(y())),process.exit(0);},4e3).unref();}export{ot as handlePreToolUse};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import {spawn,execFileSync}from'node:child_process';import {randomUUID}from'node:crypto';import {mkdirSync,writeFileSync,existsSync}from'node:fs';import {request}from'node:http';import {createRequire}from'node:module';import {homedir}from'node:os';import {join}from'node:path';var{DatabaseSync:y}=createRequire(import.meta.url)("node:sqlite"),C=75,x=400,U=2e3,H=300*1e3,W=1e3,B=1e3,F=15e3,Q=["--yes","@devflow-tools/server","--devflow-instance-token"],z=process.env.DEVFLOW_SERVER_BOOTSTRAP_HEALTH_URL??"http://127.0.0.1:13337/api/health";function E(e){let t=e instanceof Error?e.message:String(e);console.error(`[devflow] Server bootstrap skipped: ${t}`);}function $(e){let t=new y(e);t.exec(`PRAGMA busy_timeout = ${C}`);let n=t.prepare(`
|
|
2
|
+
SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'server_bootstrap_state'
|
|
3
|
+
`).get();if(n?.sql&&!n.sql.includes("'terminating'")){t.exec("BEGIN IMMEDIATE");try{t.exec("ALTER TABLE server_bootstrap_state RENAME TO server_bootstrap_state_legacy"),g(t),t.exec(`
|
|
4
|
+
INSERT INTO server_bootstrap_state (
|
|
5
|
+
id, token, state, owner_pid, wrapper_pid, process_group_id, server_pid,
|
|
6
|
+
created_at, updated_at
|
|
7
|
+
)
|
|
8
|
+
SELECT
|
|
9
|
+
id, token, state, owner_pid, wrapper_pid, process_group_id, server_pid,
|
|
10
|
+
created_at, updated_at
|
|
11
|
+
FROM server_bootstrap_state_legacy
|
|
12
|
+
`),t.exec("DROP TABLE server_bootstrap_state_legacy"),t.exec("COMMIT");}catch(r){try{t.exec("ROLLBACK");}catch{}throw r}}else n||g(t);return t}function g(e){e.exec(`
|
|
13
|
+
CREATE TABLE IF NOT EXISTS server_bootstrap_state (
|
|
14
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
15
|
+
token TEXT NOT NULL,
|
|
16
|
+
state TEXT NOT NULL CHECK (state IN ('launching', 'running', 'terminating')),
|
|
17
|
+
owner_pid INTEGER NOT NULL,
|
|
18
|
+
wrapper_pid INTEGER,
|
|
19
|
+
process_group_id INTEGER,
|
|
20
|
+
server_pid INTEGER,
|
|
21
|
+
created_at INTEGER NOT NULL,
|
|
22
|
+
updated_at INTEGER NOT NULL
|
|
23
|
+
)
|
|
24
|
+
`);}function K(e){return e.prepare(`
|
|
25
|
+
SELECT
|
|
26
|
+
token,
|
|
27
|
+
state,
|
|
28
|
+
owner_pid AS ownerPid,
|
|
29
|
+
wrapper_pid AS wrapperPid,
|
|
30
|
+
process_group_id AS processGroupId,
|
|
31
|
+
server_pid AS serverPid,
|
|
32
|
+
created_at AS createdAt,
|
|
33
|
+
updated_at AS updatedAt
|
|
34
|
+
FROM server_bootstrap_state
|
|
35
|
+
WHERE id = 1
|
|
36
|
+
`).get()}function c(e){return Number(e.changes)}function q(e){if(!Number.isSafeInteger(e)||e<=1)return false;try{return process.kill(e,0),!0}catch{return false}}function A(){let e=execFileSync("ps",["-axo","pid=,pgid=,command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:500}),t=[];for(let n of e.split(`
|
|
37
|
+
`)){let r=n.match(/^\s*(\d+)\s+(\d+)\s+(.+)$/);if(!r)continue;let o=Number(r[1]),a=Number(r[2]);!Number.isSafeInteger(o)||!Number.isSafeInteger(a)||t.push({pid:o,processGroupId:a,command:r[3]});}return t}function V(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function v(e,t){let n=V(t);return new RegExp(`(?:^|\\s)--devflow-instance-token(?:=|\\s+)${n}(?:\\s|$)`).test(e)}function P(e){return /(?:@devflow-tools\/server|devflow-server)/.test(e)}function Y(e){let t=A().filter(r=>P(r.command)&&v(r.command,e)),n=new Map;for(let r of t){let o=n.get(r.processGroupId)??[];o.push(r),n.set(r.processGroupId,o);}return [...n.entries()].map(([r,o])=>({processGroupId:r,processes:o})).sort((r,o)=>o.processes.length-r.processes.length)}function w(e,t){return Y(e).find(n=>t===void 0||n.processGroupId===t)}function d(e,t){let n=m(e,t);if(!n)return;let r=n.processes.find(o=>o.pid!==n.wrapperPid&&o.command.includes("devflow-server"));if(r)return {wrapperPid:n.wrapperPid,processGroupId:n.processGroupId,serverPid:r.pid,processes:n.processes}}function m(e,t){let n=w(e,t);if(!n)return;let r=n.processes.find(o=>o.pid===n.processGroupId&&o.command.includes("@devflow-tools/server"));if(r)return {wrapperPid:r.pid,processGroupId:r.processGroupId,processes:n.processes}}function _(e){if(!q(e))return false;try{return execFileSync("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:250}).trim().includes("server-bootstrap")}catch{return false}}function X(){return new Promise(e=>{let t=false,n=r=>{t||(t=true,e(r));};try{let r=request(z,{method:"GET",timeout:x},o=>{o.resume(),n((o.statusCode??500)>=200&&(o.statusCode??500)<300);});r.on("timeout",()=>r.destroy(new Error("health timeout"))),r.on("error",()=>n(!1)),r.end();}catch{n(false);}})}async function j(e){let t=false;try{e.exec("BEGIN IMMEDIATE"),t=!0;let n=await X(),r=K(e);if(n){if(r?.state==="running"||r?.state==="launching"){let s=d(r.token,r.processGroupId??void 0);s?e.prepare(`
|
|
38
|
+
UPDATE server_bootstrap_state
|
|
39
|
+
SET state = 'running', owner_pid = ?, wrapper_pid = ?, process_group_id = ?, server_pid = ?,
|
|
40
|
+
updated_at = ?
|
|
41
|
+
WHERE id = 1 AND token = ? AND state = ?
|
|
42
|
+
`).run(process.pid,s.wrapperPid,s.processGroupId,s.serverPid,Date.now(),r.token,r.state):r.state==="running"&&e.prepare(`
|
|
43
|
+
DELETE FROM server_bootstrap_state
|
|
44
|
+
WHERE id = 1 AND token = ? AND state = 'running'
|
|
45
|
+
`).run(r.token);}return e.exec("COMMIT"),t=!1,{action:"skip"}}if(r?.state==="launching"){if(_(r.ownerPid))return e.exec("COMMIT"),t=!1,{action:"skip"};let s=r.processGroupId??void 0,i=d(r.token,s);if(i){let f=e.prepare(`
|
|
46
|
+
UPDATE server_bootstrap_state
|
|
47
|
+
SET state = 'running', owner_pid = ?, wrapper_pid = ?, process_group_id = ?,
|
|
48
|
+
server_pid = ?, updated_at = ?
|
|
49
|
+
WHERE id = 1 AND token = ? AND state = 'launching' AND owner_pid = ?
|
|
50
|
+
`).run(process.pid,i.wrapperPid,i.processGroupId,i.serverPid,Date.now(),r.token,r.ownerPid);if(c(f)!==1)throw new Error("launch intent changed before adoption");return e.exec("COMMIT"),t=!1,console.error(`[devflow] Adopted server process group ${i.processGroupId}`),{action:"skip"}}let p=m(r.token,s);if(p&&Date.now()-r.createdAt<H)return e.exec("COMMIT"),t=!1,{action:"skip"};if(p){let f=e.prepare(`
|
|
51
|
+
UPDATE server_bootstrap_state
|
|
52
|
+
SET state = 'terminating', owner_pid = ?, process_group_id = ?, updated_at = ?
|
|
53
|
+
WHERE id = 1 AND token = ? AND state = 'launching' AND owner_pid = ?
|
|
54
|
+
`).run(process.pid,p.processGroupId,Date.now(),r.token,r.ownerPid);if(c(f)!==1)throw new Error("launch intent changed before cleanup claim");return e.exec("COMMIT"),t=!1,{action:"cleanup",token:r.token,processGroupId:p.processGroupId}}e.prepare(`
|
|
55
|
+
DELETE FROM server_bootstrap_state
|
|
56
|
+
WHERE id = 1 AND token = ? AND state = 'launching' AND owner_pid = ?
|
|
57
|
+
`).run(r.token,r.ownerPid);}else if(r?.state==="terminating"){if(_(r.ownerPid))return e.exec("COMMIT"),t=!1,{action:"skip"};let s=w(r.token);if(s){let i=e.prepare(`
|
|
58
|
+
UPDATE server_bootstrap_state
|
|
59
|
+
SET owner_pid = ?, process_group_id = ?, updated_at = ?
|
|
60
|
+
WHERE id = 1 AND token = ? AND state = 'terminating' AND owner_pid = ?
|
|
61
|
+
`).run(process.pid,s.processGroupId,Date.now(),r.token,r.ownerPid);if(c(i)!==1)throw new Error("cleanup ownership changed during recovery");return e.exec("COMMIT"),t=!1,{action:"cleanup",token:r.token,processGroupId:s.processGroupId}}e.prepare(`
|
|
62
|
+
DELETE FROM server_bootstrap_state
|
|
63
|
+
WHERE id = 1 AND token = ? AND state = 'terminating' AND owner_pid = ?
|
|
64
|
+
`).run(r.token,r.ownerPid);}else if(r?.state==="running"){let s=d(r.token);if(s)return e.prepare(`
|
|
65
|
+
UPDATE server_bootstrap_state
|
|
66
|
+
SET owner_pid = ?, wrapper_pid = ?, process_group_id = ?, server_pid = ?, updated_at = ?
|
|
67
|
+
WHERE id = 1 AND token = ? AND state = 'running'
|
|
68
|
+
`).run(process.pid,s.wrapperPid,s.processGroupId,s.serverPid,Date.now(),r.token),e.exec("COMMIT"),t=!1,{action:"skip"};let i=w(r.token);if(i&&!_(r.ownerPid)){let p=e.prepare(`
|
|
69
|
+
UPDATE server_bootstrap_state
|
|
70
|
+
SET state = 'terminating', owner_pid = ?, process_group_id = ?, updated_at = ?
|
|
71
|
+
WHERE id = 1 AND token = ? AND state = 'running' AND owner_pid = ?
|
|
72
|
+
`).run(process.pid,i.processGroupId,Date.now(),r.token,r.ownerPid);if(c(p)!==1)throw new Error("running cleanup ownership changed");return e.exec("COMMIT"),t=!1,{action:"cleanup",token:r.token,processGroupId:i.processGroupId}}e.prepare(`
|
|
73
|
+
DELETE FROM server_bootstrap_state
|
|
74
|
+
WHERE id = 1 AND token = ? AND state = 'running' AND owner_pid = ?
|
|
75
|
+
`).run(r.token,r.ownerPid);}let o=randomUUID(),a=Date.now();return e.prepare(`
|
|
76
|
+
INSERT INTO server_bootstrap_state (
|
|
77
|
+
id, token, state, owner_pid, wrapper_pid, process_group_id, server_pid,
|
|
78
|
+
created_at, updated_at
|
|
79
|
+
) VALUES (1, ?, 'launching', ?, NULL, NULL, NULL, ?, ?)
|
|
80
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
81
|
+
token = excluded.token,
|
|
82
|
+
state = 'launching',
|
|
83
|
+
owner_pid = excluded.owner_pid,
|
|
84
|
+
wrapper_pid = NULL,
|
|
85
|
+
process_group_id = NULL,
|
|
86
|
+
server_pid = NULL,
|
|
87
|
+
created_at = excluded.created_at,
|
|
88
|
+
updated_at = excluded.updated_at
|
|
89
|
+
`).run(o,process.pid,a,a),e.exec("COMMIT"),t=!1,{action:"launch",token:o}}finally{if(t)try{e.exec("ROLLBACK");}catch{}}}function J(e){return new Promise((t,n)=>{let r;try{r=spawn("npx",[...Q,e],{detached:!0,env:process.env,stdio:["ignore","inherit","inherit"]});}catch(o){n(o);return}r.once("spawn",()=>t(r)),r.once("error",n);})}async function u(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(e())return true;await new Promise(r=>setTimeout(r,10));}return e()}async function h(e){let t=process.env[e];if(!t)return;writeFileSync(t,`${process.pid}
|
|
90
|
+
`);let n=process.env.DEVFLOW_SERVER_BOOTSTRAP_TEST_CONTINUE_FILE;if(!n)return;if(!await u(()=>existsSync(n),F))throw new Error(`test checkpoint timed out: ${e}`)}async function Z(e,t){let n;return await u(()=>{let o=d(e,t);return o?(n=o,true):false},U)?n:void 0}function ee(e,t,n){let r=false;try{e.exec("BEGIN IMMEDIATE"),r=!0;let o=e.prepare(`
|
|
91
|
+
UPDATE server_bootstrap_state
|
|
92
|
+
SET wrapper_pid = ?, process_group_id = ?, server_pid = NULL, updated_at = ?
|
|
93
|
+
WHERE id = 1 AND token = ? AND state = 'launching' AND owner_pid = ?
|
|
94
|
+
`).run(n.wrapperPid,n.processGroupId,Date.now(),t,process.pid);if(c(o)!==1)throw new Error("launch intent ownership changed before wrapper persistence");e.exec("COMMIT"),r=!1;}finally{if(r)try{e.exec("ROLLBACK");}catch{}}}function re(e,t,n){let r=false;try{e.exec("BEGIN IMMEDIATE"),r=!0;let o=e.prepare(`
|
|
95
|
+
UPDATE server_bootstrap_state
|
|
96
|
+
SET state = 'running', wrapper_pid = ?, process_group_id = ?, server_pid = ?,
|
|
97
|
+
updated_at = ?
|
|
98
|
+
WHERE id = 1 AND token = ? AND state = 'launching' AND owner_pid = ?
|
|
99
|
+
`).run(n.wrapperPid,n.processGroupId,n.serverPid,Date.now(),t,process.pid);if(c(o)!==1)throw new Error("launch intent ownership changed before promotion");e.exec("COMMIT"),r=!1;}finally{if(r)try{e.exec("ROLLBACK");}catch{}}}function te(e,t){let n=false;try{e.exec("BEGIN IMMEDIATE"),n=!0,e.prepare(`
|
|
100
|
+
DELETE FROM server_bootstrap_state
|
|
101
|
+
WHERE id = 1 AND token = ? AND state = 'launching' AND owner_pid = ?
|
|
102
|
+
`).run(t,process.pid),e.exec("COMMIT"),n=!1;}finally{if(n)try{e.exec("ROLLBACK");}catch{}}}function ne(e,t,n){let r=false;try{e.exec("BEGIN IMMEDIATE"),r=!0;let o=e.prepare(`
|
|
103
|
+
UPDATE server_bootstrap_state
|
|
104
|
+
SET state = 'terminating', owner_pid = ?, updated_at = ?
|
|
105
|
+
WHERE id = 1 AND token = ? AND state = 'launching' AND owner_pid = ?
|
|
106
|
+
`).run(process.pid,Date.now(),t,n);return e.exec("COMMIT"),r=!1,c(o)===1}finally{if(r)try{e.exec("ROLLBACK");}catch{}}}function oe(e,t){let n=false;try{e.exec("BEGIN IMMEDIATE"),n=!0;let r=e.prepare(`
|
|
107
|
+
DELETE FROM server_bootstrap_state
|
|
108
|
+
WHERE id = 1 AND token = ? AND state = 'terminating' AND owner_pid = ?
|
|
109
|
+
`).run(t,process.pid);return e.exec("COMMIT"),n=!1,c(r)===1}finally{if(n)try{e.exec("ROLLBACK");}catch{}}}function l(e){return A().filter(t=>t.processGroupId===e)}function S(e,t){return l(e).some(n=>P(n.command)&&v(n.command,t))}async function se(e,t){if(!S(e,t))return false;console.error(`[devflow] Terminating untracked server process group ${e}`);try{process.kill(-e,"SIGTERM");}catch{}if(await u(()=>l(e).length===0,W))return true;if(!S(e,t))return false;try{process.kill(-e,"SIGKILL");}catch{}return u(()=>l(e).length===0,B)}async function D(e,t,n){return l(n).length===0||await se(n,t)?oe(e,t):false}async function ie(){let e=join(homedir(),".devflow");mkdirSync(e,{recursive:true});let t=$(join(e,"server-bootstrap.sqlite")),n,r,o=false;try{for(;;){let i=await j(t);if(i.action==="skip")return;if(i.action==="cleanup"){if(!await D(t,i.token,i.processGroupId))throw new Error("claimed server process group cleanup did not complete");continue}n=i.token;break}if(await h("DEVFLOW_SERVER_BOOTSTRAP_TEST_INTENT_READY_FILE"),r=await J(n),!r.pid)throw new Error("npx launched without a PID");let a=r.pid,s=await Z(n,a);if(!s){let i=m(n,a);if(!i)throw new Error("npx process group ownership could not be validated");ee(t,n,i),r.unref(),console.error(`[devflow] Server package launch still warming (PID ${i.wrapperPid})`);return}await h("DEVFLOW_SERVER_BOOTSTRAP_TEST_AFTER_SPAWN_READY_FILE"),re(t,n,s),o=!0,r.unref(),console.error(`[devflow] Server starting in background (PID ${s.wrapperPid})`);}catch(a){if(n&&r?.pid&&!o){let s=false;try{s=ne(t,n,process.pid);}catch(i){E(i);}s?await D(t,n,r.pid)||console.error(`[devflow] Server process group ${r.pid} cleanup did not complete`):(console.error(`[devflow] Server cleanup claim lost for token ${n}`),r.unref());}else if(n&&!r)try{te(t,n);}catch(s){E(s);}throw a}finally{try{t.close();}catch{}}}ie().catch(E).then(()=>{process.exitCode=0;},()=>{process.exitCode=0;});
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {request}from'http';import {existsSync,readFileSync,readdirSync,unlinkSync,mkdirSync,writeFileSync}from'fs';import {join}from'path';import {createHash}from'crypto';import {getLocalApiKey,getProjectStateDir}from'@devflow-tools/sdk';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {homedir}from'os';import {MemoryGate}from'@devflow-tools/memory-engine';function b(i){return i??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function I(i){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(b(i))}var O=1e4,B=3e4,g=500;function G(i,t,e){return new Promise(n=>{try{let r=new URL(i),o=request({hostname:r.hostname,port:r.port||80,path:r.pathname+r.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":e,"Content-Length":Buffer.byteLength(t)},timeout:5e3},s=>{let l=[];s.on("data",a=>l.push(a)),s.on("end",()=>{let a=Buffer.concat(l).toString();n(s.statusCode!=null&&s.statusCode>=200&&s.statusCode<300?a:null);});});o.on("error",()=>n(null)),o.on("timeout",()=>{o.destroy(),n(null);}),o.write(t),o.end();}catch{n(null);}})}var y=class{constructor(t){this.retryScheduled=false;this.apiUrl=t?.apiUrl??process.env.DEVFLOW_API_URL??"http://127.0.0.1:13337",this.apiKey=t?.apiKey??getLocalApiKey(),this.cacheDir=t?.cacheDir??join(process.env.DEVFLOW_STATE_DIR??join(homedir(),".devflow","global"),"telemetry-cache"),this.legacyCacheDir=t?.legacyCacheDir??(t?.cacheDir?null:join(homedir(),".devflow","telemetry-cache")),this.database=t?.database??null,this.ownsDatabase=!t?.database;}async sendEvent(t){let e={...t,input:this.truncateInput(t.input)};return this.commitOrCache("tool_call",e)?(this.postHttp("/api/telemetry/tool-call",e),t.eventId):null}async sendExecutionStart(t,e,n,r){let o={executionId:t,sessionId:e,skillName:n,startedAt:r};this.commitOrCache("execution_start",o)&&this.postHttp("/api/telemetry/skill-execution/start",o);}async sendSessionStart(t,e,n){let r={id:t,projectRoot:e,startedAt:n,label:e.split("/").pop()??"unknown"},o=this.commitOrCache("session_start",r);return o&&this.postHttp("/api/telemetry/sessions",r),o}async completeEvent(t){let e=this.commitOrCache("complete_event",t);return e&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp("/api/telemetry/tool-call/output",t)),e}async endSession(t,e=Date.now()){let n={sessionId:t,finishedAt:e},r=this.commitOrCache("session_end",n);return r&&(this.getDatabase().aggregatePendingToolMetrics(),this.postHttp(`/api/telemetry/sessions/${encodeURIComponent(t)}/close`,{finishedAt:e})),r}async flushCache(){try{let n=this.getDatabase(),r=n.listTelemetryFailures({unresolvedOnly:!0,limit:g}).reverse();for(let o of r)try{this.applyOperation(o.operation,o.payload),n.resolveTelemetryFailure(o.id);}catch{}n.trimTelemetryFailures(g);}catch{}let e=[...new Set([this.cacheDir,this.legacyCacheDir].filter(n=>!!n))].filter(n=>existsSync(n)).flatMap(n=>readdirSync(n).filter(r=>r.endsWith(".json")).map(r=>{let o=join(n,r);try{return {cacheFile:o,envelope:J(JSON.parse(readFileSync(o,"utf8")),r)}}catch{return null}})).filter(n=>n!==null).sort((n,r)=>n.envelope.timestamp-r.envelope.timestamp||P(n.envelope.operation)-P(r.envelope.operation));for(let{cacheFile:n,envelope:r}of e)try{let o=this.getDatabase();o.insertTelemetryFailure({id:r.id,operation:r.operation,payload:r.payload,error:r.failure,createdAt:r.timestamp}),this.applyOperation(r.operation,r.payload),o.resolveTelemetryFailure(r.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(t,e){try{return this.applyOperation(t,e),!0}catch(n){return this.cacheOperation(t,e,n),false}}applyOperation(t,e){let n=this.getDatabase();switch(t){case "tool_call":n.insertToolCallEvent(e);return;case "execution_start":n.insertSkillExecution({executionId:e.executionId,sessionId:e.sessionId,skillName:e.skillName,startedAt:e.startedAt,status:"running"});return;case "session_start":n.insertSession(e),n.insertRun({id:M(e.id),source:"hook",tool:"session",input:{projectRoot:e.projectRoot},status:"active",startedAt:e.startedAt,tokenUsed:0,metadata:{sessionId:e.id,projectRoot:e.projectRoot}});return;case "complete_event":if(!n.updateToolCallEvent(e.eventId,{output:e.output===void 0?void 0:JSON.stringify(e.output),error:e.error,duration:e.duration}))throw new Error(`Tool call event ${e.eventId} is not available for completion`);return;case "session_end":n.closeSession(e.sessionId,e.finishedAt),n.updateRun(M(e.sessionId),{status:"completed",finishedAt:e.finishedAt});return}}cacheOperation(t,e,n){let r=Date.now(),o={id:`failure:${r}:${Math.random().toString(36).slice(2,11)}`,operation:t,payload:e,failure:n instanceof Error?n.message:String(n),timestamp:r};try{let s=this.getDatabase();s.insertTelemetryFailure({id:o.id,operation:t,payload:e,error:o.failure,createdAt:r}),s.trimTelemetryFailures(g),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let s=join(this.cacheDir,`${r}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(s,JSON.stringify(o,null,2),{mode:384}),this.trimCompatibilityCache(),this.scheduleRetry();}catch{}}trimCompatibilityCache(){try{let t=readdirSync(this.cacheDir).filter(e=>e.endsWith(".json")).sort();for(let e of t.slice(0,Math.max(0,t.length-g)))unlinkSync(join(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},B).unref());}postHttp(t,e){G(`${this.apiUrl}${t}`,JSON.stringify(e),this.apiKey);}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=O?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,O)}...`}}};function P(i){return ["session_start","execution_start","tool_call","complete_event","session_end"].indexOf(i)}function M(i){return `hook-run:${i}`}function J(i,t){if(!i||typeof i!="object")throw new Error("Invalid telemetry cache envelope");let e=i;if(typeof e.operation=="string"&&e.payload!==void 0)return e;let n=e.type==="tool_call"?"tool_call":e.type==="execution_start"?"execution_start":null;if(!n)throw new Error("Unknown legacy telemetry cache operation");let r=e.payload??{},o=Number(r.timestamp??r.startedAt??Date.now());return {id:`legacy-cache:${t}`,operation:n,payload:r,failure:"Replayed legacy HTTP-first telemetry cache entry",timestamp:o}}async function F(i){let t=!i.memory,e=i.memory??new MemoryGate(i.projectRoot),n=0,r=0;try{await e.forceWarmUp(),i.trigger==="session_end"&&(n=await e.releasePendingDistillLeases(i.sessionId)),r=e.getPendingEventCount();}finally{t&&e.close();}let o={pendingEvents:r,releasedLeases:n,trigger:i.trigger,sessionId:i.sessionId};try{let s=openGlobalDevFlowDatabase();try{let l=Date.now(),a=`distill:${l}:${Math.random().toString(36).slice(2,10)}`;s.recordMemoryDistillCheckpoint({id:a,projectRoot:i.projectRoot,sessionId:i.sessionId,trigger:i.trigger,pendingEvents:r,releasedLeases:n,createdAt:l}),s.insertEvent({kind:"memory_distill_requested",timestamp:l,success:!0,metadata:{...o,projectRoot:i.projectRoot}});}finally{s.close();}}catch{}return o}var ee=process.env.DEVFLOW_SERVER_URL||"http://127.0.0.1:13337",te=getLocalApiKey();function ne(i,t){return new Promise(e=>{let n=JSON.stringify(t),r=new URL(i,ee),o=request({hostname:r.hostname,port:r.port,path:r.pathname,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":te,"Content-Length":Buffer.byteLength(n)},timeout:5e3},()=>e());o.on("error",()=>e()),o.write(n),o.end();})}function _(i){let t=I(i),e=createHash("sha256").update(i).digest("hex").slice(0,12);return [join(t,`session-id-${e}`),join(t,"current-execution-id"),join(t,"current-skill.json"),join(t,"event-map.json")]}function re(i){try{let t=_(i)[0];if(existsSync(t))return readFileSync(t,"utf-8").trim()}catch{}return null}function ie(i){for(let t of _(i))try{existsSync(t)&&unlinkSync(t);}catch{}}async function oe(i,t=b(),e=true,n){let r;try{r=JSON.parse(i);}catch{return}let o=r.session_id||re(t);if(!o)return;let s=n?.telemetry??new y,l=!n?.telemetry;try{try{await s.flushAndAggregate();}catch{}let a;try{a=openGlobalDevFlowDatabase();let L=a.listToolCallEventsBySession(o),C=_(t)[1];if(e&&existsSync(C)){let p="";try{p=readFileSync(C,"utf-8").trim();}catch{}if(p){let h=L.filter(m=>m.executionId===p),c=h.length,d=h.filter(m=>m.isMcpTool).length,T=c-d,w=h.filter(m=>m.toolType==="subagent").length,v=h.map(m=>m.timestamp).filter(Boolean),E=v.length>=2?Math.max(...v)-Math.min(...v):0;try{a.updateSkillExecution(p,{status:"completed",finishedAt:Date.now(),totalToolCalls:c,mcpToolCalls:d,directToolCalls:T,subagentCount:w,totalDuration:E,mcpComplianceRate:c>0?Math.round(d/c*1e4)/100:0}),await ne("/api/telemetry/skill-execution/complete",{executionId:p,finishedAt:Date.now(),status:"completed",summary:{totalToolCalls:c,mcpToolCalls:d,directToolCalls:T,subagentCount:w,totalDuration:E,mcpComplianceRate:c>0?Math.round(d/c*1e4)/100:0}});}catch{}}}e&&a.deleteHookReceipt(t);}catch{}finally{a?.close();}try{await F({projectRoot:t,sessionId:o,trigger:"session_end",memory:n?.memory});}catch{}try{await s.endSession(o),await s.flushAndAggregate();}catch{}}finally{l&&s.close(),e&&ie(t);}}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let i="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{i+=t;}),process.stdin.on("end",async()=>{await oe(i.trim()||process.argv[2]||""),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}
|
|
2
|
+
export{oe as handleSessionEnd};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {request}from'http';import {existsSync,readFileSync}from'fs';import {join}from'path';import {homedir}from'os';import {createHash}from'crypto';import {getLocalApiKey}from'@devflow-tools/sdk';var h=process.env.DEVFLOW_SERVER_URL||"http://127.0.0.1:13337",f=getLocalApiKey();function _(t,e){return new Promise(o=>{let r=JSON.stringify(e),n=new URL(t,h),s=request({hostname:n.hostname,port:n.port,path:n.pathname,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":f,"Content-Length":Buffer.byteLength(r)},timeout:5e3},()=>o());s.on("error",()=>o()),s.write(r),s.end();})}var S=join(homedir(),".devflow"),g=process.env.CLAUDE_PROJECT_DIR||process.cwd(),E=createHash("sha256").update(g).digest("hex").slice(0,12),i=join(S,`session-id-${E}`);function R(){try{if(existsSync(i))return readFileSync(i,"utf-8").trim()}catch{}return null}async function y(t){let e;try{e=JSON.parse(t);}catch{return null}if(e.stop_hook_active)return null;let o=R();return o&&_(`/api/telemetry/sessions/${encodeURIComponent(o)}/tick`,{timestamp:Date.now()}).catch(()=>{}),null}if(process.argv[1]?.endsWith("stop")||process.argv[1]?.endsWith("stop.js")){let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{t+=e;}),process.stdin.on("end",async()=>{await y(t.trim()||process.argv[2]||""),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),4e3).unref();}
|
|
2
|
+
export{y as handleStop};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {createHash}from'node:crypto';import {mkdirSync,appendFileSync}from'node:fs';import {homedir}from'node:os';import {dirname,join}from'node:path';import {MemoryGate}from'@devflow-tools/memory-engine';import'@devflow-tools/database';var g=/(?:^|[.!?。!?]\s*)(?:(?:please\s+)?(?:remember|memorize)\b|(?:请记|(?:请)?记住))/iu,D=/\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 c(e){let t=e.trim();return t&&g.test(t)&&!D.test(t)?t:null}function S(e){let t=createHash("sha256").update(e).digest("hex").slice(0,16),n=process.env.DEVFLOW_STATE_DIR||join(homedir(),".devflow","state",t);return join(n,"memory-intents.jsonl")}function a(e,t){let n=S(e);mkdirSync(dirname(n),{recursive:true}),appendFileSync(n,`${JSON.stringify(t)}
|
|
2
|
+
`,{mode:384});}var m="WARNING: DevFlow is in degraded mode (daemon unreachable): 4-Gate enforcement and memory prefetch cache are unavailable. Run `devflow doctor` for details.";function u(){return process.env.DEVFLOW_HOOK_DEGRADED==="1"}var p=process.env.CLAUDE_PROJECT_DIR||process.cwd();async function I(e){let t=u()?{additionalContext:m}:{},n;try{n=JSON.parse(e);}catch{return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...t}}}let r=n.prompt||"";if(!r.trim())return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...t}};let s=c(r);if(s)try{a(p,{content:s,sessionId:n.session_id,createdAt:Date.now()});}catch{}let o=new MemoryGate(p);try{await o.forceWarmUp(),await o.recordUserMessage(r.slice(0,2e3));}catch{}finally{o.close();}return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...t}}}if(process.argv[1]?.endsWith("user-prompt-submit")||process.argv[1]?.endsWith("user-prompt-submit.js")){let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t;}),process.stdin.on("end",async()=>{let t=await I(e.trim()||process.argv[2]||"");console.log(JSON.stringify(t)),process.exit(0);}),process.stdin.on("error",()=>{console.log(JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow"}})),process.exit(0);}),setTimeout(()=>{console.log(JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow"}})),process.exit(0);},3e4).unref();}export{I as handleUserPromptSubmit};
|
|
@@ -2,13 +2,12 @@
|
|
|
2
2
|
name: devflow:graphql
|
|
3
3
|
description: GraphQL 专家 — Schema 设计、N+1 检测、Resolver 优化、安全审计
|
|
4
4
|
required_mcp_tools:
|
|
5
|
-
- graphql_new_graphql_type
|
|
6
5
|
- graphql_diagnose_bug
|
|
7
6
|
---
|
|
8
7
|
|
|
9
8
|
<HARD-GATE>
|
|
10
9
|
收到 devflow:graphql 时,必须先调用以下 MCP 工具之一:
|
|
11
|
-
|
|
10
|
+
graphql_diagnose_bug
|
|
12
11
|
</HARD-GATE>
|
|
13
12
|
|
|
14
13
|
## MANDATORY FIRST STEP - Skill Registration
|
|
@@ -16,11 +15,10 @@ graphql_new_graphql_type / graphql_diagnose_bug
|
|
|
16
15
|
> **IMPORTANT: Before ANY other action, execute the registration command below. This is NON-NEGOTIABLE.**
|
|
17
16
|
|
|
18
17
|
```bash
|
|
19
|
-
mkdir -p ~/.devflow && echo '{"name":"devflow:graphql","required_mcp_tools":["
|
|
18
|
+
mkdir -p ~/.devflow && echo '{"name":"devflow:graphql","required_mcp_tools":["graphql_diagnose_bug"],"description":"devflow:graphql skill","registeredAt":'"$(date +%s)000"'}' > ~/.devflow/current-skill.json
|
|
20
19
|
```
|
|
21
20
|
|
|
22
21
|
After registration, you **MUST** use ONLY these MCP tools for all work in this skill:
|
|
23
|
-
- `mcp__devflow__graphql_new_graphql_type`
|
|
24
22
|
- `mcp__devflow__graphql_diagnose_bug`
|
|
25
23
|
|
|
26
24
|
**Never use direct tools** (Read, Write, Edit, Bash, Grep, etc.) for tasks that can be handled by the MCP tools above.
|
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
name: devflow:nest
|
|
3
3
|
description: NestJS 专家 — 模块架构、守卫调试、微服务配置、Swagger 生成
|
|
4
4
|
required_mcp_tools:
|
|
5
|
-
- nest_new_module
|
|
6
5
|
- nest_diagnose_bug
|
|
6
|
+
- nest_new_module
|
|
7
7
|
---
|
|
8
8
|
|
|
9
9
|
<HARD-GATE>
|
|
10
10
|
收到 devflow:nest 时,必须先调用以下 MCP 工具之一:
|
|
11
|
-
|
|
11
|
+
nest_diagnose_bug / nest_new_module
|
|
12
12
|
</HARD-GATE>
|
|
13
13
|
|
|
14
14
|
## MANDATORY FIRST STEP - Skill Registration
|
|
@@ -16,12 +16,12 @@ nest_new_module / nest_diagnose_bug
|
|
|
16
16
|
> **IMPORTANT: Before ANY other action, execute the registration command below. This is NON-NEGOTIABLE.**
|
|
17
17
|
|
|
18
18
|
```bash
|
|
19
|
-
mkdir -p ~/.devflow && echo '{"name":"devflow:nest","required_mcp_tools":["
|
|
19
|
+
mkdir -p ~/.devflow && echo '{"name":"devflow:nest","required_mcp_tools":["nest_diagnose_bug","nest_new_module"],"description":"devflow:nest skill","registeredAt":'"$(date +%s)000"'}' > ~/.devflow/current-skill.json
|
|
20
20
|
```
|
|
21
21
|
|
|
22
22
|
After registration, you **MUST** use ONLY these MCP tools for all work in this skill:
|
|
23
|
-
- `mcp__devflow__nest_new_module`
|
|
24
23
|
- `mcp__devflow__nest_diagnose_bug`
|
|
24
|
+
- `mcp__devflow__nest_new_module`
|
|
25
25
|
|
|
26
26
|
**Never use direct tools** (Read, Write, Edit, Bash, Grep, etc.) for tasks that can be handled by the MCP tools above.
|
|
27
27
|
|
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
name: devflow:nextjs
|
|
3
3
|
description: Next.js 专家 — App Router、SSR/SSG/ISR、Server Components、Middleware、部署
|
|
4
4
|
required_mcp_tools:
|
|
5
|
-
- nextjs_new_page
|
|
6
5
|
- nextjs_diagnose_bug
|
|
6
|
+
- nextjs_new_page
|
|
7
7
|
---
|
|
8
8
|
|
|
9
9
|
<HARD-GATE>
|
|
10
10
|
收到 devflow:nextjs 时,必须先调用以下 MCP 工具之一:
|
|
11
|
-
|
|
11
|
+
nextjs_diagnose_bug / nextjs_new_page
|
|
12
12
|
</HARD-GATE>
|
|
13
13
|
|
|
14
14
|
## MANDATORY FIRST STEP - Skill Registration
|
|
@@ -16,12 +16,12 @@ nextjs_new_page / nextjs_diagnose_bug
|
|
|
16
16
|
> **IMPORTANT: Before ANY other action, execute the registration command below. This is NON-NEGOTIABLE.**
|
|
17
17
|
|
|
18
18
|
```bash
|
|
19
|
-
mkdir -p ~/.devflow && echo '{"name":"devflow:nextjs","required_mcp_tools":["
|
|
19
|
+
mkdir -p ~/.devflow && echo '{"name":"devflow:nextjs","required_mcp_tools":["nextjs_diagnose_bug","nextjs_new_page"],"description":"devflow:nextjs skill","registeredAt":'"$(date +%s)000"'}' > ~/.devflow/current-skill.json
|
|
20
20
|
```
|
|
21
21
|
|
|
22
22
|
After registration, you **MUST** use ONLY these MCP tools for all work in this skill:
|
|
23
|
-
- `mcp__devflow__nextjs_new_page`
|
|
24
23
|
- `mcp__devflow__nextjs_diagnose_bug`
|
|
24
|
+
- `mcp__devflow__nextjs_new_page`
|
|
25
25
|
|
|
26
26
|
**Never use direct tools** (Read, Write, Edit, Bash, Grep, etc.) for tasks that can be handled by the MCP tools above.
|
|
27
27
|
|
|
@@ -2,17 +2,16 @@
|
|
|
2
2
|
name: devflow:react
|
|
3
3
|
description: React 18 专家能力 — Bug 诊断、组件重构、性能优化、Hooks 审查
|
|
4
4
|
required_mcp_tools:
|
|
5
|
-
- react_diagnose_bug
|
|
6
|
-
- react_new_feature
|
|
7
|
-
- react_audit_performance
|
|
8
5
|
- react_review_hooks
|
|
6
|
+
- react_audit_performance
|
|
9
7
|
- react_refactor_component
|
|
8
|
+
- react_diagnose_bug
|
|
10
9
|
- react_new_component
|
|
11
10
|
---
|
|
12
11
|
|
|
13
12
|
<HARD-GATE>
|
|
14
13
|
收到 devflow:react 时,必须先调用以下 MCP 工具之一:
|
|
15
|
-
|
|
14
|
+
react_review_hooks / react_audit_performance / react_refactor_component / react_diagnose_bug / react_new_component
|
|
16
15
|
</HARD-GATE>
|
|
17
16
|
|
|
18
17
|
## MANDATORY FIRST STEP - Skill Registration
|
|
@@ -20,15 +19,14 @@ react_diagnose_bug / react_new_feature / react_audit_performance / react_review_
|
|
|
20
19
|
> **IMPORTANT: Before ANY other action, execute the registration command below. This is NON-NEGOTIABLE.**
|
|
21
20
|
|
|
22
21
|
```bash
|
|
23
|
-
mkdir -p ~/.devflow && echo '{"name":"devflow:react","required_mcp_tools":["
|
|
22
|
+
mkdir -p ~/.devflow && echo '{"name":"devflow:react","required_mcp_tools":["react_review_hooks","react_audit_performance","react_refactor_component","react_diagnose_bug","react_new_component"],"description":"devflow:react skill","registeredAt":'"$(date +%s)000"'}' > ~/.devflow/current-skill.json
|
|
24
23
|
```
|
|
25
24
|
|
|
26
25
|
After registration, you **MUST** use ONLY these MCP tools for all work in this skill:
|
|
27
|
-
- `mcp__devflow__react_diagnose_bug`
|
|
28
|
-
- `mcp__devflow__react_new_feature`
|
|
29
|
-
- `mcp__devflow__react_audit_performance`
|
|
30
26
|
- `mcp__devflow__react_review_hooks`
|
|
27
|
+
- `mcp__devflow__react_audit_performance`
|
|
31
28
|
- `mcp__devflow__react_refactor_component`
|
|
29
|
+
- `mcp__devflow__react_diagnose_bug`
|
|
32
30
|
- `mcp__devflow__react_new_component`
|
|
33
31
|
|
|
34
32
|
**Never use direct tools** (Read, Write, Edit, Bash, Grep, etc.) for tasks that can be handled by the MCP tools above.
|