@devflow-tools/devflow 0.16.8 → 0.16.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +59 -58
- package/dist/dashboard/404.html +1 -1
- package/dist/dashboard/accuracy.html +1 -1
- package/dist/dashboard/accuracy.txt +1 -1
- package/dist/dashboard/benchmark.html +1 -1
- package/dist/dashboard/benchmark.txt +1 -1
- package/dist/dashboard/context.html +1 -1
- package/dist/dashboard/context.txt +1 -1
- package/dist/dashboard/doctor.html +1 -1
- package/dist/dashboard/doctor.txt +1 -1
- package/dist/dashboard/executions.html +1 -1
- package/dist/dashboard/executions.txt +1 -1
- package/dist/dashboard/graph.html +1 -1
- package/dist/dashboard/graph.txt +1 -1
- package/dist/dashboard/index.html +1 -1
- package/dist/dashboard/index.txt +1 -1
- package/dist/dashboard/knowledge.html +1 -1
- package/dist/dashboard/knowledge.txt +1 -1
- package/dist/dashboard/memory.html +1 -1
- package/dist/dashboard/memory.txt +1 -1
- package/dist/dashboard/replay.html +1 -1
- package/dist/dashboard/replay.txt +1 -1
- package/dist/dashboard/runs/_.html +1 -1
- package/dist/dashboard/runs/_.txt +1 -1
- package/dist/dashboard/runs.html +1 -1
- package/dist/dashboard/runs.txt +1 -1
- package/dist/dashboard/settings.html +1 -1
- package/dist/dashboard/settings.txt +1 -1
- package/dist/dashboard/timeline.html +1 -1
- package/dist/dashboard/timeline.txt +1 -1
- package/dist/dashboard/tool-metrics.html +1 -1
- package/dist/dashboard/tool-metrics.txt +1 -1
- package/dist/dashboard/workflows.html +1 -1
- package/dist/dashboard/workflows.txt +1 -1
- package/dist/hooks/hook-client.js +6 -6
- package/dist/hooks/hook-daemon.js +9 -9
- package/dist/hooks/post-tool-use.js +3 -3
- package/dist/hooks/pre-tool-use.js +2 -2
- package/dist/hooks/user-prompt-submit.js +2 -2
- package/dist/plugin/.claude-plugin/plugin.json +1 -1
- package/dist/plugin/dist/command-registry.json +116 -20
- package/dist/plugin/dist/hooks/hook-client.js +6 -6
- package/dist/plugin/dist/hooks/hook-daemon.js +9 -9
- package/dist/plugin/dist/hooks/post-tool-use.js +3 -3
- package/dist/plugin/dist/hooks/pre-tool-use.js +2 -2
- package/dist/plugin/dist/hooks/user-prompt-submit.js +2 -2
- package/dist/plugin/package.json +7 -7
- package/package.json +13 -13
- package/plugin-registry.json +29 -29
- /package/dist/dashboard/_next/static/{KgbYRVRx1rrkTqJx51q3j → JAGOZdxW2bLxLynmBzFBM}/_buildManifest.js +0 -0
- /package/dist/dashboard/_next/static/{KgbYRVRx1rrkTqJx51q3j → JAGOZdxW2bLxLynmBzFBM}/_ssgManifest.js +0 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import {createHash}from'node:crypto';import {mkdirSync,appendFileSync}from'node:fs';import {homedir as homedir$1}from'node:os';import {dirname,join as join$1}from'node:path';import {MemoryGate}from'@devflow-tools/memory-engine';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';import {existsSync,readFileSync,rmSync,mkdirSync as mkdirSync$1,writeFileSync,renameSync,readdirSync,unlinkSync}from'fs';import {join,dirname as dirname$1}from'path';import {randomUUID}from'crypto';import {getLocalApiKey,getProjectStateDir}from'@devflow-tools/sdk';import {fileURLToPath}from'url';import {request}from'http';import {homedir}from'os';var L=/(?:^|[.!?。!?]\s*)(?:(?:please\s+)?(?:remember|memorize)\b|(?:请记|(?:请)?记住))/iu,J=/\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 S(s){let t=s.trim();return t&&L.test(t)&&!J.test(t)?t:null}function H(s){let t=createHash("sha256").update(s).digest("hex").slice(0,16),e=process.env.DEVFLOW_STATE_DIR||join$1(homedir$1(),".devflow","state",t);return join$1(e,"memory-intents.jsonl")}function D(s,t){let e=H(s);mkdirSync(dirname(e),{recursive:true}),appendFileSync(e,`${JSON.stringify(t)}
|
|
2
|
-
`,{mode:384});}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 b(){return process.env.DEVFLOW_HOOK_DEGRADED==="1"}function W(s){return s??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function f(s){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(W(s))}function Q(s){return Buffer.from(s,"utf8").toString("base64url")}var p=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join(f(t),"hook-sessions");}registerSession(t){let e=t.trim();if(!e)throw new Error("session_id_required");let r=this.get(e);if(r)return r.lastActivityAt=Date.now(),this.persist(r),r;let n=Date.now(),o={sessionId:e,projectRoot:this.projectRoot,requiredMcpTools:[],startedAt:n,lastActivityAt:n};return this.sessions.set(e,o),this.persist(o),o}startExecution(t,e,r){let n=this.registerSession(t);return (!n.executionId||n.skillName!==e)&&(n.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),n.skillName=e,n.requiredMcpTools=[...new Set(r)],n.lastActivityAt=Date.now(),this.persist(n),n}get(t){let e=t.trim();if(!e)return null;let r=this.sessions.get(e);if(r)return r;let n=this.snapshotPath(e);if(!existsSync(n))return null;try{let o=JSON.parse(readFileSync(n,"utf8"));return o.sessionId!==e||o.projectRoot!==this.projectRoot?null:(o.requiredMcpTools=Array.isArray(o.requiredMcpTools)?o.requiredMcpTools:[],this.sessions.set(e,o),o)}catch{return null}}completeExecution(t){let e=this.get(t);if(!e)return null;let r={...e,requiredMcpTools:[...e.requiredMcpTools]};return delete e.executionId,delete e.skillName,e.requiredMcpTools=[],e.lastActivityAt=Date.now(),this.persist(e),r}removeSession(t){let e=t.trim();e&&(this.sessions.delete(e),rmSync(this.snapshotPath(e),{force:true}));}list(){return [...this.sessions.values()]}snapshotPath(t){return join(this.sessionsDir,`${Q(t)}.json`)}persist(t){mkdirSync$1(this.sessionsDir,{recursive:true,mode:448});let e=this.snapshotPath(t.sessionId),r=`${e}.${process.pid}.tmp`;writeFileSync(r,JSON.stringify(t),{mode:384}),renameSync(r,e);}};function ee(s){let t=s.trim().replace(/^\//,"");if(!t.startsWith("devflow:"))return null;let e=t.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(e)?`devflow:${e.toLowerCase()}`:null}function R(s){let t=s.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!t)return null;let e=ee(t[1]);return e?{rawName:t[1],skillName:e}:null}var se=1;function ie(){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 x(s=ie()){let t=[join(s,"dist","command-registry.json"),join(s,"command-registry.json")];for(let e of t)try{if(!existsSync(e))continue;let r=JSON.parse(readFileSync(e,"utf8"));if(r.version!==se||!ae(r.commands)){console.error(`[devflow] command registry contract mismatch: ${e}`);continue}return r.commands}catch(r){console.error(`[devflow] command registry load failed: ${r.message}`);}return null}function ae(s){return !s||typeof s!="object"||Array.isArray(s)?false:Object.values(s).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return I(e.mcpTools)&&I(e.blockedNative)})}function I(s){return Array.isArray(s)&&s.every(t=>typeof t=="string"&&t.length>0)}function E(s){let t=x();return t?t[s]?.mcpTools??[]:[]}var C=1e4,he=3e4,d=500;function ge(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 a=[];i.on("data",c=>a.push(c)),i.on("end",()=>{let c=Buffer.concat(a).toString();r(i.statusCode!=null&&i.statusCode>=200&&i.statusCode<300?c: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.metricAggregationScheduled=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,r,n,o=process.env.CLAUDE_PROJECT_DIR??process.cwd(),i=[]){let a={executionId:t,sessionId:e,skillName:r,startedAt:n,projectRoot:o,requiredMcpTools:i};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(t,e="completed",r=Date.now(),n){let o={executionId:t,status:e,finishedAt:r,metadata:n},i=this.commitOrCache("execution_complete",o);return i&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",o),i}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.postHttp("/api/telemetry/tool-call/output",t),this.scheduleMetricAggregation()),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:d}).reverse();for(let o of n)try{this.applyOperation(o.operation,o.payload),r.resolveTelemetryFailure(o.id);}catch{}r.trimTelemetryFailures(d);}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:fe(JSON.parse(readFileSync(o,"utf8")),n)}}catch{return null}})).filter(r=>r!==null).sort((r,n)=>r.envelope.timestamp-n.envelope.timestamp||M(r.envelope.operation)-M(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":this.ensureParentSession(r,e),r.insertToolCallEvent(e);return;case "execution_start":this.ensureParentSession(r,e),r.insertSkillExecution({executionId:e.executionId,sessionId:e.sessionId,skillName:e.skillName,startedAt:e.startedAt,status:"running",requiredMcpTools:e.requiredMcpTools});return;case "execution_complete":r.reconcileSkillExecution(e.executionId,e.status,e.finishedAt,e.metadata);return;case "session_start":r.ensureSession(e),r.insertRun({id:N(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(N(e.sessionId),{status:"completed",finishedAt:e.finishedAt});return}}ensureParentSession(t,e){let r=typeof e.sessionId=="string"?e.sessionId.trim():"";if(!r)throw new Error("Canonical session ID is required for telemetry");let n=typeof e.projectRoot=="string"&&e.projectRoot.trim()?e.projectRoot:typeof e.input?.projectRoot=="string"&&e.input.projectRoot.trim()?e.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";t.ensureSession({id:r,projectRoot:n,label:n==="unknown"?void 0:n.split("/").pop(),startedAt:Number(e.startedAt??e.timestamp??Date.now())});}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(d),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync$1(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-d)))unlinkSync(join(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},he).unref());}scheduleMetricAggregation(){if(this.metricAggregationScheduled||process.env.DEVFLOW_HOOK_DEGRADED==="1")return;this.metricAggregationScheduled=true,setTimeout(()=>{this.metricAggregationScheduled=false;try{this.getDatabase().aggregatePendingToolMetrics(50)===50&&this.scheduleMetricAggregation();}catch{}},25).unref();}postHttp(t,e){ge(`${this.apiUrl}${t}`,JSON.stringify(e),this.apiKey);}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=C?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,C)}...`}}};function M(s){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(s)}function N(s){return `hook-run:${s}`}function fe(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 m=process.env.CLAUDE_PROJECT_DIR||process.cwd();async function ve(s){let t=b()?{additionalContext:w}:{},e;try{e=JSON.parse(s);}catch{return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...t}}}let r=e.prompt||"";if(!r.trim())return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...t}};let n=S(r);if(n)try{D(m,{content:n,sessionId:e.session_id,createdAt:Date.now()});}catch{}let o=e.session_id?.trim(),i=R(r);if(o&&i){let c=new p(m),P=c.get(o)?.executionId,l=c.startExecution(o,i.skillName,E(i.skillName));if(l.executionId&&l.executionId!==P){let g=new h;try{await g.sendSessionStart(o,m,l.startedAt),await g.sendExecutionStart(l.executionId,o,i.skillName,l.lastActivityAt,m,l.requiredMcpTools);}finally{g.close();}}}let a=new MemoryGate(m);try{await a.forceWarmUp(),o&&await a.recordUserMessage(r.slice(0,2e3),o,r.slice(0,200));}catch{}finally{a.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 s="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{s+=t;}),process.stdin.on("end",async()=>{let t=await ve(s.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();}
|
|
3
|
-
export{
|
|
2
|
+
`,{mode:384});}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 b(){return process.env.DEVFLOW_HOOK_DEGRADED==="1"}function W(s){return s??process.env.CLAUDE_PROJECT_DIR??process.cwd()}function f(s){return process.env.DEVFLOW_STATE_DIR??getProjectStateDir(W(s))}function Q(s){return Buffer.from(s,"utf8").toString("base64url")}var d=class{constructor(t){this.projectRoot=t;this.sessions=new Map;this.sessionsDir=join(f(t),"hook-sessions");}registerSession(t){let e=t.trim();if(!e)throw new Error("session_id_required");let r=this.get(e);if(r)return r.lastActivityAt=Date.now(),this.persist(r),r;let n=Date.now(),o={sessionId:e,projectRoot:this.projectRoot,requiredMcpTools:[],startedAt:n,lastActivityAt:n};return this.sessions.set(e,o),this.persist(o),o}startExecution(t,e,r){let n=this.registerSession(t);return (!n.executionId||n.skillName!==e)&&(n.executionId=`exec_${Date.now()}_${randomUUID().slice(0,8)}`),n.skillName=e,n.requiredMcpTools=[...new Set(r)],n.lastActivityAt=Date.now(),this.persist(n),n}get(t){let e=t.trim();if(!e)return null;let r=this.sessions.get(e);if(r)return r;let n=this.snapshotPath(e);if(!existsSync(n))return null;try{let o=JSON.parse(readFileSync(n,"utf8"));return o.sessionId!==e||o.projectRoot!==this.projectRoot?null:(o.requiredMcpTools=Array.isArray(o.requiredMcpTools)?o.requiredMcpTools:[],this.sessions.set(e,o),o)}catch{return null}}completeExecution(t){let e=this.get(t);if(!e)return null;let r={...e,requiredMcpTools:[...e.requiredMcpTools]};return delete e.executionId,delete e.skillName,e.requiredMcpTools=[],e.lastActivityAt=Date.now(),this.persist(e),r}removeSession(t){let e=t.trim();e&&(this.sessions.delete(e),rmSync(this.snapshotPath(e),{force:true}));}list(){return [...this.sessions.values()]}snapshotPath(t){return join(this.sessionsDir,`${Q(t)}.json`)}persist(t){mkdirSync$1(this.sessionsDir,{recursive:true,mode:448});let e=this.snapshotPath(t.sessionId),r=`${e}.${process.pid}.tmp`;writeFileSync(r,JSON.stringify(t),{mode:384}),renameSync(r,e);}};function ee(s){let t=s.trim().replace(/^\//,"");if(!t.startsWith("devflow:"))return null;let e=t.slice(8).replace(/^devflow-/,"");return /^[a-z0-9][a-z0-9-]*$/i.test(e)?`devflow:${e.toLowerCase()}`:null}function x(s){let t=s.trimStart().match(/^\/(devflow:[a-z0-9][a-z0-9-]*)\b/i);if(!t)return null;let e=ee(t[1]);return e?{rawName:t[1],skillName:e}:null}var se=2,ie=1;function ae(){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 R(s=ae()){let t=[join(s,"dist","command-registry.json"),join(s,"command-registry.json")];for(let e of t)try{if(!existsSync(e))continue;let r=JSON.parse(readFileSync(e,"utf8"));if(r.version!==se&&r.version!==ie||!ce(r.commands)){console.error(`[devflow] command registry contract mismatch: ${e}`);continue}return r.commands}catch(r){console.error(`[devflow] command registry load failed: ${r.message}`);}return null}function ce(s){return !s||typeof s!="object"||Array.isArray(s)?false:Object.values(s).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return I(e.mcpTools)&&I(e.blockedNative)&&(e.source===void 0||e.source==="core"||e.source==="plugin")&&(e.requiresContext===void 0||typeof e.requiresContext=="boolean")&&(e.evidenceMode===void 0||["static","runtime","mixed"].includes(e.evidenceMode))})}function I(s){return Array.isArray(s)&&s.every(t=>typeof t=="string"&&t.length>0)}function E(s){let t=R();return t?t[s]?.mcpTools??[]:[]}var C=1e4,ge=3e4,p=500;function fe(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 a=[];i.on("data",c=>a.push(c)),i.on("end",()=>{let c=Buffer.concat(a).toString();r(i.statusCode!=null&&i.statusCode>=200&&i.statusCode<300?c: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.metricAggregationScheduled=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,r,n,o=process.env.CLAUDE_PROJECT_DIR??process.cwd(),i=[]){let a={executionId:t,sessionId:e,skillName:r,startedAt:n,projectRoot:o,requiredMcpTools:i};this.commitOrCache("execution_start",a)&&this.postHttp("/api/telemetry/skill-execution/start",a);}async sendExecutionComplete(t,e="completed",r=Date.now(),n){let o={executionId:t,status:e,finishedAt:r,metadata:n},i=this.commitOrCache("execution_complete",o);return i&&this.postHttp("/api/telemetry/skill-execution/complete-reconciled",o),i}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.postHttp("/api/telemetry/tool-call/output",t),this.scheduleMetricAggregation()),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:p}).reverse();for(let o of n)try{this.applyOperation(o.operation,o.payload),r.resolveTelemetryFailure(o.id);}catch{}r.trimTelemetryFailures(p);}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:ye(JSON.parse(readFileSync(o,"utf8")),n)}}catch{return null}})).filter(r=>r!==null).sort((r,n)=>r.envelope.timestamp-n.envelope.timestamp||M(r.envelope.operation)-M(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":this.ensureParentSession(r,e),r.insertToolCallEvent(e);return;case "execution_start":this.ensureParentSession(r,e),r.insertSkillExecution({executionId:e.executionId,sessionId:e.sessionId,skillName:e.skillName,startedAt:e.startedAt,status:"running",requiredMcpTools:e.requiredMcpTools});return;case "execution_complete":r.reconcileSkillExecution(e.executionId,e.status,e.finishedAt,e.metadata);return;case "session_start":r.ensureSession(e),r.insertRun({id:N(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(N(e.sessionId),{status:"completed",finishedAt:e.finishedAt});return}}ensureParentSession(t,e){let r=typeof e.sessionId=="string"?e.sessionId.trim():"";if(!r)throw new Error("Canonical session ID is required for telemetry");let n=typeof e.projectRoot=="string"&&e.projectRoot.trim()?e.projectRoot:typeof e.input?.projectRoot=="string"&&e.input.projectRoot.trim()?e.input.projectRoot:process.env.CLAUDE_PROJECT_DIR??"unknown";t.ensureSession({id:r,projectRoot:n,label:n==="unknown"?void 0:n.split("/").pop(),startedAt:Number(e.startedAt??e.timestamp??Date.now())});}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(p),this.scheduleRetry();return}catch{}try{existsSync(this.cacheDir)||mkdirSync$1(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-p)))unlinkSync(join(this.cacheDir,e));}catch{}}scheduleRetry(){this.retryScheduled||(this.retryScheduled=true,setTimeout(()=>{this.retryScheduled=false,this.flushCache();},ge).unref());}scheduleMetricAggregation(){if(this.metricAggregationScheduled||process.env.DEVFLOW_HOOK_DEGRADED==="1")return;this.metricAggregationScheduled=true,setTimeout(()=>{this.metricAggregationScheduled=false;try{this.getDatabase().aggregatePendingToolMetrics(50)===50&&this.scheduleMetricAggregation();}catch{}},25).unref();}postHttp(t,e){fe(`${this.apiUrl}${t}`,JSON.stringify(e),this.apiKey);}truncateInput(t){let e=JSON.stringify(t);return e===void 0||e.length<=C?t:{_truncated:true,_original_size:e.length,_preview:`${e.substring(0,C)}...`}}};function M(s){return ["session_start","execution_start","tool_call","complete_event","execution_complete","session_end"].indexOf(s)}function N(s){return `hook-run:${s}`}function ye(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 m=process.env.CLAUDE_PROJECT_DIR||process.cwd();async function Se(s){let t=b()?{additionalContext:w}:{},e;try{e=JSON.parse(s);}catch{return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...t}}}let r=e.prompt||"";if(!r.trim())return {hookSpecificOutput:{hookEventName:"UserPromptSubmit",permissionDecision:"allow",...t}};let n=S(r);if(n)try{D(m,{content:n,sessionId:e.session_id,createdAt:Date.now()});}catch{}let o=e.session_id?.trim(),i=x(r);if(o&&i){let c=new d(m),P=c.get(o)?.executionId,l=c.startExecution(o,i.skillName,E(i.skillName));if(l.executionId&&l.executionId!==P){let g=new h;try{await g.sendSessionStart(o,m,l.startedAt),await g.sendExecutionStart(l.executionId,o,i.skillName,l.lastActivityAt,m,l.requiredMcpTools);}finally{g.close();}}}let a=new MemoryGate(m);try{await a.forceWarmUp(),o&&await a.recordUserMessage(r.slice(0,2e3),o,r.slice(0,200));}catch{}finally{a.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 s="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{s+=t;}),process.stdin.on("end",async()=>{let t=await Se(s.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();}
|
|
3
|
+
export{Se as handleUserPromptSubmit};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "devflow",
|
|
3
3
|
"description": "DevFlow — Developer Intelligence Platform: project context, code graph, knowledge base, memory engine, and workflow automation with 14 domain plugins",
|
|
4
|
-
"version": "0.16.
|
|
4
|
+
"version": "0.16.9",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "DevFlow"
|
|
7
7
|
},
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version":
|
|
2
|
+
"version": 2,
|
|
3
|
+
"compatibility": 1,
|
|
3
4
|
"commands": {
|
|
4
5
|
"devflow:context": {
|
|
5
6
|
"mcpTools": [
|
|
@@ -16,7 +17,12 @@
|
|
|
16
17
|
"Explore",
|
|
17
18
|
"WebSearch",
|
|
18
19
|
"WebFetch"
|
|
19
|
-
]
|
|
20
|
+
],
|
|
21
|
+
"source": "core",
|
|
22
|
+
"sourceVersion": "0.16.9",
|
|
23
|
+
"requiresContext": true,
|
|
24
|
+
"evidenceMode": "mixed",
|
|
25
|
+
"skillPath": "skills/devflow:context/SKILL.md"
|
|
20
26
|
},
|
|
21
27
|
"devflow:graph": {
|
|
22
28
|
"mcpTools": [
|
|
@@ -30,7 +36,12 @@
|
|
|
30
36
|
"Grep",
|
|
31
37
|
"Glob",
|
|
32
38
|
"Explore"
|
|
33
|
-
]
|
|
39
|
+
],
|
|
40
|
+
"source": "core",
|
|
41
|
+
"sourceVersion": "0.16.9",
|
|
42
|
+
"requiresContext": true,
|
|
43
|
+
"evidenceMode": "mixed",
|
|
44
|
+
"skillPath": "skills/devflow:graph/SKILL.md"
|
|
34
45
|
},
|
|
35
46
|
"devflow:knowledge": {
|
|
36
47
|
"mcpTools": [
|
|
@@ -39,7 +50,12 @@
|
|
|
39
50
|
"blockedNative": [
|
|
40
51
|
"WebSearch",
|
|
41
52
|
"WebFetch"
|
|
42
|
-
]
|
|
53
|
+
],
|
|
54
|
+
"source": "core",
|
|
55
|
+
"sourceVersion": "0.16.9",
|
|
56
|
+
"requiresContext": true,
|
|
57
|
+
"evidenceMode": "mixed",
|
|
58
|
+
"skillPath": "skills/devflow:knowledge/SKILL.md"
|
|
43
59
|
},
|
|
44
60
|
"devflow:memory": {
|
|
45
61
|
"mcpTools": [
|
|
@@ -53,13 +69,23 @@
|
|
|
53
69
|
"Grep",
|
|
54
70
|
"Glob",
|
|
55
71
|
"Explore"
|
|
56
|
-
]
|
|
72
|
+
],
|
|
73
|
+
"source": "core",
|
|
74
|
+
"sourceVersion": "0.16.9",
|
|
75
|
+
"requiresContext": true,
|
|
76
|
+
"evidenceMode": "mixed",
|
|
77
|
+
"skillPath": "skills/devflow:memory/SKILL.md"
|
|
57
78
|
},
|
|
58
79
|
"devflow:workflow": {
|
|
59
80
|
"mcpTools": [
|
|
60
81
|
"run_workflow"
|
|
61
82
|
],
|
|
62
|
-
"blockedNative": []
|
|
83
|
+
"blockedNative": [],
|
|
84
|
+
"source": "core",
|
|
85
|
+
"sourceVersion": "0.16.9",
|
|
86
|
+
"requiresContext": true,
|
|
87
|
+
"evidenceMode": "mixed",
|
|
88
|
+
"skillPath": "skills/devflow:workflow/SKILL.md"
|
|
63
89
|
},
|
|
64
90
|
"devflow:animation": {
|
|
65
91
|
"mcpTools": [
|
|
@@ -75,7 +101,12 @@
|
|
|
75
101
|
"Explore",
|
|
76
102
|
"WebSearch",
|
|
77
103
|
"WebFetch"
|
|
78
|
-
]
|
|
104
|
+
],
|
|
105
|
+
"source": "plugin",
|
|
106
|
+
"sourceVersion": "0.1.0",
|
|
107
|
+
"requiresContext": true,
|
|
108
|
+
"evidenceMode": "mixed",
|
|
109
|
+
"skillPath": "skills/devflow:animation/SKILL.md"
|
|
79
110
|
},
|
|
80
111
|
"devflow:css": {
|
|
81
112
|
"mcpTools": [
|
|
@@ -91,7 +122,12 @@
|
|
|
91
122
|
"Explore",
|
|
92
123
|
"WebSearch",
|
|
93
124
|
"WebFetch"
|
|
94
|
-
]
|
|
125
|
+
],
|
|
126
|
+
"source": "plugin",
|
|
127
|
+
"sourceVersion": "0.1.0",
|
|
128
|
+
"requiresContext": true,
|
|
129
|
+
"evidenceMode": "mixed",
|
|
130
|
+
"skillPath": "skills/devflow:css/SKILL.md"
|
|
95
131
|
},
|
|
96
132
|
"devflow:docker": {
|
|
97
133
|
"mcpTools": [
|
|
@@ -107,7 +143,12 @@
|
|
|
107
143
|
"Explore",
|
|
108
144
|
"WebSearch",
|
|
109
145
|
"WebFetch"
|
|
110
|
-
]
|
|
146
|
+
],
|
|
147
|
+
"source": "plugin",
|
|
148
|
+
"sourceVersion": "0.1.0",
|
|
149
|
+
"requiresContext": true,
|
|
150
|
+
"evidenceMode": "mixed",
|
|
151
|
+
"skillPath": "skills/devflow:docker/SKILL.md"
|
|
111
152
|
},
|
|
112
153
|
"devflow:electron": {
|
|
113
154
|
"mcpTools": [
|
|
@@ -123,7 +164,12 @@
|
|
|
123
164
|
"Explore",
|
|
124
165
|
"WebSearch",
|
|
125
166
|
"WebFetch"
|
|
126
|
-
]
|
|
167
|
+
],
|
|
168
|
+
"source": "plugin",
|
|
169
|
+
"sourceVersion": "0.1.0",
|
|
170
|
+
"requiresContext": true,
|
|
171
|
+
"evidenceMode": "mixed",
|
|
172
|
+
"skillPath": "skills/devflow:electron/SKILL.md"
|
|
127
173
|
},
|
|
128
174
|
"devflow:git": {
|
|
129
175
|
"mcpTools": [
|
|
@@ -139,7 +185,12 @@
|
|
|
139
185
|
"Explore",
|
|
140
186
|
"WebSearch",
|
|
141
187
|
"WebFetch"
|
|
142
|
-
]
|
|
188
|
+
],
|
|
189
|
+
"source": "plugin",
|
|
190
|
+
"sourceVersion": "0.1.0",
|
|
191
|
+
"requiresContext": true,
|
|
192
|
+
"evidenceMode": "mixed",
|
|
193
|
+
"skillPath": "skills/devflow:git/SKILL.md"
|
|
143
194
|
},
|
|
144
195
|
"devflow:graphql": {
|
|
145
196
|
"mcpTools": [
|
|
@@ -155,7 +206,12 @@
|
|
|
155
206
|
"Explore",
|
|
156
207
|
"WebSearch",
|
|
157
208
|
"WebFetch"
|
|
158
|
-
]
|
|
209
|
+
],
|
|
210
|
+
"source": "plugin",
|
|
211
|
+
"sourceVersion": "0.1.0",
|
|
212
|
+
"requiresContext": true,
|
|
213
|
+
"evidenceMode": "mixed",
|
|
214
|
+
"skillPath": "skills/devflow:graphql/SKILL.md"
|
|
159
215
|
},
|
|
160
216
|
"devflow:nest": {
|
|
161
217
|
"mcpTools": [
|
|
@@ -172,7 +228,12 @@
|
|
|
172
228
|
"Explore",
|
|
173
229
|
"WebSearch",
|
|
174
230
|
"WebFetch"
|
|
175
|
-
]
|
|
231
|
+
],
|
|
232
|
+
"source": "plugin",
|
|
233
|
+
"sourceVersion": "0.1.0",
|
|
234
|
+
"requiresContext": true,
|
|
235
|
+
"evidenceMode": "mixed",
|
|
236
|
+
"skillPath": "skills/devflow:nest/SKILL.md"
|
|
176
237
|
},
|
|
177
238
|
"devflow:nextjs": {
|
|
178
239
|
"mcpTools": [
|
|
@@ -189,7 +250,12 @@
|
|
|
189
250
|
"Explore",
|
|
190
251
|
"WebSearch",
|
|
191
252
|
"WebFetch"
|
|
192
|
-
]
|
|
253
|
+
],
|
|
254
|
+
"source": "plugin",
|
|
255
|
+
"sourceVersion": "0.1.0",
|
|
256
|
+
"requiresContext": true,
|
|
257
|
+
"evidenceMode": "mixed",
|
|
258
|
+
"skillPath": "skills/devflow:nextjs/SKILL.md"
|
|
193
259
|
},
|
|
194
260
|
"devflow:performance": {
|
|
195
261
|
"mcpTools": [
|
|
@@ -205,7 +271,12 @@
|
|
|
205
271
|
"Explore",
|
|
206
272
|
"WebSearch",
|
|
207
273
|
"WebFetch"
|
|
208
|
-
]
|
|
274
|
+
],
|
|
275
|
+
"source": "plugin",
|
|
276
|
+
"sourceVersion": "0.1.0",
|
|
277
|
+
"requiresContext": true,
|
|
278
|
+
"evidenceMode": "mixed",
|
|
279
|
+
"skillPath": "skills/devflow:performance/SKILL.md"
|
|
209
280
|
},
|
|
210
281
|
"devflow:react": {
|
|
211
282
|
"mcpTools": [
|
|
@@ -225,7 +296,12 @@
|
|
|
225
296
|
"Explore",
|
|
226
297
|
"WebSearch",
|
|
227
298
|
"WebFetch"
|
|
228
|
-
]
|
|
299
|
+
],
|
|
300
|
+
"source": "plugin",
|
|
301
|
+
"sourceVersion": "0.1.0",
|
|
302
|
+
"requiresContext": true,
|
|
303
|
+
"evidenceMode": "mixed",
|
|
304
|
+
"skillPath": "skills/devflow:react/SKILL.md"
|
|
229
305
|
},
|
|
230
306
|
"devflow:tailwind": {
|
|
231
307
|
"mcpTools": [
|
|
@@ -242,7 +318,12 @@
|
|
|
242
318
|
"Explore",
|
|
243
319
|
"WebSearch",
|
|
244
320
|
"WebFetch"
|
|
245
|
-
]
|
|
321
|
+
],
|
|
322
|
+
"source": "plugin",
|
|
323
|
+
"sourceVersion": "0.1.0",
|
|
324
|
+
"requiresContext": true,
|
|
325
|
+
"evidenceMode": "mixed",
|
|
326
|
+
"skillPath": "skills/devflow:tailwind/SKILL.md"
|
|
246
327
|
},
|
|
247
328
|
"devflow:taro": {
|
|
248
329
|
"mcpTools": [
|
|
@@ -258,7 +339,12 @@
|
|
|
258
339
|
"Explore",
|
|
259
340
|
"WebSearch",
|
|
260
341
|
"WebFetch"
|
|
261
|
-
]
|
|
342
|
+
],
|
|
343
|
+
"source": "plugin",
|
|
344
|
+
"sourceVersion": "0.1.0",
|
|
345
|
+
"requiresContext": true,
|
|
346
|
+
"evidenceMode": "mixed",
|
|
347
|
+
"skillPath": "skills/devflow:taro/SKILL.md"
|
|
262
348
|
},
|
|
263
349
|
"devflow:ui-layout": {
|
|
264
350
|
"mcpTools": [
|
|
@@ -274,7 +360,12 @@
|
|
|
274
360
|
"Explore",
|
|
275
361
|
"WebSearch",
|
|
276
362
|
"WebFetch"
|
|
277
|
-
]
|
|
363
|
+
],
|
|
364
|
+
"source": "plugin",
|
|
365
|
+
"sourceVersion": "0.1.0",
|
|
366
|
+
"requiresContext": true,
|
|
367
|
+
"evidenceMode": "mixed",
|
|
368
|
+
"skillPath": "skills/devflow:ui-layout/SKILL.md"
|
|
278
369
|
},
|
|
279
370
|
"devflow:vue": {
|
|
280
371
|
"mcpTools": [
|
|
@@ -291,7 +382,12 @@
|
|
|
291
382
|
"Explore",
|
|
292
383
|
"WebSearch",
|
|
293
384
|
"WebFetch"
|
|
294
|
-
]
|
|
385
|
+
],
|
|
386
|
+
"source": "plugin",
|
|
387
|
+
"sourceVersion": "0.1.0",
|
|
388
|
+
"requiresContext": true,
|
|
389
|
+
"evidenceMode": "mixed",
|
|
390
|
+
"skillPath": "skills/devflow:vue/SKILL.md"
|
|
295
391
|
}
|
|
296
392
|
}
|
|
297
393
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {createConnection}from'node:net';import {getDaemonSocketPath}from'@devflow-tools/sdk';import {mkdirSync,appendFileSync}from'node:fs';import {homedir}from'node:os';import {join,dirname}from'node:path';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';function
|
|
2
|
-
`,{mode:384});}catch{}}function
|
|
3
|
-
`),0;
|
|
4
|
-
`);let
|
|
5
|
-
`);}),o.on("data",
|
|
6
|
-
`);if(
|
|
1
|
+
import {createConnection}from'node:net';import {getDaemonSocketPath}from'@devflow-tools/sdk';import {mkdirSync,appendFileSync}from'node:fs';import {homedir}from'node:os';import {join,dirname}from'node:path';import {openGlobalDevFlowDatabase}from'@devflow-tools/database';function y(e,t,n){try{let o=openGlobalDevFlowDatabase();try{o.insertEvent({kind:e,timestamp:Date.now(),duration:n,success:t.success!==!1,metadata:t});}finally{o.close();}}catch{}}var S=["4-Gate enforcement","memory prefetch cache","daemon-shared hook state"];function f(e){let t=v(e.input)??e.requestType;if(y("hook_daemon_request",{success:e.success,projectRoot:e.projectRoot,requestType:e.requestType,tool:t,attempts:e.attempts},e.durationMs),!e.success)try{let n=Date.now(),o=join(homedir(),".devflow","logs","hook-fallback",`${new Date(n).toISOString().slice(0,10)}.log`);mkdirSync(dirname(o),{recursive:!0,mode:448}),appendFileSync(o,`${JSON.stringify({ts:n,tool:t,requestType:e.requestType,projectRoot:e.projectRoot,reason:e.reason==="timeout"?"daemon-timeout":"daemon-unreachable",durationMs:e.durationMs,attempts:e.attempts,bypassCountLost:!0,disabledFeatures:S})}
|
|
2
|
+
`,{mode:384});}catch{}}function v(e){try{let t=JSON.parse(e);return typeof t.tool_name=="string"&&t.tool_name?t.tool_name:null}catch{return null}}var m=process.env.CLAUDE_PROJECT_DIR||process.cwd(),A=getDaemonSocketPath(m),c=process.argv[2],h=process.argv[3],p=Number(process.env.DEVFLOW_HOOK_CLIENT_TIMEOUT_MS),M=Number.isFinite(p)&&p>0?p:1e3,d=Number(process.env.DEVFLOW_HOOK_CLIENT_RETRY_DELAY_MS),P=Number.isFinite(d)&&d>=0?d:100,b=2*1024*1024,g=c==="post-tool-use"||c==="post-tool-use-failure"?1:2;async function q(){let e=h!==void 0?x(h):c==="memory-snapshot"?{input:"",truncated:false}:await B(),{input:t,truncated:n}=e,o=Date.now(),u="unknown";for(let s=0;s<g;s+=1){let r=await F(t,n);if(r.response!==null)return f({projectRoot:m,requestType:c,input:t,durationMs:Date.now()-o,success:true,attempts:s+1}),process.stdout.write(`${r.response}
|
|
3
|
+
`),0;u=r.reason??"unknown",s<g-1&&await I(P);}return process.env.DEVFLOW_HOOK_CLIENT_SUPPRESS_FALLBACK_LOG!=="1"&&f({projectRoot:m,requestType:c,input:t,durationMs:Date.now()-o,success:false,attempts:g,reason:u}),1}function F(e,t){return new Promise(n=>{let o=createConnection(A),u=false,s="",r=(a,l)=>{u||(u=true,clearTimeout(i),o.destroy(),n({response:a,reason:l}));},i=setTimeout(()=>r(null,"timeout"),M);o.setEncoding("utf8"),o.on("connect",()=>{o.write(`${JSON.stringify({type:"hello",rootPath:m})}
|
|
4
|
+
`);let a=L(e,t);if(!a){r(null,"protocol");return}o.write(`${JSON.stringify(a)}
|
|
5
|
+
`);}),o.on("data",a=>{s+=a;let l=s.indexOf(`
|
|
6
|
+
`);if(l<0)return;let D=s.slice(0,l).trim();r(D||null);}),o.on("error",()=>r(null,"unreachable")),o.on("close",()=>r(null,"unreachable"));})}function L(e,t){let n=t?{truncated:true}:{};return c==="stop"?{type:"stop",input:e,...n}:c==="memory-snapshot"?{type:"memory-snapshot"}:["session-start","session-end","post-tool-use","post-tool-use-failure","pre-tool-use","user-prompt-submit","pre-compact"].includes(c)?{type:c,input:e,...n}:null}function B(){return new Promise(e=>{let t=[],n=0,o=false;process.stdin.on("data",u=>{let s=Buffer.isBuffer(u)?u:Buffer.from(u),r=b-n;if(r>0){let i=s.subarray(0,r);t.push(i),n+=i.length;}s.length>r&&(o=true);}),process.stdin.on("end",()=>e({input:Buffer.concat(t).toString("utf8"),truncated:o})),process.stdin.on("error",()=>e({input:"",truncated:false}));})}function x(e){let t=Buffer.from(e);return t.length<=b?{input:e,truncated:false}:{input:t.subarray(0,b).toString("utf8"),truncated:true}}function I(e){return new Promise(t=>setTimeout(t,e))}q().then(e=>process.exit(e)).catch(()=>process.exit(1));
|