@kykiles/opencode-mem 13.10.3 → 13.10.5
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/package.json
CHANGED
package/plugin/package.json
CHANGED
|
@@ -222,7 +222,7 @@ ${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
|
|
|
222
222
|
${c}`}pe();var AP=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),DP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),jP=512*1024;async function*F_(t,e,r=20){if(r<=0)return;let n;try{n=await(0,Zr.readdir)(t,{withFileTypes:!0})}catch(o){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,o instanceof Error?o:void 0);return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||DP.has(o.name))continue;let s=(0,Bn.join)(t,o.name);if(o.isDirectory())yield*F_(s,e,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));AP.has(i)&&(yield s)}}}async function LP(t){try{let e=await(0,Zr.stat)(t);if(e.size>jP||e.size===0)return null;let r=await(0,Zr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function U_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(g=>g.length>0),i=[];for await(let g of F_(t,t,20)){if(r.filePattern&&!(0,Bn.relative)(t,g).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let S=await LP(g);S&&i.push({absolutePath:g,relativePath:(0,Bn.relative)(t,g),content:S})}let a=L_(i),c=[],u=[],l=0;for(let[g,S]of a){l+=qP(S);let x=Vs(g.toLowerCase(),s)>0,E=[],$=(k,Se)=>{for(let K of k){let at=0,Ae="",Pt=Vs(K.name.toLowerCase(),s);Pt>0&&(at+=Pt*3,Ae="name match"),K.signature.toLowerCase().includes(o)&&(at+=2,Ae=Ae?`${Ae} + signature`:"signature match"),K.jsdoc&&K.jsdoc.toLowerCase().includes(o)&&(at+=1,Ae=Ae?`${Ae} + jsdoc`:"jsdoc match"),at>0&&(x=!0,E.push({filePath:g,symbolName:Se?`${Se}.${K.name}`:K.name,kind:K.kind,signature:K.signature,jsdoc:K.jsdoc,lineStart:K.lineStart,lineEnd:K.lineEnd,matchReason:Ae})),K.children&&$(K.children,K.name)}};$(S.symbols),x&&(c.push(S),u.push(...E))}u.sort((g,S)=>{let v=Vs(g.symbolName.toLowerCase(),s);return Vs(S.symbolName.toLowerCase(),s)-v});let d=u.slice(0,n),p=new Set(d.map(g=>g.filePath)),f=c.filter(g=>p.has(g.filePath)).slice(0,n),m=f.reduce((g,S)=>g+S.foldedTokenEstimate,0);return{foldedFiles:f,matchingSymbols:d,totalFilesScanned:i.length,totalSymbolsFound:l,tokenEstimate:m}}function Vs(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=t.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function qP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function H_(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
|
|
223
223
|
`);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(`
|
|
224
224
|
`).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(qr(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(`
|
|
225
|
-
`)}var Du=require("node:fs/promises"),Gs=require("node:fs"),it=require("node:path"),G_=require("node:os"),B_=require("node:url");var W_="claude";function ZP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Ks(t){if(!t)return W_;let e=ZP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:W_}var FP=Ht(le.API_REQUEST),Ge=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Js=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=UP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??FP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ge("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Ge("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ge("missing_api_key","Server API key is not configured (OPENCODE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await xu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ge(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ge("http_error",`Server ${e} ${r} returned ${i.status}: ${HP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Ge("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function V_(t){return t instanceof Ge}function UP(t){return t.replace(/\/+$/,"")}function Nu(t){return typeof t=="string"?Ks(t):null}function HP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}pe();function Au(){let e=(Ms().OPENCODE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function K_(){let t=Ms(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.OPENCODE_MEM_SERVER_URL,t.OPENCODE_MEM_SERVER_BETA_URL),n=e(t.OPENCODE_MEM_SERVER_API_KEY,t.OPENCODE_MEM_SERVER_BETA_API_KEY),o=e(t.OPENCODE_MEM_SERVER_PROJECT_ID,t.OPENCODE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Js(s),projectId:o,serverBaseUrl:r}}var dO={},WP="13.10.3";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var Y_=!1,X_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,it.dirname)((0,B_.fileURLToPath)(dO.url))}catch(t){return Y_=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),ju=O_()??(0,it.resolve)(X_,"worker-service.cjs");function VP(){Y_&&((0,Gs.existsSync)(ju)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:ju,mcpServerDir:X_}))}async function _t(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Us(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Us(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function KP(){try{return(await Us("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function JP(){if(Au()!=="server")return null;let e=K_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function GP(t){return V_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Xn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Qn(t){let e=JP();if(!e)throw new Ge("transport",`${t} requires OPENCODE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Ge("missing_api_key",`${t}: ${e.reason}`);return e}function eo(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),GP(n)}}}var BP=eo("observation_add",async t=>{let e=Qn("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return Xn(o)});function Ys(t){return typeof t=="string"?Ks(t):null}var YP=eo("observation_record_event",async t=>{let e=Qn("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Xn(o)}),XP=eo("observation_search",async t=>{let e=Qn("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Xn(o)}),QP=eo("observation_context",async t=>{let e=Qn("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Xn(o)});function eO(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function tO(t){let e=eO(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:_t("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var rO=eo("observation_generation_status",async t=>{let e=Qn("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return Xn(n)});async function nO(){if(await KP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),VP();try{let t=Pu(),e=await T_(t,ju);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var Q_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
225
|
+
`)}var Du=require("node:fs/promises"),Gs=require("node:fs"),it=require("node:path"),G_=require("node:os"),B_=require("node:url");var W_="claude";function ZP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Ks(t){if(!t)return W_;let e=ZP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:W_}var FP=Ht(le.API_REQUEST),Ge=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Js=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=UP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??FP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ge("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Ge("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ge("missing_api_key","Server API key is not configured (OPENCODE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await xu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ge(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ge("http_error",`Server ${e} ${r} returned ${i.status}: ${HP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Ge("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function V_(t){return t instanceof Ge}function UP(t){return t.replace(/\/+$/,"")}function Nu(t){return typeof t=="string"?Ks(t):null}function HP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}pe();function Au(){let e=(Ms().OPENCODE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function K_(){let t=Ms(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.OPENCODE_MEM_SERVER_URL,t.OPENCODE_MEM_SERVER_BETA_URL),n=e(t.OPENCODE_MEM_SERVER_API_KEY,t.OPENCODE_MEM_SERVER_BETA_API_KEY),o=e(t.OPENCODE_MEM_SERVER_PROJECT_ID,t.OPENCODE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Js(s),projectId:o,serverBaseUrl:r}}var dO={},WP="13.10.5";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var Y_=!1,X_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,it.dirname)((0,B_.fileURLToPath)(dO.url))}catch(t){return Y_=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),ju=O_()??(0,it.resolve)(X_,"worker-service.cjs");function VP(){Y_&&((0,Gs.existsSync)(ju)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:ju,mcpServerDir:X_}))}async function _t(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Us(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Us(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function KP(){try{return(await Us("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function JP(){if(Au()!=="server")return null;let e=K_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function GP(t){return V_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Xn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Qn(t){let e=JP();if(!e)throw new Ge("transport",`${t} requires OPENCODE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Ge("missing_api_key",`${t}: ${e.reason}`);return e}function eo(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),GP(n)}}}var BP=eo("observation_add",async t=>{let e=Qn("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return Xn(o)});function Ys(t){return typeof t=="string"?Ks(t):null}var YP=eo("observation_record_event",async t=>{let e=Qn("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Xn(o)}),XP=eo("observation_search",async t=>{let e=Qn("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Xn(o)}),QP=eo("observation_context",async t=>{let e=Qn("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Xn(o)});function eO(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function tO(t){let e=eO(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:_t("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var rO=eo("observation_generation_status",async t=>{let e=Qn("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return Xn(n)});async function nO(){if(await KP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),VP();try{let t=Pu(),e=await T_(t,ju);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var Q_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
226
226
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
227
227
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
228
228
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|
|
@@ -62,7 +62,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
|
|
|
62
62
|
`,"utf8")}catch(f){let m=f instanceof Error?f:new Error(String(f));Eo(`[LOGGER] Failed to write to log file: ${m.message}
|
|
63
63
|
${m.stack??""}
|
|
64
64
|
`)}else Eo(p+`
|
|
65
|
-
`)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}setErrorSink(e){G0=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!G0||!(n instanceof Error))return;G0(n)}catch{}}dataIn(e,r,n,i){this.info(e,`\u2192 ${r}`,n,i)}dataOut(e,r,n,i){this.info(e,`\u2190 ${r}`,n,i)}success(e,r,n,i){this.info(e,`\u2713 ${r}`,n,i)}failure(e,r,n,i){this.error(e,`\u2717 ${r}`,n,i)}},w=new V0});function LK(){let t=[];t.push(H0.default.json({limit:"5mb"})),t.push((n,i,s)=>{let o=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>n.path.endsWith(f)),c=n.path==="/api/logs";if(n.path.startsWith("/health")||n.path==="/"||o||c)return s();let l=Date.now(),u=`${n.method}-${Date.now()}`,d=Bte(n.method,n.path,n.body);w.debug("HTTP",`\u2192 ${n.method} ${n.path}`,{requestId:u},d);let p=i.send.bind(i);i.send=function(f){let m=Date.now()-l;return w.debug("HTTP",`\u2190 ${i.statusCode} ${n.path}`,{requestId:u,duration:`${m}ms`}),p(f)},s()});let e=Qs(),r=NK.default.join(e,"plugin","ui");return t.push(H0.default.static(r)),t}function qK(){return(t,e,r)=>{let n=t.headers.origin;if(n){if(!n.startsWith("http://localhost:")&&!n.startsWith("http://127.0.0.1:")){r(new Error("CORS not allowed"));return}e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Vary","Origin")}if(t.method==="OPTIONS"){e.setHeader("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,PATCH,DELETE"),e.setHeader("Access-Control-Allow-Headers","Content-Type,Authorization,X-Requested-With"),e.status(204).end();return}r()}}function Vp(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){w.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function Bte(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${w.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var H0,NK,FK=R(()=>{"use strict";H0=Xe(Bp(),1),NK=Xe(require("path"),1);Jn();he()});function $K(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function UK(t,e){e.status(404).json($K("NotFound",`Cannot ${t.method} ${t.path}`))}var So,JK,zK=R(()=>{"use strict";he();So=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};JK=(t,e,r,n)=>{let i=t instanceof So?t.statusCode:500;w.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof So?t.code:void 0},t);let s=$K(t.name||"Error",t.message,t instanceof So?t.code:void 0,t instanceof So?t.details:void 0);r.status(i).json(s)}});var Vte,Hte,fRe,GK=R(()=>{"use strict";Vte=new Set([".cmd",".bat"]),Hte=new Set([".exe",".com"]),fRe=new Set([...Hte,...Vte])});function Kl(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(Yte.has(r)){e[r]=n;continue}Y0.has(r)||W0.some(i=>r.startsWith(i))||(e[r]=n)}return e}var W0,Y0,Wte,Yte,Hp=R(()=>{"use strict";W0=["CLAUDECODE_","CLAUDE_CODE_"],Y0=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Wte=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),Yte=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...Wte])});function Vr(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(w.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return w.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Wp(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Vr(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function tre(t){let e=(0,tE.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Kl(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function rre(t){let e=BK.get(t);if(e&&Date.now()-e.capturedAtMs<ere)return e.token;let r=null;try{r=tre(t)}catch(n){w.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return BK.set(t,{token:r,capturedAtMs:Date.now()}),r}function rE(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,Un.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let i=e.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return rre(t);try{let e=(0,tE.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Kl(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Gi(t){if(!t||!Vr(t.pid))return!1;if(!t.startToken)return!0;let e=rE(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||w.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function Yp(){return Q0||(Q0=new eE),Q0}function X0(){let t=nre.shift();t&&t()}var tE,Un,Z0,Qte,Xte,Zte,ere,BK,eE,Q0,nre,xo=R(()=>{"use strict";tE=require("child_process");GK();Un=require("fs"),Z0=Xe(require("path"),1);he();Hp();Jn();Qte=5e3,Xte=1e3,Zte=tt.supervisorRegistry();ere=5e3,BK=new Map;eE=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Zte){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Un.mkdirSync)(Z0.default.dirname(this.registryPath),{recursive:!0}),!(0,Un.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Un.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){r instanceof Error?w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&w.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&X0()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,i]of this.entries)Vr(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)X0();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;w.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let i=r.filter(a=>Vr(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}await Wp(i,Qte);let s=i.filter(a=>Vr(a.pid));for(let a of s){w.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}}if(s.length>0){let a=Date.now()+Xte;for(;Date.now()<a&&s.filter(c=>Vr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&X0();return w.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Un.mkdirSync)(Z0.default.dirname(this.registryPath),{recursive:!0}),(0,Un.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Q0=null;nre=[]});function VK(t){return process.platform==="win32"?Math.round(t*Dl.WINDOWS_MULTIPLIER):t}var Dl,nE=R(()=>{"use strict";Dl={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function QK(t){let e=t.currentPid??process.pid,r=t.pidFilePath??sre,n=t.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!Vr(a.pid)){t.registry.unregister(a.id);continue}try{await HK(a,"SIGTERM")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await Wp(i,5e3);let s=i.filter(a=>Vr(a.pid));for(let a of s)try{await HK(a,"SIGKILL")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await Wp(s,1e3);for(let a of i)t.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))t.registry.unregister(a.id);are(r,e),t.registry.pruneDeadEntries()}function are(t,e,r=!1){if(!(0,wo.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,wo.readFileSync)(t,"utf-8"));n=typeof a.pid=="number"?a.pid:null}catch(a){w.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:a instanceof Error?a.message:String(a)});return}let i=e!==null&&n===e,s=n===null||!Vr(n);if(!i&&!(r&&s)){w.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,wo.rmSync)(t,{force:!0})}catch(a){a instanceof Error?w.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},a):w.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(a)})}}async function HK(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(s){if(s instanceof Error&&s.code==="ESRCH")return;throw s}return}let i=["/PID",String(r),"/T"];e==="SIGKILL"&&i.push("/F"),await ire("taskkill",i,{timeout:Dl.POWERSHELL_COMMAND,windowsHide:!0})}var WK,wo,YK,ire,sre,XK=R(()=>{"use strict";WK=require("child_process"),wo=require("fs"),YK=require("util");he();nE();xo();Jn();ire=(0,YK.promisify)(WK.execFile),sre=tt.workerPid()});function ore(){let e=Yp().pruneDeadEntries();e>0&&w.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function eD(){_o===null&&(_o=setInterval(ore,ZK),_o.unref(),w.debug("SYSTEM","Health checker started",{intervalMs:ZK}))}function tD(){_o!==null&&(clearInterval(_o),_o=null,w.debug("SYSTEM","Health checker stopped"))}var ZK,_o,rD=R(()=>{"use strict";he();xo();ZK=3e4,_o=null});function nD(){return lre}function ure(t={}){let e=t.pidFilePath??cre;if(!(0,Xs.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Xs.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Xs.rmSync)(e,{force:!0}),"invalid"}return Gi(r)&&r?((t.logAlive??!0)&&w.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(w.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,Xs.rmSync)(e,{force:!0}),"stale")}var Xs,cre,iE,lre,iD=R(()=>{"use strict";Xs=require("fs");he();xo();XK();rD();Jn();cre=tt.workerPid(),iE=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),ure({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,eD()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){w.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,w.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?w.error("SYSTEM","Error during shutdown",{},i):w.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?w.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):w.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{w.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}tD(),this.stopPromise=QK({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},lre=new iE(Yp())});function sE(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var sD=R(()=>{"use strict"});function aE(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var aD=R(()=>{"use strict"});function oE(){let t=Array.from(dre.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var dre,oD=R(()=>{"use strict";dre=new Map});var cE,cD,$Re,lD=R(()=>{"use strict";cE=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let r=e.rateLimitType??"default";this.entries.set(r,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},cD=new cE,$Re=900*1e3});function mre(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var pD,fD,uE,Ml,mD,pre,lE,uD,fre,dD,Qp,hD=R(()=>{"use strict";pD=Xe(Bp(),1),fD=Xe(require("http"),1),uE=Xe(require("fs"),1),Ml=Xe(require("path"),1);jK();he();FK();zK();iD();xo();Hp();sD();aD();oD();lD();mD=Ml.default.resolve(__dirname,"../skills/mem-search"),pre=Ml.default.join(mD,"operations"),lE=Ml.default.join(mD,"SKILL.md"),uD=(()=>{try{let t=uE.readFileSync(lE,"utf-8");return w.info("SYSTEM","Cached SKILL.md at boot",{path:lE,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return w.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:lE,message:t instanceof Error?t.message:String(t)}),null}})(),fre=(()=>{let t=new Map;for(let e of $0){let r=Ml.default.join(pre,`${e}.md`);try{t.set(e,uE.readFileSync(r,"utf-8"))}catch(n){w.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&w.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),dD="13.10.3";Qp=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,pD.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{let s=fD.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),w.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,w.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(UK),this.app.use(JK)}setupMiddleware(){LK().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{mre(r),n()})}setupCors(){this.app.use(qK())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,r)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error",s=this.options.getDependencyHealth?this.options.getDependencyHealth():oE();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:dD,workerPath:this.options.workerPath,uptime:aE(this.startTime),managed:process.env.OPENCODE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),dependencies:s,rateLimits:cD.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:dD})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!PK.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!$0.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=fre.get(i);return a===void 0?(w.debug("HTTP","Instruction file not cached at boot",{operation:i}),r.status(404).json({error:"Instruction not found"})):r.json({content:[{type:"text",text:a}]})}if(uD===null)return w.debug("HTTP","SKILL.md not cached at boot",{topic:n}),r.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(uD,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Vp,async(e,r)=>{process.platform==="win32"&&process.env.OPENCODE_MEM_MANAGED==="true"&&process.send?(r.json({status:"restarting"}),w.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):sE(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Vp,async(e,r)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.OPENCODE_MEM_MANAGED==="true"&&process.send?(r.json({status:"shutting_down"}),w.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):sE(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Vp,(e,r)=>{let a=nD().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Vr(f.pid)?"alive":"dead",startedAt:f.startedAt})),o=a.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Y0.has(f)||W0.some(m=>f.startsWith(m))),l=aE(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c,dependencies:this.options.getDependencyHealth?this.options.getDependencyHealth():oE()}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var _r,hre,yre,dE,yD=R(()=>{"use strict";_r=require("zod"),hre=_r.z.enum(["hook","worker","provider","server","api"]),yre=_r.z.object({id:_r.z.string().min(1),projectId:_r.z.string().min(1),serverSessionId:_r.z.string().min(1).nullable().default(null),sourceType:hre,eventType:_r.z.string().min(1),platformSource:_r.z.string().min(1).nullable().default(null),payload:_r.z.unknown().default({}),contentSessionId:_r.z.string().min(1).nullable().default(null),memorySessionId:_r.z.string().min(1).nullable().default(null),occurredAtEpoch:_r.z.number().int().nonnegative(),createdAtEpoch:_r.z.number().int().nonnegative()}),dE=yre.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function We(){return(0,Xp.randomUUID)()}function ft(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gD(t){return Array.isArray(t)?t:[]}function Ke(t){return typeof t=="number"?t:new Date(t).getTime()}function Hr(t){return t==null?null:t instanceof Date?t:new Date(t)}async function ie(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function gn(t,e,r){if(!await ie(t,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,r]))throw new Error("project_id must belong to team_id")}async function hi(t,e,r,n){if(!await ie(t,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,r,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Nl(t){return JSON.stringify(pE(t))}function bn(t){return(0,Xp.createHash)("sha256").update(Nl(t)).digest("hex")}function pE(t){if(Array.isArray(t))return t.map(pE);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=pE(e[n]),r),{})}return t}var Xp,vn=R(()=>{"use strict";Xp=require("crypto")});function gre(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bi(t){if(!t)return Io;let e=gre(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Io}function sr(t){return typeof t!="string"?null:Bi(t)}var Io,Zs=R(()=>{"use strict";Io="claude"});function bD(t){let e=sr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),Nl(t.payload??{})])}`}function fE(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:ft(t.metadata),occurredAtEpoch:Ke(t.occurred_at),receivedAtEpoch:Ke(t.received_at),createdAtEpoch:Ke(t.created_at)}}var Wr,ko=R(()=>{"use strict";vn();Zs();Wr=class{constructor(e){this.client=e}client;async create(e){await gn(this.client,e.projectId,e.teamId),e.serverSessionId&&await hi(this.client,e.serverSessionId,e.projectId,e.teamId);let r=bD(e),n=sr(e.platformSource),i=await ie(this.client,`
|
|
65
|
+
`)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}setErrorSink(e){G0=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!G0||!(n instanceof Error))return;G0(n)}catch{}}dataIn(e,r,n,i){this.info(e,`\u2192 ${r}`,n,i)}dataOut(e,r,n,i){this.info(e,`\u2190 ${r}`,n,i)}success(e,r,n,i){this.info(e,`\u2713 ${r}`,n,i)}failure(e,r,n,i){this.error(e,`\u2717 ${r}`,n,i)}},w=new V0});function LK(){let t=[];t.push(H0.default.json({limit:"5mb"})),t.push((n,i,s)=>{let o=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>n.path.endsWith(f)),c=n.path==="/api/logs";if(n.path.startsWith("/health")||n.path==="/"||o||c)return s();let l=Date.now(),u=`${n.method}-${Date.now()}`,d=Bte(n.method,n.path,n.body);w.debug("HTTP",`\u2192 ${n.method} ${n.path}`,{requestId:u},d);let p=i.send.bind(i);i.send=function(f){let m=Date.now()-l;return w.debug("HTTP",`\u2190 ${i.statusCode} ${n.path}`,{requestId:u,duration:`${m}ms`}),p(f)},s()});let e=Qs(),r=NK.default.join(e,"plugin","ui");return t.push(H0.default.static(r)),t}function qK(){return(t,e,r)=>{let n=t.headers.origin;if(n){if(!n.startsWith("http://localhost:")&&!n.startsWith("http://127.0.0.1:")){r(new Error("CORS not allowed"));return}e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Vary","Origin")}if(t.method==="OPTIONS"){e.setHeader("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,PATCH,DELETE"),e.setHeader("Access-Control-Allow-Headers","Content-Type,Authorization,X-Requested-With"),e.status(204).end();return}r()}}function Vp(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){w.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function Bte(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${w.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var H0,NK,FK=R(()=>{"use strict";H0=Xe(Bp(),1),NK=Xe(require("path"),1);Jn();he()});function $K(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function UK(t,e){e.status(404).json($K("NotFound",`Cannot ${t.method} ${t.path}`))}var So,JK,zK=R(()=>{"use strict";he();So=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};JK=(t,e,r,n)=>{let i=t instanceof So?t.statusCode:500;w.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof So?t.code:void 0},t);let s=$K(t.name||"Error",t.message,t instanceof So?t.code:void 0,t instanceof So?t.details:void 0);r.status(i).json(s)}});var Vte,Hte,fRe,GK=R(()=>{"use strict";Vte=new Set([".cmd",".bat"]),Hte=new Set([".exe",".com"]),fRe=new Set([...Hte,...Vte])});function Kl(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(Yte.has(r)){e[r]=n;continue}Y0.has(r)||W0.some(i=>r.startsWith(i))||(e[r]=n)}return e}var W0,Y0,Wte,Yte,Hp=R(()=>{"use strict";W0=["CLAUDECODE_","CLAUDE_CODE_"],Y0=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Wte=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),Yte=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...Wte])});function Vr(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(w.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return w.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Wp(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Vr(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function tre(t){let e=(0,tE.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Kl(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function rre(t){let e=BK.get(t);if(e&&Date.now()-e.capturedAtMs<ere)return e.token;let r=null;try{r=tre(t)}catch(n){w.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return BK.set(t,{token:r,capturedAtMs:Date.now()}),r}function rE(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,Un.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let i=e.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return rre(t);try{let e=(0,tE.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Kl(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Gi(t){if(!t||!Vr(t.pid))return!1;if(!t.startToken)return!0;let e=rE(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||w.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function Yp(){return Q0||(Q0=new eE),Q0}function X0(){let t=nre.shift();t&&t()}var tE,Un,Z0,Qte,Xte,Zte,ere,BK,eE,Q0,nre,xo=R(()=>{"use strict";tE=require("child_process");GK();Un=require("fs"),Z0=Xe(require("path"),1);he();Hp();Jn();Qte=5e3,Xte=1e3,Zte=tt.supervisorRegistry();ere=5e3,BK=new Map;eE=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Zte){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Un.mkdirSync)(Z0.default.dirname(this.registryPath),{recursive:!0}),!(0,Un.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Un.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){r instanceof Error?w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&w.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&X0()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,i]of this.entries)Vr(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)X0();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;w.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let i=r.filter(a=>Vr(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}await Wp(i,Qte);let s=i.filter(a=>Vr(a.pid));for(let a of s){w.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}}if(s.length>0){let a=Date.now()+Xte;for(;Date.now()<a&&s.filter(c=>Vr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&X0();return w.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Un.mkdirSync)(Z0.default.dirname(this.registryPath),{recursive:!0}),(0,Un.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Q0=null;nre=[]});function VK(t){return process.platform==="win32"?Math.round(t*Dl.WINDOWS_MULTIPLIER):t}var Dl,nE=R(()=>{"use strict";Dl={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function QK(t){let e=t.currentPid??process.pid,r=t.pidFilePath??sre,n=t.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!Vr(a.pid)){t.registry.unregister(a.id);continue}try{await HK(a,"SIGTERM")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await Wp(i,5e3);let s=i.filter(a=>Vr(a.pid));for(let a of s)try{await HK(a,"SIGKILL")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await Wp(s,1e3);for(let a of i)t.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))t.registry.unregister(a.id);are(r,e),t.registry.pruneDeadEntries()}function are(t,e,r=!1){if(!(0,wo.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,wo.readFileSync)(t,"utf-8"));n=typeof a.pid=="number"?a.pid:null}catch(a){w.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:a instanceof Error?a.message:String(a)});return}let i=e!==null&&n===e,s=n===null||!Vr(n);if(!i&&!(r&&s)){w.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,wo.rmSync)(t,{force:!0})}catch(a){a instanceof Error?w.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},a):w.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(a)})}}async function HK(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(s){if(s instanceof Error&&s.code==="ESRCH")return;throw s}return}let i=["/PID",String(r),"/T"];e==="SIGKILL"&&i.push("/F"),await ire("taskkill",i,{timeout:Dl.POWERSHELL_COMMAND,windowsHide:!0})}var WK,wo,YK,ire,sre,XK=R(()=>{"use strict";WK=require("child_process"),wo=require("fs"),YK=require("util");he();nE();xo();Jn();ire=(0,YK.promisify)(WK.execFile),sre=tt.workerPid()});function ore(){let e=Yp().pruneDeadEntries();e>0&&w.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function eD(){_o===null&&(_o=setInterval(ore,ZK),_o.unref(),w.debug("SYSTEM","Health checker started",{intervalMs:ZK}))}function tD(){_o!==null&&(clearInterval(_o),_o=null,w.debug("SYSTEM","Health checker stopped"))}var ZK,_o,rD=R(()=>{"use strict";he();xo();ZK=3e4,_o=null});function nD(){return lre}function ure(t={}){let e=t.pidFilePath??cre;if(!(0,Xs.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Xs.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Xs.rmSync)(e,{force:!0}),"invalid"}return Gi(r)&&r?((t.logAlive??!0)&&w.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(w.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,Xs.rmSync)(e,{force:!0}),"stale")}var Xs,cre,iE,lre,iD=R(()=>{"use strict";Xs=require("fs");he();xo();XK();rD();Jn();cre=tt.workerPid(),iE=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),ure({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,eD()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){w.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,w.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?w.error("SYSTEM","Error during shutdown",{},i):w.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?w.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):w.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{w.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}tD(),this.stopPromise=QK({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},lre=new iE(Yp())});function sE(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var sD=R(()=>{"use strict"});function aE(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var aD=R(()=>{"use strict"});function oE(){let t=Array.from(dre.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var dre,oD=R(()=>{"use strict";dre=new Map});var cE,cD,$Re,lD=R(()=>{"use strict";cE=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let r=e.rateLimitType??"default";this.entries.set(r,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},cD=new cE,$Re=900*1e3});function mre(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var pD,fD,uE,Ml,mD,pre,lE,uD,fre,dD,Qp,hD=R(()=>{"use strict";pD=Xe(Bp(),1),fD=Xe(require("http"),1),uE=Xe(require("fs"),1),Ml=Xe(require("path"),1);jK();he();FK();zK();iD();xo();Hp();sD();aD();oD();lD();mD=Ml.default.resolve(__dirname,"../skills/mem-search"),pre=Ml.default.join(mD,"operations"),lE=Ml.default.join(mD,"SKILL.md"),uD=(()=>{try{let t=uE.readFileSync(lE,"utf-8");return w.info("SYSTEM","Cached SKILL.md at boot",{path:lE,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return w.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:lE,message:t instanceof Error?t.message:String(t)}),null}})(),fre=(()=>{let t=new Map;for(let e of $0){let r=Ml.default.join(pre,`${e}.md`);try{t.set(e,uE.readFileSync(r,"utf-8"))}catch(n){w.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&w.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),dD="13.10.5";Qp=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,pD.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{let s=fD.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),w.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,w.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(UK),this.app.use(JK)}setupMiddleware(){LK().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{mre(r),n()})}setupCors(){this.app.use(qK())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,r)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error",s=this.options.getDependencyHealth?this.options.getDependencyHealth():oE();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:dD,workerPath:this.options.workerPath,uptime:aE(this.startTime),managed:process.env.OPENCODE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),dependencies:s,rateLimits:cD.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:dD})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!PK.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!$0.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=fre.get(i);return a===void 0?(w.debug("HTTP","Instruction file not cached at boot",{operation:i}),r.status(404).json({error:"Instruction not found"})):r.json({content:[{type:"text",text:a}]})}if(uD===null)return w.debug("HTTP","SKILL.md not cached at boot",{topic:n}),r.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(uD,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Vp,async(e,r)=>{process.platform==="win32"&&process.env.OPENCODE_MEM_MANAGED==="true"&&process.send?(r.json({status:"restarting"}),w.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):sE(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Vp,async(e,r)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.OPENCODE_MEM_MANAGED==="true"&&process.send?(r.json({status:"shutting_down"}),w.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):sE(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Vp,(e,r)=>{let a=nD().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Vr(f.pid)?"alive":"dead",startedAt:f.startedAt})),o=a.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Y0.has(f)||W0.some(m=>f.startsWith(m))),l=aE(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c,dependencies:this.options.getDependencyHealth?this.options.getDependencyHealth():oE()}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var _r,hre,yre,dE,yD=R(()=>{"use strict";_r=require("zod"),hre=_r.z.enum(["hook","worker","provider","server","api"]),yre=_r.z.object({id:_r.z.string().min(1),projectId:_r.z.string().min(1),serverSessionId:_r.z.string().min(1).nullable().default(null),sourceType:hre,eventType:_r.z.string().min(1),platformSource:_r.z.string().min(1).nullable().default(null),payload:_r.z.unknown().default({}),contentSessionId:_r.z.string().min(1).nullable().default(null),memorySessionId:_r.z.string().min(1).nullable().default(null),occurredAtEpoch:_r.z.number().int().nonnegative(),createdAtEpoch:_r.z.number().int().nonnegative()}),dE=yre.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function We(){return(0,Xp.randomUUID)()}function ft(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gD(t){return Array.isArray(t)?t:[]}function Ke(t){return typeof t=="number"?t:new Date(t).getTime()}function Hr(t){return t==null?null:t instanceof Date?t:new Date(t)}async function ie(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function gn(t,e,r){if(!await ie(t,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,r]))throw new Error("project_id must belong to team_id")}async function hi(t,e,r,n){if(!await ie(t,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,r,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Nl(t){return JSON.stringify(pE(t))}function bn(t){return(0,Xp.createHash)("sha256").update(Nl(t)).digest("hex")}function pE(t){if(Array.isArray(t))return t.map(pE);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=pE(e[n]),r),{})}return t}var Xp,vn=R(()=>{"use strict";Xp=require("crypto")});function gre(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bi(t){if(!t)return Io;let e=gre(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Io}function sr(t){return typeof t!="string"?null:Bi(t)}var Io,Zs=R(()=>{"use strict";Io="claude"});function bD(t){let e=sr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),Nl(t.payload??{})])}`}function fE(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:ft(t.metadata),occurredAtEpoch:Ke(t.occurred_at),receivedAtEpoch:Ke(t.received_at),createdAtEpoch:Ke(t.created_at)}}var Wr,ko=R(()=>{"use strict";vn();Zs();Wr=class{constructor(e){this.client=e}client;async create(e){await gn(this.client,e.projectId,e.teamId),e.serverSessionId&&await hi(this.client,e.serverSessionId,e.projectId,e.teamId);let r=bD(e),n=sr(e.platformSource),i=await ie(this.client,`
|
|
66
66
|
INSERT INTO agent_events (
|
|
67
67
|
id, project_id, team_id, server_session_id, source_adapter,
|
|
68
68
|
source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at
|
|
@@ -345,7 +345,7 @@ data:
|
|
|
345
345
|
)
|
|
346
346
|
ORDER BY e.occurred_at ASC
|
|
347
347
|
LIMIT $4
|
|
348
|
-
`,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(wme)}}});function g4(t){let e=kme.safeParse(t);if(!e.success)throw new $u(e.error.issues);return e.data}var Qt,hc,h4,y4,_me,Ime,kme,$u,Mm=R(()=>{"use strict";Qt=require("zod"),hc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},h4={event:"evt",summary:"sum"},y4=Qt.z.object({team_id:Qt.z.string().min(1,"team_id is required"),project_id:Qt.z.string().min(1,"project_id is required"),source_type:Qt.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:Qt.z.string().min(1,"source_id is required"),generation_job_id:Qt.z.string().min(1,"generation_job_id is required"),api_key_id:Qt.z.string().min(1).nullable(),actor_id:Qt.z.string().min(1).nullable(),source_adapter:Qt.z.string().min(1,"source_adapter is required"),request_id:Qt.z.string().min(1).nullable().optional()}),_me=y4.extend({kind:Qt.z.literal("event"),agent_event_id:Qt.z.string().min(1)}),Ime=y4.extend({kind:Qt.z.literal("summary"),server_session_id:Qt.z.string().min(1)}),kme=Qt.z.discriminatedUnion("kind",[_me,Ime]),$u=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function yc(t){let e=h4[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,b4.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var b4,b_=R(()=>{"use strict";b4=require("crypto");Mm()});function v4(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var E4,Nm,S4=R(()=>{"use strict";ko();Vi();sa();he();b_();vn();E4="observation_generate_for_event",Nm=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await Sn(this.options.pool,async o=>{let l=await new Wr(o).create(e);if(!n)return{event:l,outbox:null};let u=new ut(o),d=new zt(o),p=We(),f=v4({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:E4,bullmqJobId:yc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),a="skipped";return s.outbox&&(a=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:a}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await Sn(this.options.pool,async a=>{let o=new Wr(a),c=new ut(a),l=new zt(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=We(),m=v4({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),g=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:E4,bullmqJobId:yc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:g.id,projectId:g.projectId,teamId:g.teamId,eventType:"queued",statusAfter:g.status,attempt:g.attempts,details:{source:i}}),u.push({event:p,outbox:g})}return u});return Promise.all(s.map(async({event:a,outbox:o})=>{let c=o?await this.publishEventJob(a,o):"skipped";return{event:a,outbox:o,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??yc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return w.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function v_(t){return yc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function E_(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var x4=R(()=>{"use strict";b_()});var Tme,Lm,w4=R(()=>{"use strict";Vi();sa();us();he();x4();vn();Tme="observation_generate_session_summary",Lm=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await Sn(this.options.pool,async s=>{let o=await new Yt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new ut(s),l=new zt(s),u=We(),d=E_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:o.projectId,teamId:o.teamId,sourceType:"session_summary",sourceId:o.id,serverSessionId:o.id,jobType:Tme,bullmqJobId:v_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:o,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??v_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=E_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,a),"enqueued"}catch(o){return w.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:o instanceof Error?o.message:String(o)}),"queued_only"}}}});function _4(t){return`${(process.env.OPENCODE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function I4(t,e){return`claude mcp add --transport http opencode-mem ${t} --header "Authorization: Bearer ${e}"`}async function O4(t,e,r=j4,n=Ame){if(T4.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(o=>setTimeout(o,n));let a=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!a)return{job:s,timedOut:!1};if(s=a,T4.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function jme(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&C4.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&Pme.has(n)?n:null,s=Fm(t.query.limit,K4,1,D4),a=Fm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),o=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(o){let l=new Date(o);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:a,since:c}}function R4(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function A4(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&C4.has(e)?e:null,n=Fm(t.query.limit,K4,1,D4),i=Fm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Fm(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function S_(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function Cme(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function Kme(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function Ju(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Uu(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function gc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Dme(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function x_(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function P4(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function w_(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var ce,$m,Ome,Rme,k4,j4,Ame,T4,qm,Pme,C4,K4,D4,M4=R(()=>{"use strict";ce=require("zod");yD();ko();Vi();yi();ql();To();he();ef();vS();kN();XN();l4();d4();f4();Ea();$m=require("node:crypto");us();S4();w4();Zs();Ome="api",Rme="13.10.3";k4=ce.z.object({generate:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional(),wait:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional()}),j4=3e4,Ame=100,T4=["completed","failed","cancelled"];qm=class{constructor(e){this.options=e;this.ingestEvents=new Nm({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Lm({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",IN());let r=ta(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=ta(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.OPENCODE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(u4(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.OPENCODE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(g_(this.options.pool,{kind:"request",cap:a})),process.env.OPENCODE_MEM_USAGE_METERING==="1"&&i.push(p4(this.options.pool));let o=[...i],c=Number(process.env.OPENCODE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(g_(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...o],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Rr(this.options.pool).summarize({teamId:m,since:g});f.status(200).json({since:g.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ce.z.object({label:ce.z.string().max(120).optional(),expiresInDays:ce.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let g=this.requireTeamId(p,f);if(!g)return;let b=`cm_${(0,$m.randomBytes)(24).toString("hex")}`,v=(0,$m.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Dt(this.options.pool).createApiKey({keyHash:v,teamId:g,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let k=_4(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:k,connectCommand:I4(k,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let g=_4(p);f.status(200).json({mcpUrl:g,connectCommand:I4(g,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=k4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",v=dE.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(p,f);if(!S||!this.ensureProjectAllowed(p,f,E.projectId))return;let k=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([k],[p.body],S);let O,j=null,L="skipped",te={generate:g,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:k.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(k,te);O=q.event,j=q.outbox,L=q.enqueueState}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.write");return}if(await this.auditWrite(p,"event.received",O.id,O.projectId,{sourceAdapter:O.sourceAdapter,sourceEventId:O.sourceEventId,eventType:O.eventType,serverSessionId:O.serverSessionId,generationJobId:j?.id??null}),b){let q=j,J=!1;if(j){let re=new ut(this.options.pool),at=await O4(re,j);q=at.job,J=at.timedOut}f.status(201).json({event:Uu(O),generationJob:q?P4(q,L):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:Uu(O),...j?{generationJob:x_(j,L)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=k4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",E=ce.z.array(dE).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(p,f);if(!S)return;let k=Kme(p,E.data);if(k){f.status(k.status).json(k.body);return}let O=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(O,Array.isArray(p.body)?p.body:E.data,S);let j=[],L=[],te={generate:g,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestBatch(O,te);j=q.map(({event:J,outbox:re})=>({event:J,outbox:re})),L=q.map(({enqueueState:J})=>J)}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:j.length,generationJobIds:j.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new ut(this.options.pool),J=Date.now()+j4,re=[];for(let _ of j){if(!_.outbox){re.push({event:_.event,outbox:null,timedOut:!1});continue}let K=Math.max(0,J-Date.now()),A=await O4(q,_.outbox,K);re.push({event:_.event,outbox:A.job,timedOut:A.timedOut})}let at=re.some(_=>_.timedOut);f.status(201).json({events:re.map(({event:_,outbox:K,timedOut:A},P)=>({event:Uu(_),generationJob:K?P4(K,L[P]):null,...A?{waitTimedOut:!0}:{}})),...at?{waitTimedOut:!0}:{}});return}f.status(201).json({events:j.map(({event:q,outbox:J},re)=>({event:Uu(q),...J?{generationJob:x_(J,L[re])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),b=new Wr(this.options.pool),v=await this.loadScopedById(p,f,{id:g,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:g,projectId:E,teamId:m})});v&&f.json({event:Uu(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[g,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
|
|
348
|
+
`,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(wme)}}});function g4(t){let e=kme.safeParse(t);if(!e.success)throw new $u(e.error.issues);return e.data}var Qt,hc,h4,y4,_me,Ime,kme,$u,Mm=R(()=>{"use strict";Qt=require("zod"),hc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},h4={event:"evt",summary:"sum"},y4=Qt.z.object({team_id:Qt.z.string().min(1,"team_id is required"),project_id:Qt.z.string().min(1,"project_id is required"),source_type:Qt.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:Qt.z.string().min(1,"source_id is required"),generation_job_id:Qt.z.string().min(1,"generation_job_id is required"),api_key_id:Qt.z.string().min(1).nullable(),actor_id:Qt.z.string().min(1).nullable(),source_adapter:Qt.z.string().min(1,"source_adapter is required"),request_id:Qt.z.string().min(1).nullable().optional()}),_me=y4.extend({kind:Qt.z.literal("event"),agent_event_id:Qt.z.string().min(1)}),Ime=y4.extend({kind:Qt.z.literal("summary"),server_session_id:Qt.z.string().min(1)}),kme=Qt.z.discriminatedUnion("kind",[_me,Ime]),$u=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function yc(t){let e=h4[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,b4.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var b4,b_=R(()=>{"use strict";b4=require("crypto");Mm()});function v4(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var E4,Nm,S4=R(()=>{"use strict";ko();Vi();sa();he();b_();vn();E4="observation_generate_for_event",Nm=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await Sn(this.options.pool,async o=>{let l=await new Wr(o).create(e);if(!n)return{event:l,outbox:null};let u=new ut(o),d=new zt(o),p=We(),f=v4({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:E4,bullmqJobId:yc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),a="skipped";return s.outbox&&(a=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:a}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await Sn(this.options.pool,async a=>{let o=new Wr(a),c=new ut(a),l=new zt(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=We(),m=v4({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),g=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:E4,bullmqJobId:yc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:g.id,projectId:g.projectId,teamId:g.teamId,eventType:"queued",statusAfter:g.status,attempt:g.attempts,details:{source:i}}),u.push({event:p,outbox:g})}return u});return Promise.all(s.map(async({event:a,outbox:o})=>{let c=o?await this.publishEventJob(a,o):"skipped";return{event:a,outbox:o,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??yc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return w.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function v_(t){return yc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function E_(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var x4=R(()=>{"use strict";b_()});var Tme,Lm,w4=R(()=>{"use strict";Vi();sa();us();he();x4();vn();Tme="observation_generate_session_summary",Lm=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await Sn(this.options.pool,async s=>{let o=await new Yt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new ut(s),l=new zt(s),u=We(),d=E_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:o.projectId,teamId:o.teamId,sourceType:"session_summary",sourceId:o.id,serverSessionId:o.id,jobType:Tme,bullmqJobId:v_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:o,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??v_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=E_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,a),"enqueued"}catch(o){return w.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:o instanceof Error?o.message:String(o)}),"queued_only"}}}});function _4(t){return`${(process.env.OPENCODE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function I4(t,e){return`claude mcp add --transport http opencode-mem ${t} --header "Authorization: Bearer ${e}"`}async function O4(t,e,r=j4,n=Ame){if(T4.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(o=>setTimeout(o,n));let a=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!a)return{job:s,timedOut:!1};if(s=a,T4.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function jme(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&C4.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&Pme.has(n)?n:null,s=Fm(t.query.limit,K4,1,D4),a=Fm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),o=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(o){let l=new Date(o);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:a,since:c}}function R4(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function A4(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&C4.has(e)?e:null,n=Fm(t.query.limit,K4,1,D4),i=Fm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Fm(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function S_(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function Cme(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function Kme(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function Ju(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Uu(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function gc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Dme(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function x_(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function P4(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function w_(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var ce,$m,Ome,Rme,k4,j4,Ame,T4,qm,Pme,C4,K4,D4,M4=R(()=>{"use strict";ce=require("zod");yD();ko();Vi();yi();ql();To();he();ef();vS();kN();XN();l4();d4();f4();Ea();$m=require("node:crypto");us();S4();w4();Zs();Ome="api",Rme="13.10.5";k4=ce.z.object({generate:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional(),wait:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional()}),j4=3e4,Ame=100,T4=["completed","failed","cancelled"];qm=class{constructor(e){this.options=e;this.ingestEvents=new Nm({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Lm({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",IN());let r=ta(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=ta(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.OPENCODE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(u4(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.OPENCODE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(g_(this.options.pool,{kind:"request",cap:a})),process.env.OPENCODE_MEM_USAGE_METERING==="1"&&i.push(p4(this.options.pool));let o=[...i],c=Number(process.env.OPENCODE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(g_(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...o],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Rr(this.options.pool).summarize({teamId:m,since:g});f.status(200).json({since:g.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ce.z.object({label:ce.z.string().max(120).optional(),expiresInDays:ce.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let g=this.requireTeamId(p,f);if(!g)return;let b=`cm_${(0,$m.randomBytes)(24).toString("hex")}`,v=(0,$m.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Dt(this.options.pool).createApiKey({keyHash:v,teamId:g,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let k=_4(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:k,connectCommand:I4(k,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let g=_4(p);f.status(200).json({mcpUrl:g,connectCommand:I4(g,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=k4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",v=dE.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(p,f);if(!S||!this.ensureProjectAllowed(p,f,E.projectId))return;let k=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([k],[p.body],S);let O,j=null,L="skipped",te={generate:g,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:k.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(k,te);O=q.event,j=q.outbox,L=q.enqueueState}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.write");return}if(await this.auditWrite(p,"event.received",O.id,O.projectId,{sourceAdapter:O.sourceAdapter,sourceEventId:O.sourceEventId,eventType:O.eventType,serverSessionId:O.serverSessionId,generationJobId:j?.id??null}),b){let q=j,J=!1;if(j){let re=new ut(this.options.pool),at=await O4(re,j);q=at.job,J=at.timedOut}f.status(201).json({event:Uu(O),generationJob:q?P4(q,L):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:Uu(O),...j?{generationJob:x_(j,L)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=k4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",E=ce.z.array(dE).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(p,f);if(!S)return;let k=Kme(p,E.data);if(k){f.status(k.status).json(k.body);return}let O=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(O,Array.isArray(p.body)?p.body:E.data,S);let j=[],L=[],te={generate:g,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestBatch(O,te);j=q.map(({event:J,outbox:re})=>({event:J,outbox:re})),L=q.map(({enqueueState:J})=>J)}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:j.length,generationJobIds:j.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new ut(this.options.pool),J=Date.now()+j4,re=[];for(let _ of j){if(!_.outbox){re.push({event:_.event,outbox:null,timedOut:!1});continue}let K=Math.max(0,J-Date.now()),A=await O4(q,_.outbox,K);re.push({event:_.event,outbox:A.job,timedOut:A.timedOut})}let at=re.some(_=>_.timedOut);f.status(201).json({events:re.map(({event:_,outbox:K,timedOut:A},P)=>({event:Uu(_),generationJob:K?P4(K,L[P]):null,...A?{waitTimedOut:!0}:{}})),...at?{waitTimedOut:!0}:{}});return}f.status(201).json({events:j.map(({event:q,outbox:J},re)=>({event:Uu(q),...J?{generationJob:x_(J,L[re])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),b=new Wr(this.options.pool),v=await this.loadScopedById(p,f,{id:g,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:g,projectId:E,teamId:m})});v&&f.json({event:Uu(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[g,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
|
|
349
349
|
SELECT o.id, o.project_id, o.team_id, o.server_session_id, o.kind, o.content,
|
|
350
350
|
o.metadata, o.generation_key, o.created_by_job_id, o.created_at, o.updated_at,
|
|
351
351
|
os.id AS source_id_pk, os.source_type, os.source_id, os.generation_job_id, os.created_at AS source_created_at
|
|
@@ -13,7 +13,7 @@ ${i.stack}`:` ${i.message}`;else if(this.getLevel()===0&&typeof i=="object")try{
|
|
|
13
13
|
${g.stack??""}
|
|
14
14
|
`)}else Z(m+`
|
|
15
15
|
`)}debug(e,t,n,o){this.log(0,e,t,n,o)}info(e,t,n,o){this.log(1,e,t,n,o)}warn(e,t,n,o){this.log(2,e,t,n,o)}setErrorSink(e){Ze=e}error(e,t,n,o){this.log(3,e,t,n,o),this.routeErrorToSink(t,n,o)}routeErrorToSink(e,t,n){try{if(!Ze||!(n instanceof Error))return;Ze(n)}catch{}}dataIn(e,t,n,o){this.info(e,`\u2192 ${t}`,n,o)}dataOut(e,t,n,o){this.info(e,`\u2190 ${t}`,n,o)}success(e,t,n,o){this.info(e,`\u2713 ${t}`,n,o)}failure(e,t,n,o){this.error(e,`\u2717 ${t}`,n,o)}},a=new tt});var L=require("fs"),Qe=require("os"),le=require("path");T();var ne=O.transcriptsConfig(),he=O.transcriptsState(),gn={version:1,schemas:{},watches:[],stateFile:he};function Sn(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name;if(!(r.name==="codex"||e==="codex")||!r.path)return!1;let n=P(r.path).replace(/\\/g,"/"),o=(0,le.join)((0,Qe.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${o}/**/*.jsonl`}function It(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name,t=r.name==="codex"&&(!e||e==="codex");return r.context?.mode==="agents"&&t&&Sn(r)}function P(r){return r&&(r.startsWith("~")?(0,le.join)((0,Qe.homedir)(),r.slice(1)):r)}function de(r=ne){let e=P(r);if(!(0,L.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let t=(0,L.readFileSync)(e,"utf-8"),n=JSON.parse(t);if(!n.version||!n.watches)throw new Error(`Invalid transcript watch config: ${e}`);return n.stateFile||(n.stateFile=he),n}function Oe(r=ne){let e=P(r),t=(0,le.dirname)(e);(0,L.existsSync)(t)||(0,L.mkdirSync)(t,{recursive:!0}),(0,L.writeFileSync)(e,JSON.stringify(gn,null,2))}var w=require("fs"),I=require("path");f();var W=require("fs"),Nt=require("path");f();function At(r){try{if(!(0,W.existsSync)(r))return{offsets:{}};let e=(0,W.readFileSync)(r,"utf-8"),t=JSON.parse(e);return t.offsets?t:{offsets:{}}}catch(e){return a.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:r,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function xt(r,e){try{let t=(0,Nt.dirname)(r);(0,W.existsSync)(t)||(0,W.mkdirSync)(t,{recursive:!0}),(0,W.writeFileSync)(r,JSON.stringify(e,null,2))}catch(t){a.warn("TRANSCRIPT","Failed to save watch state",{statePath:r,error:t instanceof Error?t.message:String(t)})}}var fe=K(require("path"),1);var M=K(require("path"),1),h=require("fs");var rt=require("node:child_process");function Te(r,e,t){return(0,rt.spawn)(r,e??[],{windowsHide:!0,...t})}var _n=new Set([".cmd",".bat"]),hn=new Set([".exe",".com"]),os=new Set([...hn,..._n]);f();var k={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},Y={SUCCESS:0,BLOCKING_ERROR:2};function B(r){return process.platform==="win32"?Math.round(r*k.WINDOWS_MULTIPLIER):r}var ye=require("fs"),nt=require("path"),ot=require("os");_e();var v=class{static DEFAULTS={OPENCODE_MEM_MODEL:"claude-haiku-4-5-20251001",OPENCODE_MEM_CONTEXT_OBSERVATIONS:"50",OPENCODE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),OPENCODE_MEM_WORKER_HOST:"127.0.0.1",OPENCODE_MEM_API_TIMEOUT_MS:String(B(k.API_REQUEST)),OPENCODE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",OPENCODE_MEM_PROVIDER:"claude",OPENCODE_MEM_CLAUDE_AUTH_METHOD:"subscription",OPENCODE_MEM_GEMINI_API_KEY:"",OPENCODE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",OPENCODE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",OPENCODE_MEM_OPENROUTER_API_KEY:"",OPENCODE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",OPENCODE_MEM_OPENROUTER_BASE_URL:"",OPENCODE_MEM_OPENROUTER_SITE_URL:"",OPENCODE_MEM_OPENROUTER_APP_NAME:"opencode-mem",OPENCODE_MEM_DATA_DIR:(0,nt.join)((0,ot.homedir)(),".opencode-mem"),OPENCODE_MEM_LOG_LEVEL:"INFO",OPENCODE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",OPENCODE_MEM_MODE:"code",OPENCODE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",OPENCODE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",OPENCODE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",OPENCODE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",OPENCODE_MEM_CONTEXT_FULL_COUNT:"0",OPENCODE_MEM_CONTEXT_FULL_FIELD:"narrative",OPENCODE_MEM_CONTEXT_SESSION_COUNT:"10",OPENCODE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",OPENCODE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",OPENCODE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",OPENCODE_MEM_WELCOME_HINT_ENABLED:"true",OPENCODE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",OPENCODE_MEM_FOLDER_USE_LOCAL_MD:"false",OPENCODE_MEM_TRANSCRIPTS_ENABLED:"true",OPENCODE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,nt.join)((0,ot.homedir)(),".opencode-mem","transcript-watch.json"),OPENCODE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",OPENCODE_MEM_MAX_CONCURRENT_AGENTS:"2",OPENCODE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",OPENCODE_MEM_EXCLUDED_PROJECTS:"",OPENCODE_MEM_FOLDER_MD_EXCLUDE:"[]",OPENCODE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",OPENCODE_MEM_SEMANTIC_INJECT:"false",OPENCODE_MEM_SEMANTIC_INJECT_LIMIT:"5",OPENCODE_MEM_TIER_ROUTING_ENABLED:"true",OPENCODE_MEM_TIER_SIMPLE_MODEL:"haiku",OPENCODE_MEM_TIER_SUMMARY_MODEL:"",OPENCODE_MEM_TIER_FAST_MODEL:"haiku",OPENCODE_MEM_TIER_SMART_MODEL:"sonnet",OPENCODE_MEM_CHROMA_ENABLED:"true",OPENCODE_MEM_CHROMA_MODE:"local",OPENCODE_MEM_CHROMA_HOST:"127.0.0.1",OPENCODE_MEM_CHROMA_PORT:"8000",OPENCODE_MEM_CHROMA_SSL:"false",OPENCODE_MEM_CHROMA_API_KEY:"",OPENCODE_MEM_CHROMA_TENANT:"default_tenant",OPENCODE_MEM_CHROMA_DATABASE:"default_database",OPENCODE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",OPENCODE_MEM_TELEGRAM_ENABLED:"true",OPENCODE_MEM_TELEGRAM_BOT_TOKEN:"",OPENCODE_MEM_TELEGRAM_CHAT_ID:"",OPENCODE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",OPENCODE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",OPENCODE_MEM_QUEUE_ENGINE:"sqlite",OPENCODE_MEM_REDIS_URL:"",OPENCODE_MEM_REDIS_HOST:"127.0.0.1",OPENCODE_MEM_REDIS_PORT:"6379",OPENCODE_MEM_REDIS_MODE:"external",OPENCODE_MEM_QUEUE_REDIS_PREFIX:`opencode_mem_${process.env.OPENCODE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,OPENCODE_MEM_AUTH_MODE:"api-key",OPENCODE_MEM_RUNTIME:"worker",OPENCODE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.OPENCODE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,OPENCODE_MEM_SERVER_API_KEY:"",OPENCODE_MEM_SERVER_PROJECT_ID:"",OPENCODE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.OPENCODE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,OPENCODE_MEM_SERVER_BETA_API_KEY:"",OPENCODE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e,t=!0){try{if(!(0,ye.existsSync)(e)){let c=this.getAllDefaults();try{Xe(e,c),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(u){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,u instanceof Error?u.message:String(u))}return t?this.applyEnvOverrides(c):c}let n=(0,ye.readFileSync)(e,"utf-8"),o=ee(n),i=o;if(o.env&&typeof o.env=="object"){i=o.env;try{Xe(e,i),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,c instanceof Error?c.message:String(c))}}let s={...this.DEFAULTS};for(let c of Object.keys(this.DEFAULTS))i[c]!==void 0&&(s[c]=i[c]);return t?this.applyEnvOverrides(s):s}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return t?this.applyEnvOverrides(o):o}}};T();T();var we=null;function H(){return we!==null||(we=v.loadFromFile(re)),we}var X=require("fs");f();var ut=require("child_process");var A=require("fs"),at=K(require("path"),1);f();var On=["CLAUDECODE_","CLAUDE_CODE_"],Tn=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),yn=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),wn=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...yn]);function Pe(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(wn.has(t)){e[t]=n;continue}Tn.has(t)||On.some(o=>t.startsWith(o))||(e[t]=n)}return e}T();var Pn=5e3,Mn=1e3,vn=O.supervisorRegistry();function N(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(a.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return a.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function Me(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!N(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var Rn=5e3,Lt=new Map;function Cn(r){let e=(0,ut.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Pe(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let t=e.stdout.trim();return t.length>0?t:null}return null}function kn(r){let e=Lt.get(r);if(e&&Date.now()-e.capturedAtMs<Rn)return e.token;let t=null;try{t=Cn(r)}catch(n){a.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return Lt.set(r,{token:t,capturedAtMs:Date.now()}),t}function Ft(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,A.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let o=e.slice(t+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return kn(r);try{let e=(0,ut.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Pe(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function lt(r){if(!r||!N(r.pid))return!1;if(!r.startToken)return!0;let e=Ft(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||a.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var ct=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=vn){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,A.mkdirSync)(at.default.dirname(this.registryPath),{recursive:!0}),!(0,A.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,A.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(t){t instanceof Error?a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&a.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&it()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),o=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,o]of this.entries)N(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)it();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;a.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(s=>s.pid)});let o=t.filter(s=>N(s.pid));for(let s of o)try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGTERM"):process.kill(s.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGTERM session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGTERM session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}await Me(o,Pn);let i=o.filter(s=>N(s.pid));for(let s of i){a.warn("SYSTEM",`Session process PID ${s.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:s.pid,pgid:s.pgid,sessionId:n});try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGKILL"):process.kill(s.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGKILL session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGKILL session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}}if(i.length>0){let s=Date.now()+Mn;for(;Date.now()<s&&i.filter(u=>N(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let s of t)this.entries.delete(s.id),this.runtimeProcesses.delete(s.id);this.persist();for(let s of t)s.type==="sdk"&&it();return a.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,A.mkdirSync)(at.default.dirname(this.registryPath),{recursive:!0}),(0,A.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},st=null;function ve(){return st||(st=new ct),st}var bn=[];function it(){let r=bn.shift();r&&r()}var Ht=require("child_process"),oe=require("fs"),Ut=require("util");f();T();var In=(0,Ut.promisify)(Ht.execFile),Dn=O.workerPid();async function $t(r){let e=r.currentPid??process.pid,t=r.pidFilePath??Dn,n=r.registry.getAll(),o=[...n].filter(s=>s.pid!==e).sort((s,c)=>Date.parse(c.startedAt)-Date.parse(s.startedAt));for(let s of o){if(!N(s.pid)){r.registry.unregister(s.id);continue}try{await Wt(s,"SIGTERM")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}}await Me(o,5e3);let i=o.filter(s=>N(s.pid));for(let s of i)try{await Wt(s,"SIGKILL")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}await Me(i,1e3);for(let s of o)r.registry.unregister(s.id);for(let s of n.filter(c=>c.pid===e))r.registry.unregister(s.id);jt(t,e),r.registry.pruneDeadEntries()}function jt(r,e,t=!1){if(!(0,oe.existsSync)(r))return;let n=null;try{let s=JSON.parse((0,oe.readFileSync)(r,"utf-8"));n=typeof s.pid=="number"?s.pid:null}catch(s){a.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:s instanceof Error?s.message:String(s)});return}let o=e!==null&&n===e,i=n===null||!N(n);if(!o&&!(t&&i)){a.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,oe.rmSync)(r,{force:!0})}catch(s){s instanceof Error?a.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},s):a.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(s)})}}async function Wt(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}try{process.kill(t,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let o=["/PID",String(t),"/T"];e==="SIGKILL"&&o.push("/F"),await In("taskkill",o,{timeout:k.POWERSHELL_COMMAND,windowsHide:!0})}f();var Gt=3e4,se=null;function Nn(){let e=ve().pruneDeadEntries();e>0&&a.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Kt(){se===null&&(se=setInterval(Nn,Gt),se.unref(),a.debug("SYSTEM","Health checker started",{intervalMs:Gt}))}function Yt(){se!==null&&(clearInterval(se),se=null,a.debug("SYSTEM","Health checker stopped"))}T();var An=O.workerPid(),dt=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Re({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Kt()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){a.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,a.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?a.error("SYSTEM","Error during shutdown",{},o):a.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?a.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):a.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{a.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}Yt(),this.stopPromise=$t({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},Ns=new dt(ve());function Re(r={}){let e=r.pidFilePath??An;if(!(0,X.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,X.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,X.rmSync)(e,{force:!0}),"invalid"}return lt(t)&&t?((r.logAlive??!0)&&a.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(a.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,X.rmSync)(e,{force:!0}),"stale")}Se();var pt=require("path"),ke=require("fs"),Jt=require("crypto");T();var Ce=require("fs");function Bt(r,e){if(!(0,Ce.existsSync)(r))return e;try{return JSON.parse((0,Ce.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}f();var Vt="telemetry.json";function xn(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Ln(r,e){if(xn(r))return{enabled:!1,source:"DO_NOT_TRACK"};let t=r.OPENCODE_MEM_TELEMETRY?.toLowerCase();return t==="0"||t==="false"||t==="off"?{enabled:!1,source:"env"}:t==="1"||t==="true"||t==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function Xt(r,e){return Ln(r,e).enabled}function Fn(){return(0,pt.join)(te(),Vt)}function ft(){let r;try{r=Bt(Fn(),null)}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,t),null}return!r||typeof r!="object"||typeof r.installId!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"?null:{enabled:r.enabled,installId:r.installId,decidedAt:typeof r.decidedAt=="string"?r.decidedAt:""}}function Wn(r){let e=te();(0,ke.mkdirSync)(e,{recursive:!0}),(0,ke.writeFileSync)((0,pt.join)(e,Vt),JSON.stringify(r,null,2)+`
|
|
16
|
-
`)}function qt(){let r=ft();if(r?.installId)return r.installId;let e=(0,Jt.randomUUID)();return Wn({installId:e,decidedAt:""}),e}var Hn=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),zt=200;function Un(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Hn.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>zt?n.slice(0,zt):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function Qt(r){let e={};try{Un(r,e)}catch{}return e}var Et=K(require("os"),1);f();var $n="13.10.
|
|
16
|
+
`)}function qt(){let r=ft();if(r?.installId)return r.installId;let e=(0,Jt.randomUUID)();return Wn({installId:e,decidedAt:""}),e}var Hn=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),zt=200;function Un(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Hn.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>zt?n.slice(0,zt):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function Qt(r){let e={};try{Un(r,e)}catch{}return e}var Et=K(require("os"),1);f();var $n="13.10.5",jn="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Gn="https://us.i.posthog.com";function Zt(){return process.env.OPENCODE_MEM_TELEMETRY_KEY||jn}function er(){return process.env.OPENCODE_MEM_TELEMETRY_HOST||Gn}var Kn=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function tr(r){let e={};for(let t of Kn)r[t]!==void 0&&(e[t]=r[t]);return e}function Yn(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Et.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function rr(){return{version:$n,os:process.platform,os_version:Et.default.release(),is_wsl:Yn(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var Bn=2e3;async function nr(r,e,t){try{if(!Xt(process.env,ft()))return;let n=Qt({...rr(),...e??{}});if(t?.person?n.$set=tr(n):n.$process_person_profile=!1,process.env.OPENCODE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
|
|
17
17
|
`);return}let o=Zt(),i=new AbortController,s=setTimeout(()=>i.abort(),Bn);try{await Jn(o,r,n,i.signal)}finally{clearTimeout(s)}}catch{}}async function Jn(r,e,t,n){await fetch(`${er()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:qt(),properties:t}),signal:n})}var q=K(require("path"),1),sr=require("os"),U=require("fs"),gt=require("child_process");f();T();var Zs=O.dataDir(),ei=O.workerPid();function or(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function Xn(r,e){let t=e==="win32"?`where ${r}`:`which ${r}`,n;try{n=(0,gt.execSync)(t,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},i):a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},new Error(String(i))),null}return n.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}var mt;function ir(r={}){let e=Object.keys(r).length===0;if(e&&mt!==void 0)return mt;let t=qn(r);return e&&t!==null&&(mt=t),t}function qn(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(or(t))return t;let n=r.env??process.env,o=r.homeDirectory??(0,sr.homedir)(),i=r.pathExists??U.existsSync,s=r.lookupInPath??Xn,c=e==="win32"?[n.BUN,n.BUN_PATH,q.default.join(o,".bun","bin","bun.exe"),q.default.join(o,".bun","bin","bun"),n.USERPROFILE?q.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?q.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?q.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,q.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let u of c){let d=u?.trim();if(d&&(or(d)&&i(d)||d.toLowerCase()==="bun"))return d}return s("bun",e)}var ar=K(require("path"),1);var cr=require("fs");f();T();function zn(){return v.loadFromFile(re).OPENCODE_MEM_WORKER_HOST}function Qn(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}async function Zn(r,e,t="GET"){let n=await fetch(`http://${Qn(zn())}:${r}${e}`,{method:t}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}function eo(){try{let r=ar.default.join(ue,"package.json");return JSON.parse((0,cr.readFileSync)(r,"utf-8")).version}catch(r){if(r instanceof Error){let e=r.code;if(e==="ENOENT"||e==="EBUSY")return a.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw r}throw r}}async function to(r){try{let e=await Zn(r,"/api/health");return e.ok?JSON.parse(e.body).version:null}catch{return a.debug("SYSTEM","Could not fetch worker version",{}),null}}async function ur(r){let e=eo(),t=await to(r);return!t||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:t}:{matches:e===t,pluginVersion:e,workerVersion:t}}f();var be=require("path"),R=require("fs");T();f();var ro=6e4;function lr(){return(0,be.join)(te(),"spawn.lock")}function dr(){let r=lr(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,R.mkdirSync)((0,be.dirname)(r),{recursive:!0}),(0,R.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),i=o.code;if(i!=="EEXIST")return a.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},o),!0;if(t>0)return!1;let s;try{s=(0,R.statSync)(r).mtimeMs}catch{continue}if(Date.now()-s<=ro)return!1;let c;try{c=(0,R.statSync)(r).mtimeMs}catch{continue}if(c!==s)return!1;try{(0,R.unlinkSync)(r)}catch{return!1}}return!1}function pr(){let r=lr();try{if(JSON.parse((0,R.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,R.unlinkSync)(r)}catch{}}function Sr(r,e,t){let n=process.env[r];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=t.min&&o<=t.max)return o;a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var Le=Sr("OPENCODE_MEM_HEALTH_TIMEOUT_MS",B(k.HEALTH_CHECK),{min:500,max:3e5}),_r=Sr("OPENCODE_MEM_HOOK_READINESS_TIMEOUT_MS",B(k.HOOK_READINESS_WAIT),{min:0,max:3e5}),no={min:500,max:3e5};async function Ot(r,e={},t){try{return await fetch(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}var Ie=null,De=null,Ne=null,Ae=null;function oo(){return M.default.join(v.get("OPENCODE_MEM_DATA_DIR"),"settings.json")}function Tt(){return Ne!==null||(Ne=v.loadFromFile(oo())),Ne}function fr(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function so(r,e,t){let n=process.env[r];if(n!==void 0){let s=fr(n,t);return s!==null?s:(a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let o=Tt()[r],i=fr(o,t);return i!==null?i:(a.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:o,min:t.min,max:t.max}),e)}function hr(){if(Ie!==null)return Ie;let r=Tt();return Ie=parseInt(r.OPENCODE_MEM_WORKER_PORT,10),Ie}function io(){return De!==null||(De=Tt().OPENCODE_MEM_WORKER_HOST),De}function ao(){return Ae!==null||(Ae=so("OPENCODE_MEM_API_TIMEOUT_MS",B(k.API_REQUEST),no)),Ae}function co(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}function uo(r){return`http://${co(io())}:${hr()}${r}`}function $(r,e={}){let t=e.method??"GET",n=e.timeoutMs??ao(),o=uo(r),i={method:t};return e.headers&&(i.headers=e.headers),e.body&&(i.body=e.body),n>0?Ot(o,i,n):fetch(o,i)}async function lo(){return(await $("/api/health",{timeoutMs:Le})).ok}async function Er(){return(await $("/api/readiness",{timeoutMs:Le})).ok}function Or(r){let e=(0,h.existsSync)(M.default.join(r,"plugin","scripts"))?M.default.join(r,"plugin"):r;return M.default.join(e,"scripts","worker-service.cjs")}function po(){let r=M.default.dirname(M.default.dirname(ue)),e=M.default.join(r,"cache","thedotmack","opencode-mem");try{return(0,h.readdirSync)(e).filter(t=>/^\d/.test(t)).map(t=>M.default.join(e,t)).filter(t=>{try{return(0,h.statSync)(t).isDirectory()}catch{return!1}}).sort((t,n)=>(0,h.statSync)(n).mtimeMs-(0,h.statSync)(t).mtimeMs).map(Or)}catch{return[]}}function fo(){let r=process.env.OPENCODE_MEM_WORKER_SCRIPT_PATH?.trim();if(r){if((0,h.existsSync)(r))return r;a.debug("SYSTEM","Ignoring missing OPENCODE_MEM_WORKER_SCRIPT_PATH override",{override:r})}let e=[...po(),Or(M.default.join(ue,"plugin")),M.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let t of e)if((0,h.existsSync)(t))return t;return null}async function Eo(r){let e=r.backoffMs;for(let t=1;t<=r.attempts;t++){if(await yr())return!0;t<r.attempts&&(await new Promise(n=>setTimeout(n,e)),e*=2)}return!1}async function St(r=_r){if(r<=0)try{return await Er()}catch(t){let n=t instanceof Error?t:new Error(String(t));return a.debug("SYSTEM","Worker readiness check threw",{},n),!1}let e=Date.now();for(;Date.now()-e<r;){try{if(await Er())return!0}catch(n){a.debug("SYSTEM","Worker readiness check threw",{error:n instanceof Error?n.message:String(n)})}let t=r-(Date.now()-e);if(t<=0)break;await new Promise(n=>setTimeout(n,Math.min(250,t)))}return!1}async function Tr(){try{let e=await(await $("/api/health",{timeoutMs:Le})).json();return typeof e.version=="string"?e.version:null}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.debug("SYSTEM","Worker health-version fetch failed",{},e),null}}async function mo(r,e=_r){let t=Date.now();for(;Date.now()-t<e;){if(await Tr()===r)return!0;let o=e-(Date.now()-t);if(o<=0)break;await new Promise(i=>setTimeout(i,Math.min(500,o)))}return!1}async function _t(r){let e=await Tr();e!==null&&e!==r&&a.warn("SYSTEM","Worker is ready but still reports a stale version; not recycling again in this hook invocation (one recycle per hook event)",{pluginVersion:r,workerVersion:e})}async function yr(){let r;try{r=await lo()}catch(t){return a.debug("SYSTEM","Worker health check threw",{error:t instanceof Error?t.message:String(t)}),!1}if(!r)return!1;let e=Re({logAlive:!1});return e==="missing"||e==="alive"}async function Fe(){let r=null;if(await yr()){let{matches:i,pluginVersion:s,workerVersion:c}=await ur(hr());if(s!=="unknown"&&(r=s),i)return await St()?(r!==null&&await _t(r),!0):(a.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);a.info("SYSTEM","Worker version mismatch \u2014 recycling stale worker",{pluginVersion:s,workerVersion:c});let u=!1;try{await $("/api/admin/restart",{method:"POST",timeoutMs:Le}),u=!0}catch(d){let l=d instanceof Error?d:new Error(String(d));a.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{},l)}if(u){if(await mo(s))return await St()?(r!==null&&await _t(r),!0):(a.warn("SYSTEM","Recycled worker appeared but did not become ready; skipping hook API call"),!1);a.warn("SYSTEM","No successor worker appeared after recycle; falling through to lazy-spawn",{pluginVersion:s,workerVersion:c})}}let e=ir(),t=fo();if(!e)return a.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!t)return a.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let n=dr();try{if(n){a.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:e,scriptPath:t});try{Te(e,[t,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(s){return s instanceof Error?a.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:e,scriptPath:t},s):a.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:e,scriptPath:t,error:String(s)}),!1}}else a.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await Eo({attempts:6,backoffMs:500}))return a.warn("SYSTEM",n?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),!1}finally{n&&pr()}return await St()?(r!==null&&await _t(r),!0):(a.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var xe=null;async function go(){return xe!==null||(xe=await Fe()),xe}var So=3;function wr(){return M.default.join(S,"state")}function Pr(){return M.default.join(wr(),"hook-failures.json")}function _o(r){let e=JSON.parse(r);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}function Mr(){try{return _o((0,h.readFileSync)(Pr(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function vr(r){let e=wr(),t=Pr(),n=`${t}.tmp`;try{(0,h.existsSync)(e)||(0,h.mkdirSync)(e,{recursive:!0}),(0,h.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,h.renameSync)(n,t)}catch(o){a.debug("SYSTEM","Failed to persist hook-failure counter",{error:o instanceof Error?o.message:String(o)})}}function ho(){try{let e=H().OPENCODE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return So}var mr=null;async function Oo(){let e={consecutiveFailures:Mr().consecutiveFailures+1,lastFailureAt:Date.now()};vr(e);let t=ho();return e.consecutiveFailures>=t&&(e.consecutiveFailures===t&&await nr("hook_failed",{...mr!==null?{hook_type:mr}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),Ct(`opencode-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function gr(){Mr().consecutiveFailures!==0&&vr({consecutiveFailures:0,lastFailureAt:0})}var ht=Symbol.for("opencode-mem/worker-fallback");function We(r){return typeof r=="object"&&r!==null&&r[ht]===!0}async function He(r,e,t,n={}){if(!await go())return await Oo(),{continue:!0,reason:"worker_unreachable",[ht]:!0};let i={method:e};t!==void 0&&(i.headers={"Content-Type":"application/json"},i.body=JSON.stringify(t)),n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs);let s=await $(r,i);if(!s.ok){let u=await s.text().catch(()=>"");if(gr(),s.status===429||s.status>=500)return a.warn("SYSTEM",`Worker API ${e} ${r} returned ${s.status}; skipping hook API call`,{body:u.substring(0,200)}),{continue:!0,reason:`worker_api_${s.status}`,[ht]:!0};let d=u;try{d=JSON.parse(u)}catch{}return d}gr();let c=await s.text();if(c.length!==0)try{return JSON.parse(c)}catch{return c}}var Cr=require("os"),kr=K(require("path"),1),br=require("child_process");f();var Ue=require("fs"),ie=K(require("path"),1);f();var pe={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Rr(r){let e=ie.default.join(r,".git"),t;try{t=(0,Ue.statSync)(e)}catch(l){return l instanceof Error&&l.code!=="ENOENT"&&a.warn("GIT","Unexpected error checking .git",{error:l instanceof Error?l.message:String(l)}),pe}if(!t.isFile())return pe;let n;try{n=(0,Ue.readFileSync)(e,"utf-8").trim()}catch(l){return a.warn("GIT","Failed to read .git file",{error:l instanceof Error?l.message:String(l)}),pe}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return pe;let s=ie.default.resolve(ie.default.dirname(e),o[1]).match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!s)return pe;let c=s[1],u=ie.default.basename(r),d=ie.default.basename(c);return{isWorktree:!0,worktreeName:u,parentRepoPath:c,parentProjectName:d}}function Ir(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,Cr.homedir)()):r}function To(r){try{return(0,br.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.debug("PROJECT_NAME","git rev-parse failed, falling back to basename",{dir:r},t),null}}function yo(r){if(!r||r.trim()==="")return a.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Ir(r),n=To(e)??e,o=kr.default.basename(n);if(o===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let u=`drive-${s[1].toUpperCase()}`;return a.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:u}),u}}return a.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return o}function z(r){let e=yo(r);if(!r)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let t=Ir(r),n=Rr(t);if(n.isWorktree&&n.parentProjectName){let o=`${n.parentProjectName}/${e}`;return{primary:o,parent:n.parentProjectName,isWorktree:!0,allProjects:[n.parentProjectName,o]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}f();var Q=require("path");var Dr=require("os"),Nr=require("path");f();function wo(r){let e=r.startsWith("~")?(0,Dr.homedir)()+r.slice(1):r;e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function $e(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,Nr.basename)(t),o=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of o)try{let s=wo(i);if(s.test(t)||s.test(n))return!0}catch(s){a.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:s instanceof Error?s.message:String(s)});continue}return!1}T();function Po(r,e){let t=(0,Q.normalize)(r),n=(0,Q.normalize)(e);if(t===n)return!0;let o=(0,Q.relative)(n,t);return o.length>0&&!o.startsWith("..")&&!(0,Q.isAbsolute)(o)}function je(r){if(process.env.OPENCODE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if(Po(r,ze))return!1;let e=H();return!$e(r,e.OPENCODE_MEM_EXCLUDED_PROJECTS)}var Ar="claude";function Mo(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function x(r){if(!r)return Ar;let e=Mo(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Ar}f();var Fr=["private","opencode-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],xr=new RegExp(`<(${Fr.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Lr=100;function vo(r){let e=Object.fromEntries(Fr.map(o=>[o,0]));xr.lastIndex=0;let t=0,n=r.replace(xr,(o,i)=>(e[i]=(e[i]??0)+1,t+=1,""));return t>Lr&&a.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:Lr,contentLength:r.length}),{stripped:n.trim(),counts:e}}function yt(r){return vo(r).stripped}var Ro=["task-notification"],Co=new RegExp(`^\\s*<(${Ro.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),ko=256*1024;function Wr(r){return!r||r.length>ko?!1:Co.test(r)}f();var bo=B(k.API_REQUEST),j=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ge=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Io(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??bo}async startSession(e){let t=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new j("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new j("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:t,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:wt(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:wt(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:wt(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,t,n){if(!this.apiKey||!this.apiKey.trim())throw new j("missing_api_key","Server API key is not configured (OPENCODE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${t}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let s;try{s=await Ot(o,i,this.timeoutMs)}catch(u){let d=u instanceof Error?u.message:String(u),l=/timed out|timeout/i.test(d);throw new j(l?"timeout":"transport",`Server ${e} ${t} failed: ${d}`,{cause:u})}if(!s.ok){let u=await s.text().catch(()=>"");throw new j("http_error",`Server ${e} ${t} returned ${s.status}: ${Do(u,200)}`,{status:s.status})}let c=await s.text();if(!c||c.length===0)return{};try{return JSON.parse(c)}catch(u){let d=u instanceof Error?u:new Error(String(u));throw new j("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:d})}}};function Hr(r){return r instanceof j}function Io(r){return r.replace(/\/+$/,"")}function wt(r){return typeof r=="string"?x(r):null}function Do(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function No(){let e=(H().OPENCODE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Ao(){let r=H(),e=(...s)=>{for(let c of s){let u=(c??"").trim();if(u.length>0)return u}return""},t=e(r.OPENCODE_MEM_SERVER_URL,r.OPENCODE_MEM_SERVER_BETA_URL),n=e(r.OPENCODE_MEM_SERVER_API_KEY,r.OPENCODE_MEM_SERVER_BETA_API_KEY),o=e(r.OPENCODE_MEM_SERVER_PROJECT_ID,r.OPENCODE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return a.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return a.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return a.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new Ge(i),projectId:o,serverBaseUrl:t}}function Ur(){if(No()!=="server")return{runtime:"worker"};let r=Ao();return r||{runtime:"worker"}}function $r(r,e){a.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var xo={executeWithWorkerFallback:He,isWorkerFallback:We,loadFromFileOnce:H,resolveRuntimeContext:Ur,logServerFallback:$r,shouldTrackProject:je},J=xo;var jr={async execute(r){let{sessionId:e,prompt:t}=r,n=r.cwd??process.cwd();if(!e)return a.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:Y.SUCCESS};if(!J.shouldTrackProject(n))return a.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};if(t&&Wr(t))return a.debug("HOOK","session-init: skipping internal protocol payload",{preview:t.slice(0,80)}),{continue:!0,suppressOutput:!0};let o=!t||!t.trim()?"[media prompt]":t,i=z(n).primary,s=x(r.platform),c=J.loadFromFileOnce(),u=String(c.OPENCODE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",d=J.resolveRuntimeContext();if(d.runtime==="server")try{return await Lo(d,r,e,s,i,o),{continue:!0,suppressOutput:!0}}catch(g){if(Hr(g)&&g.isFallbackEligible())J.logServerFallback(g.kind,{status:g.status,message:g.message,route:"/v1/sessions/start"});else return a.error("HOOK","Server session-start failed (non-recoverable)",{error:g instanceof Error?g.message:String(g)}),{continue:!0,suppressOutput:!0,exitCode:Y.SUCCESS}}a.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:i});let l=await J.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:e,project:i,prompt:o,platformSource:s});if(J.isWorkerFallback(l))return{continue:!0,suppressOutput:!0,exitCode:Y.SUCCESS};if(typeof l?.sessionDbId!="number")return a.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:i}),{continue:!0,suppressOutput:!0,exitCode:Y.SUCCESS};let _=l.sessionDbId,m=l.promptNumber;if(a.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:_,promptNumber:m,skipped:l.skipped,contextInjected:l.contextInjected}),a.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${m} | sessionDbId=${_}`),l.skipped&&l.reason==="private")return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${_} | promptNumber=${m} | skipped=true | reason=private`,{sessionId:_}),{continue:!0,suppressOutput:!0};let y="";if(u&&o&&o.length>=20&&o!=="[media prompt]"){let g=c.OPENCODE_MEM_SEMANTIC_INJECT_LIMIT||"5",G=await J.executeWithWorkerFallback("/api/context/semantic","POST",{q:o,project:i,limit:g,platformSource:s});!J.isWorkerFallback(G)&&G?.context&&(a.debug("HOOK",`Semantic injection: ${G.count} observations for prompt`,{sessionId:_,count:G.count}),y=G.context)}return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${_} | promptNumber=${m} | project=${i}`,{sessionId:_}),y?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:y}}:{continue:!0,suppressOutput:!0}}};async function Lo(r,e,t,n,o,i){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:o,prompt:i}}),a.info("HOOK","session-init: server session started",{contentSessionId:t,project:o})}f();var Gr={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:o}=r,i=x(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(a.dataIn("HOOK",`FileEdit: ${n}`,{editCount:o?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!je(t))return a.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:Y.SUCCESS};let s=await He("/api/sessions/observations","POST",{contentSessionId:e,platformSource:i,tool_name:"write_file",tool_input:{filePath:n,edits:o},tool_response:{success:!0},cwd:t});return We(s)?{continue:!0,suppressOutput:!0,exitCode:Y.SUCCESS}:(a.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0})}};T();f();var b=require("fs"),Ke=require("path");f();f();T();var ka=O.settings();function Kr(r,e){let t="<opencode-mem-context>",n="</opencode-mem-context>";if(!r)return`${t}
|
|
18
18
|
${e}
|
|
19
19
|
${n}`;let o=r.indexOf(t),i=r.indexOf(n);return o!==-1&&i!==-1?r.substring(0,o)+`${t}
|