import{existsSync as p,readFileSync as m}from"node:fs";import{homedir as f}from"node:os";import{join as h,dirname as E,resolve as g}from"node:path";import{fileURLToPath as T}from"node:url";function S(){if(process.env.MCP_SKILL_PATH)return process.env.MCP_SKILL_PATH;let r=E(T(import.meta.url)),t=g(r,"..","bin","mcp-skill.mjs");return p(t)?t:null}function l(){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=h(f(),".zibby","config.json");return p(r)&&JSON.parse(m(r,"utf-8")).sessionToken||null}catch{return null}}function u(){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 d(){return(typeof process.env.WORKFLOW_TYPE=="string"?process.env.WORKFLOW_TYPE.trim():"")||"agent"}function O(){let r={};for(let[t,e]of Object.entries(process.env)){let o=/^ZIBBY_STORE__(.+)$/.exec(t);if(!o)continue;let n=typeof e=="string"?e.trim():"";n&&(r[o[1]]=n)}return r}var a={};function I(){for(let r of Object.keys(a))delete a[r]}function i(r){let t={...O(),...a},e=Object.keys(t),o=typeof r=="string"?r.trim():"";return o?Object.prototype.hasOwnProperty.call(t,o)?{storeId:t[o],name:o}:{error:`unknown store '${o}'; available: ${e.join(", ")}`}:e.length===1?{storeId:t[e[0]],name:e[0]}:e.length===0?{error:"no stores bound to this agent"}:{error:`multiple stores are bound; pass \`store\` (one of: ${e.join(", ")})`}}async function b(r){let t=l();if(!t)throw new Error("No backend credential (PROJECT_API_TOKEN). Stores are only available inside a Zibby run.");let e=await fetch(`${u()}/datasets/stores/ensure`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let o=await e.text().catch(()=>"");throw new Error(`ensure_store failed (${e.status}): ${o.slice(0,300)}`)}return e.json()}async function c(r,t,e){let o=l();if(!o)throw new Error("No backend credential (PROJECT_API_TOKEN). Dataset store is only available inside a Zibby run.");let n=`${u()}/datasets/stores/${encodeURIComponent(r)}/${t}`,s=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!s.ok){let y=await s.text().catch(()=>"");throw new Error(`Store ${t} failed (${s.status}): ${y.slice(0,300)}`)}return s.json()}var L={id:"dataset-store",serverName:"dataset_store",allowedTools:["mcp__dataset_store__*"],description:"Dataset store \u2014 a durable, queryable store for structured JSON records; append rows now, run SQL-style aggregations/reports later",promptFragment:`## Dataset Store (durable, queryable structured-record store)
You have one or more durable stores for STRUCTURED records that survive across
your stateless runs. Unlike key-value memory (for picking up where you left
off), this is for accumulating DATA you want to QUERY and AGGREGATE later \u2014 e.g.
per-run metrics, processed items, findings \u2014 and turn into a report.

Your bound stores are listed in the "AVAILABLE STORES" block below (each with a
name + description). Pick one BY DESCRIPTION and pass its \`store\` NAME (e.g.
"scorecards") to the tools \u2014 NOT an id. If exactly one store is bound you may
omit \`store\` and it defaults to that one. You can ONLY write to a bound store
name; any other name is rejected. Each appended record is an arbitrary JSON
object, auto-tagged with YOUR agent type so you can later filter to your writes.

There are TWO kinds of bound store (shown as TYPE in AVAILABLE STORES):
\u2022 dataset \u2014 append-only structured records you QUERY/AGGREGATE later (analytics).
\u2022 sqlite  \u2014 a real, MUTABLE relational database (a SQLite file per store): CREATE
  TABLE on the fly, INSERT/UPDATE/DELETE, SELECT. Schema + data persist across
  runs. Use this when you need to UPDATE rows / track changing state (e.g. a
  queue with a status column), not just append.

You can also CREATE your own store on demand (no deploy needed) with
ensure_store \u2014 e.g. an agent that needs a private sqlite DB to track drafts/
state creates it at the start of the run and reuses it every run.

Tools:
- ensure_store: Create/reuse a store ON DEMAND for this agent (idempotent by
  name). Use when you need a store not bound at deploy. Then use its name with
  the tools below.
- dataset_append: (dataset stores) Append ONE structured JSON \`record\`.
- dataset_query: (dataset stores) SQL-style select/aggregate over appended records.
- sqlite_exec: (sqlite stores) Run SQL that CHANGES data \u2014 CREATE TABLE / INSERT /
  UPDATE / DELETE (one or more statements). Idempotent DDL: use CREATE TABLE IF
  NOT EXISTS. Returns { rowsModified, wrote }.
- sqlite_query: (sqlite stores) Run a SELECT (optionally with \`params\` for safe
  binding). Returns { columns, rows }. Read-only \u2014 never changes data.
Pick the tool that matches the store's TYPE; using a dataset tool on a sqlite
store (or vice-versa) is rejected.`,resolve(){let r=S();if(!r)return{command:null,args:[],env:{},description:this.description};let t={};for(let e of["PROJECT_API_TOKEN","ZIBBY_ACCOUNT_API_URL","ZIBBY_ENV","ZIBBY_PROD_ACCOUNT_API_URL","ZIBBY_USER_TOKEN","WORKFLOW_TYPE"])process.env[e]&&(t[e]=process.env[e]);for(let e of Object.keys(process.env))/^ZIBBY_STORE__.+$/.test(e)&&process.env[e]&&(t[e]=process.env[e]);return{type:"stdio",command:"node",args:[r,"../dist/datasetStore.js","datasetStoreSkill"],env:t,description:this.description,alwaysLoad:!1}},async handleToolCall(r,t){try{switch(r){case"dataset_append":{if(t?.record==null||typeof t.record!="object"||Array.isArray(t.record))return JSON.stringify({error:"record is required (a JSON object)"});let e=i(t?.store);if(e.error)return JSON.stringify({error:e.error});let o=typeof t?.agent=="string"&&t.agent.trim()?t.agent.trim():d(),n={record:t.record,agent:o};typeof t?.description=="string"&&t.description.trim()&&(n.description=t.description.trim());let s=await c(e.storeId,"append",n);return JSON.stringify({...s,store:e.name,storeId:e.storeId})}case"dataset_query":{let e=i(t?.store);if(e.error)return JSON.stringify({error:e.error});let o={};for(let s of["select","where","groupBy","orderBy","limit","since","until","agent"])t?.[s]!=null&&(o[s]=t[s]);let n=await c(e.storeId,"query",o);return JSON.stringify({...n,store:e.name,storeId:e.storeId})}case"ensure_store":{let e=typeof t?.name=="string"?t.name.trim():"";if(!e)return JSON.stringify({error:"name is required"});let o=typeof t?.type=="string"&&t.type.trim()?t.type.trim().toLowerCase():"sqlite",n=typeof t?.description=="string"?t.description.trim():"",s=await b({name:e,type:o,description:n,namespace:d()});return s?.storeId&&(a[e]=s.storeId),JSON.stringify({...s,store:e})}case"sqlite_exec":case"sqlite_query":{let e=i(t?.store);if(e.error)return JSON.stringify({error:e.error});if(typeof t?.sql!="string"||!t.sql.trim())return JSON.stringify({error:"sql is required (a non-empty SQL string)"});let o={sql:t.sql};Array.isArray(t?.params)&&(o.params=t.params);let n=await c(e.storeId,"sql",o);return JSON.stringify({...n,store:e.name,storeId:e.storeId})}default:return JSON.stringify({error:`Unknown tool: ${r}`})}}catch(e){return JSON.stringify({error:e.message})}},tools:[{name:"dataset_append",description:"Append ONE structured JSON record to a bound store, durably. Records persist across your stateless runs and are auto-tagged with your agent type so you can filter to your own writes later. Use to accumulate data you will query/aggregate (e.g. per-run metrics, processed items). Append ONE record per call.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to write to (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store; you can ONLY write to a bound store name.'},record:{type:"object",description:'An arbitrary JSON object \u2014 one row of data. Its keys become queryable fields (e.g. {"repo":"owner/x","stars":1200}). One record per call.'},description:{type:"string",description:"Optional, informational note about this write. The store already exists from deploy, so this is not required and does not create anything."},agent:{type:"string",description:"Optional writing-agent tag. Defaults to your own agent type \u2014 leave unset to auto-tag."}},required:["record"]}},{name:"dataset_query",description:"Run a SQL-style query over a bound store to build reports: select/aggregate (count|sum|avg|min|max), filter, group, order, limit, and bound by month. Returns { columns, rows }. Use this to compute summaries/aggregations from records you appended earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:'The logical store NAME to query (e.g. "scorecards"), taken from the AVAILABLE STORES list \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this and it defaults to that store.'},select:{type:"array",description:"Columns to return. Each item is { field?, agg?, as? }. agg \u2208 count|sum|avg|min|max; omit field for count(*). Omit `select` entirely to return raw rows."},where:{type:"array",description:"Filters, ANDed. Each item is { field, op, value }; op \u2208 eq|ne|gt|gte|lt|lte|like. `field` is a JSON key of the stored record."},groupBy:{type:"array",description:"Field names to group by (array of strings) for aggregation."},orderBy:{type:"array",description:"Sort spec. Each item is { field|as, dir }; dir \u2208 asc|desc."},limit:{type:"number",description:"Maximum number of rows to return."},since:{type:"string",description:"Inclusive lower bound month, 'yyyy-MM' (e.g. '2026-01')."},until:{type:"string",description:"Inclusive upper bound month, 'yyyy-MM' (e.g. '2026-06')."},agent:{type:"string",description:"Filter to records written by one agent namespace. Omit to query across all writers."}},required:[]}},{name:"ensure_store",description:'Create (or reuse) a store ON DEMAND for THIS agent \u2014 use when you need a store that was NOT declared/bound at deploy. Idempotent by name and private to this agent: calling again with the same name returns the SAME store (safe to call at the start of every run). Returns { storeId }. For type "sqlite" you then define schema with sqlite_exec (CREATE TABLE IF NOT EXISTS) and read/write via sqlite_exec/sqlite_query using this name.',input_schema:{type:"object",properties:{name:{type:"string",description:'A short logical name for the store (e.g. "linkedin_posts"). Letters, digits, _ and - only.'},type:{type:"string",enum:["sqlite","dataset"],description:'Store type. "sqlite" (default) = a mutable relational DB whose schema YOU define with SQL. "dataset" = append-only JSON records for later aggregation/analytics.'},description:{type:"string",description:"What this store is for (shown in the Storage UI)."}},required:["name"]}},{name:"sqlite_exec",description:"For SQLITE-type stores: run SQL that CHANGES data \u2014 CREATE TABLE (use IF NOT EXISTS), INSERT, UPDATE, DELETE (one or more statements in one call). The store is a real, mutable SQLite database that persists across your stateless runs. Returns { rowsModified, wrote }. Use this to build schema on the fly and to update rows / track changing state (e.g. a queue with a status column).",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:'The SQL to run. May contain multiple statements separated by ";". Prefer CREATE TABLE IF NOT EXISTS for idempotent schema.'},params:{type:"array",description:'Optional positional bind params for a SINGLE parameterized statement (safe binding of values), e.g. sql "UPDATE t SET s=? WHERE id=?" with params ["done", 1].'}},required:["sql"]}},{name:"sqlite_query",description:"For SQLITE-type stores: run a read-only SELECT (optionally with `params` for safe binding) against the store's SQLite database. Returns { columns, rows }. Never changes data. Use to read back rows/state you stored earlier.",input_schema:{type:"object",properties:{store:{type:"string",description:"The logical store NAME (a sqlite-type store from AVAILABLE STORES) \u2014 pick by description. NOT an id. If exactly one store is bound you may omit this."},sql:{type:"string",description:"A single SELECT statement. Use ? placeholders + `params` for any values."},params:{type:"array",description:'Optional positional bind params for the SELECT, e.g. ["linkedin_personal"].'}},required:["sql"]}}]};export{I as __clearEnsuredStores,L as datasetStoreSkill};
