@devflow-tools/claude-code-plugin 0.14.4 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import {appendFileSync,existsSync,readdirSync,readFileSync,unlinkSync,mkdirSync,writeFileSync}from'fs';import {join,dirname}from'path';import {homedir}from'os';import {createHash}from'crypto';import {request}from'http';import {fileURLToPath}from'url';var N=1e4,Y=3e4,z=300*1e3;function y(e,t,o){return new Promise(n=>{try{let r=new URL(e),i=request({hostname:r.hostname,port:r.port||80,path:r.pathname+r.search,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":o,"Content-Length":Buffer.byteLength(t)},timeout:5e3},s=>{let a=[];s.on("data",p=>a.push(p)),s.on("end",()=>{let p=Buffer.concat(a).toString();n(s.statusCode!=null&&s.statusCode>=200&&s.statusCode<300?p:null);});});i.on("error",()=>n(null)),i.on("timeout",()=>{i.destroy(),n(null);}),i.write(t),i.end();}catch{n(null);}})}var S=class{constructor(t){this.retryScheduled=false;this.retryAttempts=0;this.apiUrl=t?.apiUrl??process.env.DEVFLOW_API_URL??"http://127.0.0.1:13337",this.apiKey=t?.apiKey??process.env.DEVFLOW_API_KEY??"dev-key-000000",this.cacheDir=t?.cacheDir??join(homedir(),".devflow","telemetry-cache");}async sendEvent(t){let o=this.truncateInput(t.input),n={...t,input:o},r=`${this.apiUrl}/api/telemetry/tool-call`,i=await y(r,JSON.stringify(n),this.apiKey);if(i)try{let s=JSON.parse(i),a=s.data?.eventId??s.eventId??null;if(a)return a}catch{}return this.cacheEvent({type:"tool_call",payload:n}),null}async sendExecutionStart(t,o,n,r){let i={executionId:t,sessionId:o,skillName:n,startedAt:r},s=`${this.apiUrl}/api/telemetry/skill-execution/start`;await y(s,JSON.stringify(i),this.apiKey)||this.cacheEvent({type:"execution_start",payload:i});}async sendSessionStart(t,o,n){let r={id:t,projectRoot:o,startedAt:n,label:o.split("/").pop()??"unknown"},i=`${this.apiUrl}/api/telemetry/sessions`;return await y(i,JSON.stringify(r),this.apiKey)!==null}async flushCache(){if(!existsSync(this.cacheDir))return;let t=readdirSync(this.cacheDir).filter(o=>o.endsWith(".json"));for(let o of t)try{let n=join(this.cacheDir,o),r=readFileSync(n,"utf8"),i=JSON.parse(r),s=i.type==="execution_start"?"/api/telemetry/skill-execution/start":"/api/telemetry/tool-call",a=`${this.apiUrl}${s}`;await y(a,JSON.stringify(i.payload),this.apiKey)&&unlinkSync(n);}catch{}}cacheEvent(t){try{existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:!0});let o=join(this.cacheDir,`${Date.now()}_${Math.random().toString(36).slice(2,11)}.json`);writeFileSync(o,JSON.stringify(t,null,2)),this.scheduleRetry();}catch{}}scheduleRetry(){if(this.retryScheduled)return;this.retryScheduled=true;let t=Math.min(Y*Math.pow(2,this.retryAttempts),z);setTimeout(()=>{this.retryScheduled=false,this.flushCache().then(()=>{this.retryAttempts=0;}).catch(()=>{this.retryAttempts++;});},t).unref();}truncateInput(t){let o=JSON.stringify(t);return o.length<=N?t:{_truncated:true,_original_size:o.length,_preview:o.substring(0,N)+"..."}}};var nt=1800*1e3;function P(){return process.env.DEVFLOW_STATE_DIR??join(homedir(),".devflow")}function ot(){if(process.env.CLAUDE_PLUGIN_ROOT)return process.env.CLAUDE_PLUGIN_ROOT;try{let e=fileURLToPath(import.meta.url);return join(dirname(e),"..","..")}catch{return process.cwd()}}function rt(){let e=ot(),t=[join(e,"dist","command-registry.json"),join(e,"command-registry.json")],o=[];try{for(let n of t){if(existsSync(n)){let r=JSON.parse(readFileSync(n,"utf8")).commands;if(r)return r}o.push(`${n}: ${existsSync(n)?"found":"missing"}`);}}catch(n){o.push(`error: ${n.message}`);}try{writeFileSync(join(P(),"hook-debug.log"),JSON.stringify({ts:Date.now(),pluginRoot:e,CLAUDE_PLUGIN_ROOT:process.env.CLAUDE_PLUGIN_ROOT??"(unset)",cwd:process.cwd(),paths:o},null,2));}catch{}return null}function A(e){let t=rt();return t?t[e]?.mcpTools??[]:[]}var k=class{constructor(t){this.stateDir=P();}detect(){let t=join(this.stateDir,"current-skill.json");if(!existsSync(t))return null;try{let o=readFileSync(t,"utf8"),n=JSON.parse(o);return !n.registeredAt||Date.now()-n.registeredAt>nt?(this.endExecution(),null):n}catch{return null}}startExecution(t,o){existsSync(this.stateDir)||mkdirSync(this.stateDir,{recursive:true});let n=this.getCurrentExecutionId();if(n)return n;let r=`exec_${Date.now()}_${Math.random().toString(36).slice(2,11)}`;return writeFileSync(join(this.stateDir,"current-execution-id"),r),writeFileSync(join(this.stateDir,"current-skill.json"),JSON.stringify({name:t,required_mcp_tools:o?.required_mcp_tools??[],registeredAt:Date.now()})),r}getCurrentExecutionId(){let t=join(this.stateDir,"current-execution-id");if(!existsSync(t))return null;try{return readFileSync(t,"utf8").trim()}catch{return null}}endExecution(){let t=join(this.stateDir,"current-skill.json"),o=join(this.stateDir,"current-execution-id");try{existsSync(t)&&unlinkSync(t);}catch{}try{existsSync(o)&&unlinkSync(o);}catch{}}};function m(){return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}}function U(e){return {hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",additionalContext:e}}}var g=join(homedir(),".devflow");function M(){existsSync(g)||mkdirSync(g,{recursive:true});}function lt(){try{let e=join(g,"session-id");if(existsSync(e))return readFileSync(e,"utf-8").trim()}catch{}return null}function ut(e){M(),writeFileSync(join(g,"session-id"),e);}function pt(e,t,o){M();let n=join(g,"event-map.json"),r=[];try{existsSync(n)&&(r=JSON.parse(readFileSync(n,"utf-8")));}catch{}r.push({toolName:e,eventId:t,timestamp:o}),writeFileSync(n,JSON.stringify(r));}function dt(e){switch(e){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"}}var j={Grep:"get_project_context",Glob:"get_project_context",Agent:"get_project_context",WebSearch:"get_knowledge",WebFetch:"get_knowledge",Bash:"get_project_context"};function ht(e){switch(e){case "WebSearch":case "WebFetch":return 1;case "Agent":return 3;case "Grep":case "Glob":return 3;case "Bash":return 5;default:return 2}}function mt(){let e=process.env.CLAUDE_PROJECT_DIR||process.cwd(),t=createHash("sha256").update(e).digest("hex").slice(0,16);return join(process.env.TMPDIR||"/tmp",".devflow-receipts",`${t}.json`)}function $(){try{let e=mt();return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):{}}catch{return {}}}function gt(e){let t=j[e];if(!t)return null;let n=$().bypassCount??0,r=ht(e);return n<r?null:`Direct tool "${e}" blocked (${n} prior violations). Use mcp__devflow__${t} instead.`}async function ft(e){try{if(!e||e.trim()==="")return m();let t=JSON.parse(e),o=Date.now(),n=process.env.CLAUDE_PROJECT_DIR||process.cwd(),r=n.split("/").pop()||"unknown",i=new S,s=lt();s||(s=`session:${r}:${Date.now().toString(36)}`,ut(s),i.sendSessionStart(s,n,Date.now()).catch(()=>{}));let a=new k;if(t.tool_name==="Skill"){let c=t.tool_input?.skill;if(c&&c.startsWith("devflow:")){let _=a.startExecution(c,{required_mcp_tools:A(c)});i.sendExecutionStart(_,s,c,Date.now()).catch(()=>{});}}let p=a.detect(),u=t.tool_name.startsWith("mcp__"),F=u?t.tool_name.replace(/^mcp__[^_]+__/,""):void 0,w=p?.required_mcp_tools??[],D=w.length>0,E=D&&!u&&t.tool_name!=="Skill",d;if(E){let c=w[0]||"get_project_context";d=U(`\u5EFA\u8BAE\u5148\u8C03\u7528 ${c} \u83B7\u53D6\u9879\u76EE\u4E0A\u4E0B\u6587\uFF0C\u7ED3\u679C\u4F1A\u66F4\u7CBE\u786E\u3002`);}else if(!u&&t.tool_name!=="Skill")if(gt(t.tool_name)){let _=j[t.tool_name]||"get_project_context";d=U(`\u5DF2\u591A\u6B21\u4F7F\u7528 ${t.tool_name}\uFF0C\u5EFA\u8BAE\u5207\u6362\u5230 ${_} \u83B7\u53D6\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587\u3002`);}else d=m();else d=m();let J=a.getCurrentExecutionId()??s,I={eventId:`evt_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,executionId:J,sessionId:s,timestamp:Date.now(),toolName:t.tool_name,toolType:u?"mcp":t.tool_name==="Agent"?"subagent":"direct",isMcpTool:u,mcpToolName:F,mcpEnforced:u&&D,mcpFallback:!u&&D,kind:dt(t.tool_name),input:t.tool_input,duration:0,blocked:d.hookSpecificOutput.permissionDecision==="deny"};i.sendEvent(I).then(c=>{c&&pt(t.tool_name,c,I.timestamp);}).catch(()=>{});try{let c=$(),_={ts:o,tool:t.tool_name,skill:p?.name??"(none)",requiredTools:w,isMcp:u,enforce:E,stateless:!E&&!u&&t.tool_name!=="Skill",bypassCount:c.bypassCount??0,decision:d.hookSpecificOutput.permissionDecision,env_CLAUDE_PLUGIN_ROOT:process.env.CLAUDE_PLUGIN_ROOT??"(unset)",cwd:process.cwd()},W=join(g,"hook-debug.jsonl");appendFileSync(W,JSON.stringify(_)+`
2
- `);}catch{}return d}catch{return m()}}if(process.argv[1]?.endsWith("pre-tool-use")||process.argv[1]?.endsWith("pre-tool-use.js")){let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t;}),process.stdin.on("end",async()=>{let t=await ft(e);console.log(JSON.stringify(t));}),process.stdin.on("error",()=>{console.log(JSON.stringify(m())),process.exit(0);}),setTimeout(()=>{console.log(JSON.stringify(m())),process.exit(0);},4e3).unref();}export{ft as handlePreToolUse};
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;});
@@ -1,2 +1,2 @@
1
- import {get,request}from'http';import {existsSync,readFileSync,unlinkSync}from'fs';import {join}from'path';import {homedir}from'os';var I=process.env.DEVFLOW_SERVER_URL||"http://127.0.0.1:13337",x=process.env.DEVFLOW_API_KEY||"dev-key-000000",A=process.env.CLAUDE_PROJECT_DIR||process.cwd();function F(e){return new Promise(o=>{let i=new URL(e,I);get(i.toString(),{headers:{"X-API-Key":x},timeout:5e3},t=>{let n=[];t.on("data",c=>n.push(c)),t.on("end",()=>{try{o(JSON.parse(Buffer.concat(n).toString()));}catch{o(null);}});}).on("error",()=>o(null));})}function g(e,o){return new Promise(i=>{let l=JSON.stringify(o),t=new URL(e,I),n=request({hostname:t.hostname,port:t.port,path:t.pathname,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":x,"Content-Length":Buffer.byteLength(l)},timeout:5e3},()=>i());n.on("error",()=>i()),n.write(l),n.end();})}var u=join(homedir(),".devflow"),y=join(u,"session-id"),E=join(u,"current-execution-id"),U=join(u,"current-skill.json"),k=join(u,"event-map.json");function j(){try{if(existsSync(y))return readFileSync(y,"utf-8").trim()}catch{}return null}function B(){for(let e of [y,E,U,k])try{existsSync(e)&&unlinkSync(e);}catch{}}async function J(e){let o;try{o=JSON.parse(e);}catch{return}let i=o.session_id||j();if(!i)return;let t=(await F(`/api/telemetry/sessions/${encodeURIComponent(i)}/events`))?.data||[],n=t.length,c=t.filter(s=>s.isMcpTool).length,S=n-c,_=t.filter(s=>s.toolType==="subagent").length,d=t.map(s=>s.timestamp).filter(Boolean),R=d.length>=2?Math.max(...d)-Math.min(...d):0,v=n>0?Math.round(c/n*1e4)/100:0;if(existsSync(E)){let s="";try{s=readFileSync(E,"utf-8").trim();}catch{}if(s){let p=t.filter(r=>r.executionId===s),m=p.length,h=p.filter(r=>r.isMcpTool).length,w=m-h,L=p.filter(r=>r.toolType==="subagent").length,f=p.map(r=>r.timestamp).filter(Boolean),P=f.length>=2?Math.max(...f)-Math.min(...f):0;try{await g("/api/telemetry/skill-execution/complete",{executionId:s,finishedAt:Date.now(),status:"completed",summary:{totalToolCalls:m,mcpToolCalls:h,directToolCalls:w,subagentCount:L,totalDuration:P,mcpComplianceRate:m>0?Math.round(h/m*1e4)/100:0}});}catch{}}}await g(`/api/telemetry/sessions/${encodeURIComponent(i)}/close`,{finishedAt:Date.now(),stats:{totalToolCalls:n,mcpToolCalls:c,directToolCalls:S,subagentCount:_,totalDuration:R,mcpComplianceRate:v}}),g(`/api/memory/process?rootPath=${encodeURIComponent(A)}`,{trigger:"session_end",sessionId:i}).catch(()=>{}),B();}if(process.argv[1]?.endsWith("session-end")||process.argv[1]?.endsWith("session-end.js")){let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",o=>{e+=o;}),process.stdin.on("end",async()=>{await J(e.trim()||process.argv[2]||""),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),1e4).unref();}
2
- export{J as handleSessionEnd};
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};
@@ -1,2 +1,2 @@
1
- import {request}from'http';import {existsSync,readFileSync}from'fs';import {join}from'path';import {homedir}from'os';var m=process.env.DEVFLOW_SERVER_URL||"http://127.0.0.1:13337",l=process.env.DEVFLOW_API_KEY||"dev-key-000000";function h(t,e){return new Promise(n=>{let r=JSON.stringify(e),o=new URL(t,m),s=request({hostname:o.hostname,port:o.port,path:o.pathname,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":l,"Content-Length":Buffer.byteLength(r)},timeout:5e3},()=>n());s.on("error",()=>n()),s.write(r),s.end();})}var f=join(homedir(),".devflow"),i=join(f,"session-id");function S(){try{if(existsSync(i))return readFileSync(i,"utf-8").trim()}catch{}return null}async function _(t){let e;try{e=JSON.parse(t);}catch{return null}if(e.stop_hook_active)return null;let n=S();return n&&h(`/api/telemetry/sessions/${encodeURIComponent(n)}/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 _(t.trim()||process.argv[2]||""),process.exit(0);}),process.stdin.on("error",()=>process.exit(0)),setTimeout(()=>process.exit(0),4e3).unref();}
2
- export{_ as handleStop};
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};
@@ -1,2 +1,2 @@
1
- import {request}from'http';var c=process.env.DEVFLOW_SERVER_URL||"http://127.0.0.1:13337",p=process.env.DEVFLOW_API_KEY||"dev-key-000000",m=process.env.CLAUDE_PROJECT_DIR||process.cwd(),a=[{regex:/\b(remember|记住|save this|保存|记一下)\b/i,score:1},{regex:/^\/memory\b/,score:1},{regex:/\b(prefer|default|以后默认|always use|偏好|preference)\b/i,score:.8},{regex:/\b(no\b|不对|don't|wrong|不是这样|错了|不对的)\b/i,score:.75},{regex:/\b(原因|because|问题在于|root cause|根本原因|why)\b/i,score:.5},{regex:/\b(we\b|我们|项目里|our team|团队|our project)\b/i,score:.3},{regex:/\b(line \d+|above|below|↑|这段|那段代码|the code above)\b/i,score:.2}];function u(t){let e=.1;for(let o of a)o.regex.test(t)&&(e=Math.max(e,o.score));return e}function b(t,e){return new Promise(o=>{let r=JSON.stringify(e),s=new URL(t,c),n=request({hostname:s.hostname,port:s.port,path:s.pathname,method:"POST",headers:{"Content-Type":"application/json","X-API-Key":p,"Content-Length":Buffer.byteLength(r)},timeout:5e3},()=>o());n.on("error",()=>o()),n.write(r),n.end();})}async function g(t){let e;try{e=JSON.parse(t);}catch{return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow"}}}let o=e.prompt||"";if(!o.trim())return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow"}};let r=u(o);return b(`/api/memory/signal?rootPath=${encodeURIComponent(m)}`,{type:"user_message",content:o.slice(0,2e3),score:r,sessionId:e.session_id,timestamp:Date.now()}).catch(()=>{}),{hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow"}}}if(process.argv[1]?.endsWith("user-prompt-submit")||process.argv[1]?.endsWith("user-prompt-submit.js")){let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{t+=e;}),process.stdin.on("end",async()=>{let e=await g(t.trim()||process.argv[2]||"");console.log(JSON.stringify(e)),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();}
2
- export{g as handleUserPromptSubmit};
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};
@@ -11,10 +11,10 @@ INPUT="$(cat)"
11
11
 
12
12
  if [ -f "$CLIENT_JS" ]; then
13
13
  node "$CLIENT_JS" post-tool-use "$INPUT" 2>/dev/null || {
14
- echo "$INPUT" | node "$FALLBACK_JS" 2>/dev/null || true
14
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
15
15
  }
16
16
  elif [ -f "$FALLBACK_JS" ]; then
17
- echo "$INPUT" | node "$FALLBACK_JS" 2>/dev/null || true
17
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
18
18
  fi
19
19
 
20
20
  exit 0
@@ -10,10 +10,10 @@ INPUT="$(cat)"
10
10
 
11
11
  if [ -f "$CLIENT_JS" ]; then
12
12
  node "$CLIENT_JS" post-tool-use-failure "$INPUT" 2>/dev/null || {
13
- echo "$INPUT" | node "$FALLBACK_JS" 2>/dev/null || true
13
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
14
14
  }
15
15
  elif [ -f "$FALLBACK_JS" ]; then
16
- echo "$INPUT" | node "$FALLBACK_JS" 2>/dev/null || true
16
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
17
17
  fi
18
18
 
19
19
  exit 0
package/hooks/pre-compact CHANGED
@@ -10,10 +10,10 @@ INPUT="$(cat)"
10
10
 
11
11
  if [ -f "$CLIENT_JS" ]; then
12
12
  node "$CLIENT_JS" pre-compact "$INPUT" 2>/dev/null || {
13
- echo "$INPUT" | node "$FALLBACK_JS" 2>/dev/null || true
13
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
14
14
  }
15
15
  elif [ -f "$FALLBACK_JS" ]; then
16
- echo "$INPUT" | node "$FALLBACK_JS" 2>/dev/null || true
16
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
17
17
  fi
18
18
 
19
19
  exit 0
@@ -11,13 +11,13 @@ if [ -f "$CLIENT_JS" ]; then
11
11
  node "$CLIENT_JS" pre-tool-use || {
12
12
  echo '[devflow] hook-client failed, trying fallback' >&2
13
13
  if [ -f "$FALLBACK_JS" ]; then
14
- node "$FALLBACK_JS" || echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}'
14
+ DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" || echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"WARNING: DevFlow is in degraded mode (daemon unreachable). Run devflow doctor for details."}}'
15
15
  else
16
- echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}'
16
+ echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"WARNING: DevFlow is in degraded mode (daemon unreachable). Run devflow doctor for details."}}'
17
17
  fi
18
18
  }
19
19
  elif [ -f "$FALLBACK_JS" ]; then
20
- node "$FALLBACK_JS" || echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}'
20
+ DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" || echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"WARNING: DevFlow is in degraded mode (daemon unavailable). Run devflow doctor for details."}}'
21
21
  else
22
- echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}'
22
+ echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","additionalContext":"WARNING: DevFlow is in degraded mode (daemon unavailable). Run devflow doctor for details."}}'
23
23
  fi
package/hooks/session-end CHANGED
@@ -10,10 +10,10 @@ INPUT="$(cat)"
10
10
 
11
11
  if [ -f "$CLIENT_JS" ]; then
12
12
  node "$CLIENT_JS" session-end "$INPUT" 2>/dev/null || {
13
- echo "$INPUT" | node "$FALLBACK_JS" 2>/dev/null || true
13
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
14
14
  }
15
15
  elif [ -f "$FALLBACK_JS" ]; then
16
- echo "$INPUT" | node "$FALLBACK_JS" 2>/dev/null || true
16
+ echo "$INPUT" | DEVFLOW_HOOK_DEGRADED=1 node "$FALLBACK_JS" 2>/dev/null || true
17
17
  fi
18
18
 
19
19
  exit 0