import{existsSync as a,readFileSync as p}from"node:fs";import{homedir as l}from"node:os";import{join as y,dirname as u,resolve as d}from"node:path";import{fileURLToPath as m}from"node:url";function f(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=u(m(import.meta.url)),e=d(r,"..","bin","mcp-skill.mjs");return a(e)?e:null}function k(){if(process.env.PROJECT_API_TOKEN)return process.env.PROJECT_API_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{let r=y(l(),".zibby","config.json");return a(r)&&JSON.parse(p(r,"utf-8")).sessionToken||null}catch{return null}}function _(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://api-prod.zibby.app"}function v(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function s(r){return`${v()}:${r}`}async function i(r,e){let t=k();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). KV memory is only available inside a Zibby run.");let n=`${_()}/credits/review-memory`,o=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({op:r,...e})});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`KV memory ${r} failed (${o.status}): ${c.slice(0,300)}`)}return o.json()}var T={id:"kv-memory",serverName:"kv_memory",allowedTools:["mcp__kv_memory__*"],description:"KV memory \u2014 a private, per-agent persistent key\u2192value store across stateless runs (auto-namespaced)",promptFragment:`## KV Memory (private, per-agent, persistent key-value store)
You have a PRIVATE per-agent key-value memory that survives across your
stateless runs. It is automatically namespaced to YOU (this agent type) \u2014 other
agents cannot see or collide with your entries, and you don't need to prefix
anything. Just use plain keys.

Tools:
- kv_recall: Recall the value stored under a plain \`key\` (exact match).
  Use at the START of a run to pick up what a prior run of yours recorded.
- kv_recall_prefix: List entries whose plain \`keyPrefix\` matches
  (e.g. "seen#" to list everything you've marked seen). Capped at 25.
- kv_store: Store (overwrite) a concise value under a plain \`key\`.
  Use to record durable facts \u2014 e.g. dedup markers, prior decisions, summaries.

Your namespace is added for you automatically; pass plain keys like
"seen#owner/repo#42" or "lastRun".`,resolve(){let r=f();if(!r)return{command:null,args:[],env:{},description:this.description};let e={};for(let t of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[t]&&(e[t]=process.env[t]);return{type:"stdio",command:"node",args:[r,"../dist/kvMemory.js","kvMemorySkill"],env:e,description:this.description,alwaysLoad:!0}},async handleToolCall(r,e){try{switch(r){case"kv_recall":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});let n=await i("recall",{scope:s(t)});return JSON.stringify(n)}case"kv_recall_prefix":{let t=typeof e?.keyPrefix=="string"?e.keyPrefix.trim():"";if(!t)return JSON.stringify({error:"keyPrefix is required"});let n=await i("recall-prefix",{scopePrefix:s(t)});return JSON.stringify(n)}case"kv_store":{let t=typeof e?.key=="string"?e.key.trim():"";if(!t)return JSON.stringify({error:"key is required"});if(typeof e?.content!="string"||e.content.length===0)return JSON.stringify({error:"content is required (non-empty string)"});let n={scope:s(t),content:e.content};e.metadata!=null&&(n.metadata=e.metadata);let o=await i("store",n);return JSON.stringify(o)}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(t){return JSON.stringify({error:t.message})}},tools:[{name:"kv_recall",description:'Recall the value you stored under a plain key (exact match). Your per-agent namespace is added automatically \u2014 pass a plain key like "seen#owner/repo#42".',input_schema:{type:"object",properties:{key:{type:"string",description:'Plain storage key (no namespace prefix needed) \u2014 e.g. "seen#owner/repo#42" or "lastRun".'}},required:["key"]}},{name:"kv_recall_prefix",description:'List your entries whose plain key STARTS WITH a prefix (e.g. "seen#"). Your per-agent namespace is added automatically. Capped at 25.',input_schema:{type:"object",properties:{keyPrefix:{type:"string",description:'Plain key prefix to match (no namespace prefix needed) \u2014 e.g. "seen#".'}},required:["keyPrefix"]}},{name:"kv_store",description:"Store (overwrite) a value under a plain key so a later run of yours can recall it. Your per-agent namespace is added automatically.",input_schema:{type:"object",properties:{key:{type:"string",description:"Plain storage key (no namespace prefix needed). Same key you recall by."},content:{type:"string",description:"The value to persist. Free-form markdown/text."},metadata:{type:"object",description:"Optional structured metadata."}},required:["key","content"]}}]};export{T as kvMemorySkill};
