@turbobase/cli 1.25.1 → 1.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -2048,7 +2048,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
2048
2048
|
`}var jM,ll,VS=C(()=>{Io();jM=10*1024*1024,ll=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??jM}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
2049
2049
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),LM(r)}clear(){this._buffer=void 0}}});import KS from"node:process";var ul,WS=C(()=>{VS();ul=class{constructor(e=KS.stdin,r=KS.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new ll({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=HS(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var GS,JS=C(()=>{GS=[]});var sT={};Yo(sT,{AUTHORING_MCP_SERVER_NAME:()=>eT,AUTHORING_MCP_SERVER_VERSION:()=>tT,AUTHORING_RESOURCES:()=>FM,AUTHORING_TOOLS:()=>ZM,AUTHORING_TOOLS_PUBLIC:()=>oT,buildAuthoringMcpServer:()=>nT,resolveSamplesDir:()=>rT,runAuthoringMcpServer:()=>HM});import{promises as DM}from"node:fs";import{isAbsolute as MM,resolve as dl,sep as UM}from"node:path";function QS(){return XS??=import("../mcp/grounding.js").then(e=>e,()=>null),XS}function rT(t,e){if(e===void 0)return dl(process.cwd(),t??"samples");let r=dl(e);if(t===void 0)return r;if(MM(t))return null;let n=dl(r,t);return n===r||n.startsWith(r+UM)?n:null}function Ve(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function BM(t,e={}){let r=e.fetchImpl??fetch;try{let n=await r(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return n.ok?((await n.json()).extensions??[]).map(s=>s.hookId).filter(s=>typeof s=="string"):null}catch{return null}}async function nT(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let m=await Xt(t.baseUrl);if(!m)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:m.baseUrl,token:m.token}}let r=t.grounding??{},n=await QS(),o=null;if(n)try{let m=await e();o={surface:"mcp-authoring",baseUrl:m.baseUrl,token:m.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],c=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{c=(await n.listRecipesForSurface(o,i)).map(m=>({id:m.id,record_type:m.record_type,intent:m.intent}))}catch{c=[]}}let l=o?await BM(o,r):null,u=new cl({name:eT,version:tT},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(m=>m.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let m=o;for(let h of a)u.registerPrompt(h.id,{title:h.name,description:h.description},async()=>{let b=await n.getMcpPromptSkill(m,h.id,r);if(!b)throw new Error(`unknown prompt: ${h.id}`);return{description:b.description,messages:[{role:"user",content:{type:"text",text:(b.prompts??[]).join(`
|
|
2050
2050
|
|
|
2051
|
-
`)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),b=await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog fetch failed: ${b.status}`);return Ve(await b.json())}),u.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:A.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:A.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:m,source:h})=>{let{baseUrl:b,token:$}=await e(),E=h?`?source=${encodeURIComponent(h)}`:"",P=await fetch(`${b}/v1/catalog/records/${encodeURIComponent(m)}${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown record type "${m}" \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`record anatomy fetch failed: ${P.status}`);return Ve(await P.json())}),u.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:A.array(A.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:A.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:m,source:h})=>{let{baseUrl:b,token:$}=await e(),E=new URLSearchParams({types:m.join(",")});h&&E.set("source",h);let P=await fetch(`${b}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`none of those record types resolved: ${m.join(", ")} \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`common columns fetch failed: ${P.status}`);return Ve(await P.json())}),u.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),b=await fetch(`${m}/v1/catalog/census`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog census failed: ${b.status}`);return Ve(await b.json())}),u.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:A.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:A.enum(YS).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:A.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:m,kind:h,limit:b})=>{let{baseUrl:$,token:E}=await e(),P=new URLSearchParams({q:m});h&&P.set("kind",h),b!==void 0&&P.set("limit",String(b));let z=await fetch(`${$}/v1/catalog/objects?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return Ve(await z.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:A.enum(YS),externalId:A.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:m,externalId:h})=>{let{baseUrl:b,token:$}=await e(),E=await fetch(`${b}/v1/catalog/objects/${encodeURIComponent(m)}/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${m}:${h} \u2014 find it with search_catalog.`);if(!E.ok)throw new Error(`catalog object fetch failed: ${E.status}`);return Ve(await E.json())}),u.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:A.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:A.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:m,limit:h})=>{let{baseUrl:b,token:$}=await e(),E=new URLSearchParams({q:m});h!==void 0&&E.set("limit",String(h));let P=await fetch(`${b}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!P.ok)throw new Error(`kb search failed: ${P.status}`);return Ve(await P.json())}),u.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:A.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:m})=>{let{baseUrl:h,token:b}=await e(),$=await fetch(`${h}/v1/kb/document/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return Ve(await $.json())}),u.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:A.boolean().optional()}},async({recordsOnly:m})=>{let{baseUrl:h,token:b}=await e();return{content:[{type:"text",text:await In({baseUrl:h,token:b,recordsOnly:m})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:A.string(),event:A.string().optional(),template:A.enum(["require-field","enforce-format","blank"]).optional(),field:A.string().optional(),regex:A.string().optional(),source:A.string().optional(),id:A.string().optional()}},async m=>{let h=mr("hook",{recordType:m.recordType,event:m.event,template:m.template,field:m.field,regex:m.regex,source:m.source,id:m.id});return Ve({path:h.relativePath,content:h.content})}),u.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:A.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:A.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:A.string().optional().describe("Target record type (defaults to the trigger record type)."),event:A.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:A.string().optional()}},async m=>{let h=mr("conduit",{recordType:m.recordType,source:m.source,to:m.to,toRecordType:m.toRecordType,event:m.event,id:m.id});return Ve({path:h.relativePath,content:h.content})}),u.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:A.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:A.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:A.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:A.string().optional()}},async m=>{let h=mr("process",{recordType:m.recordType,then:m.then,onFailure:m.onFailure,id:m.id});return Ve({path:h.relativePath,content:h.content})}),u.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:A.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:A.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:A.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:A.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:A.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:A.array(A.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async m=>{let{baseUrl:h,token:b}=await e(),$=new Y({baseUrl:h,token:b});return Ve(await $.authorConduit({intent:m.intent,from:{source:m.fromSource,recordType:m.fromRecordType},to:{source:m.toSource,recordType:m.toRecordType},...m.intentId?{intentId:m.intentId}:{},...m.columns?.length?{columns:m.columns}:{}}))}),u.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:A.string().describe("The extension TS source."),samplesDir:A.string().optional().describe('Samples directory (default "samples").')}},async({source:m,samplesDir:h})=>{let b=rT(h,t.samplesRoot);if(b===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:qM})}],isError:!0};let $;try{$=await cs(b)}catch(z){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw z}let E=await ta(m,$.map(z=>z.fixture)),P=E.filter(z=>!z.pass).length;return Ve({total:E.length,passed:E.length-P,results:E})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:A.string(),recordType:A.string(),event:A.string(),source:A.string().describe('Adapter id or "standalone".'),sourceCode:A.string().describe("The verbatim extension TS."),extensionKind:A.string().optional()}},async m=>{let{baseUrl:h,token:b}=await e(),E=await new Y({baseUrl:h,token:b}).deploy({id:m.id,recordType:m.recordType,event:m.event,source:m.source,sourceCode:m.sourceCode,extensionKind:m.extensionKind});return Ve(E)}),u.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:A.string(),limit:A.number().int().positive().optional()}},async({id:m,limit:h})=>{let{baseUrl:b,token:$}=await e(),E=new Y({baseUrl:b,token:$});return Ve({id:m,logs:await E.logs(m,h)})}),u.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),b=new Y({baseUrl:m,token:h});return Ve(await b.appsList())}),u.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:A.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:A.string().optional().describe("Display name (defaults to the slug)."),description:A.string().optional().describe("Short description.")}},async({slug:m,name:h,description:b})=>{let{baseUrl:$,token:E}=await e(),P=new Y({baseUrl:$,token:E});return Ve(await P.appsCreate({slug:m,name:h,description:b}))}),u.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:A.string().describe("App slug or id.")}},async({app:m})=>{let{baseUrl:h,token:b}=await e(),$=new Y({baseUrl:h,token:b});return Ve(await $.appsPull(m))}),u.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:A.string().describe("App slug or id."),files:A.record(A.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:A.string().optional().describe("Short note stored with the revision.")}},async({app:m,files:h,note:b})=>{let{baseUrl:$,token:E}=await e(),P=new Y({baseUrl:$,token:E});return Ve(await P.appsPush(m,h,{note:b}))});let p=A.object({name:A.string().describe("Field name (lowercase identifier)."),type:A.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:A.boolean().optional()}),w=A.object({slug:A.string().describe("Table slug; the physical table is cr_<slug>."),displayName:A.string().optional(),fields:A.array(p).describe("At least one field."),rowLevelOwner:A.boolean().optional().describe("Restrict non-admins to rows they created.")});return u.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),b=new Y({baseUrl:m,token:h});return Ve(await b.tablesList())}),u.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:A.array(w),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:h})=>{let{baseUrl:b,token:$}=await e(),E=new Y({baseUrl:b,token:$});return Ve(await E.tablesPlan({tables:m,claimedBy:h}))}),u.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:A.array(w),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:h})=>{let{baseUrl:b,token:$}=await e(),E=new Y({baseUrl:b,token:$});return Ve(await E.tablesApply({tables:m,claimedBy:h}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async m=>{let{baseUrl:h,token:b}=await e(),E=await(await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}})).text();return{contents:[{uri:m.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async m=>{let{baseUrl:h,token:b}=await e(),$=await In({baseUrl:h,token:b});return{contents:[{uri:m.href,mimeType:"text/plain",text:$}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async m=>{let h=dl(process.cwd(),"samples"),b=[];try{b=(await DM.readdir(h)).filter(E=>E.endsWith(".json"))}catch{b=[]}let $=await cs(h);return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({files:b,samples:$.map(E=>E.fixture)},null,2)}]}}),u.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async m=>{let h=await QS(),b=[];if(h){let{baseUrl:$,token:E}=await e();b=await h.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:E},r)}return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({recipes:b})}]}}),u}async function HM(t={}){let e=await nT(t),r=new ul;await e.connect(r)}var YS,XS,eT,tT,qM,oT,ZM,FM,iT=C(()=>{FS();WS();An();Yl();ss();fr();cu();ia();JS();YS=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];eT="turbobase-authoring",tT="0.1.0";qM="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";oT=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],ZM=[...oT,...GS],FM=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as ag}from"node:child_process";import{promises as be}from"node:fs";import{homedir as VM}from"node:os";import{basename as lT,dirname as Lr,join as Ot,relative as hl,resolve as ge,sep as ig}from"node:path";var Tg=bl(Sg(),1),{program:mU,createCommand:gU,createArgument:yU,createOption:bU,CommanderError:wU,InvalidArgumentError:vU,InvalidOptionArgumentError:_U,Command:Eg,Argument:xU,Option:kU,Help:$U}=Tg.default;Yl();ss();fr();cu();ea();import{promises as ky}from"node:fs";function xy(t,e){return e===t?"same-type-merge":"different-type-mint"}var $y=4;function lu(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=uo(t,"id"),r=uo(t,"on"),n=uo(t,"source"),o=uo(t,"recordType"),s=[];for(let c of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let l=uo(c[1]??"","source"),u=uo(c[1]??"","recordType");l&&u&&s.push({source:l,recordType:u})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):$y}}function uo(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function LR(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function Sy(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=lu(t)}catch(l){return{fixtureName:o,conduit:MR(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}let a=LR(e),c=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await Qi(t,{resolveDir:n.resolveDir}),p=!!(await as(l,a,{member:"when",timeoutMs:Xi})).whenResult;s.push({name:"from.when",status:p?"passed":"failed",detail:p?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let w=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${w} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!p)return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[]};let m=[],h=[],b=[];for(let E=0;E<i.targets.length;E+=1){let P=i.targets[E],z=await as(l,{...a,materialized:b.map(Dr=>({...Dr}))},{member:"transform",stepIndex:E,timeoutMs:Xi});m.push(...z.effects.logs);let B=z.effects.result;if(!B||typeof B!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${E+1})`:""} returned no result (expected { patch, createdFrom? })`);let W=B,Ke=xy(i.fromRecordType,P.recordType),{wouldWriteBindings:Ye,masterAction:Gt}=DR(i,P,Ke,e);h.push({to:P,transformResult:W,applyBranch:Ke,wouldWriteBindings:Ye,masterAction:Gt}),b.push({source:P.source,recordType:P.recordType,masterTable:`<${P.recordType} master, dry-run>`,masterRowId:`<dry-run target ${E+1}>`,externalId:null})}let $=h[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,transformResult:$.transformResult,applyBranch:$.applyBranch,wouldWriteBindings:$.wouldWriteBindings,masterAction:$.masterAction,targets:h,logs:m}}catch(l){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function DR(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:n.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function MR(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:$y}}async function Ty(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function Ey(t){let e=await ky.readFile(t,"utf8");return JSON.parse(e)}function Ry(t){return ky.readFile(t,"utf8")}function Py(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let n=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(n){let a=t.targets.reduce((c,l)=>c+l.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let o=[];o.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),o.push(`conduit: ${r.id}`);let s=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");o.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${s}${r.on?` on=${r.on}`:""}`),o.push(""),o.push("guards (dispatch order):");for(let a of t.guards){let c=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";o.push(` ${c} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(o.push(""),o.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)o.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)o.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return o.push(""),o.push("transform: SKIPPED (from.when gate did not fire)."),o.join(`
|
|
2051
|
+
`)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),b=await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog fetch failed: ${b.status}`);return Ve(await b.json())}),u.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:A.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:A.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:m,source:h})=>{let{baseUrl:b,token:$}=await e(),E=h?`?source=${encodeURIComponent(h)}`:"",P=await fetch(`${b}/v1/catalog/records/${encodeURIComponent(m)}${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown record type "${m}" \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`record anatomy fetch failed: ${P.status}`);return Ve(await P.json())}),u.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:A.array(A.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:A.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:m,source:h})=>{let{baseUrl:b,token:$}=await e(),E=new URLSearchParams({types:m.join(",")});h&&E.set("source",h);let P=await fetch(`${b}/v1/catalog/columns?${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`none of those record types resolved: ${m.join(", ")} \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`common columns fetch failed: ${P.status}`);return Ve(await P.json())}),u.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),b=await fetch(`${m}/v1/catalog/census`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!b.ok)throw new Error(`catalog census failed: ${b.status}`);return Ve(await b.json())}),u.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:A.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:A.enum(YS).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:A.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:m,kind:h,limit:b})=>{let{baseUrl:$,token:E}=await e(),P=new URLSearchParams({q:m});h&&P.set("kind",h),b!==void 0&&P.set("limit",String(b));let z=await fetch(`${$}/v1/catalog/objects?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return Ve(await z.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:A.enum(YS),externalId:A.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:m,externalId:h})=>{let{baseUrl:b,token:$}=await e(),E=await fetch(`${b}/v1/catalog/objects/${encodeURIComponent(m)}/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(E.status===404)throw new Error(`unknown object ${m}:${h} \u2014 find it with search_catalog.`);if(!E.ok)throw new Error(`catalog object fetch failed: ${E.status}`);return Ve(await E.json())}),u.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:A.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:A.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:m,limit:h})=>{let{baseUrl:b,token:$}=await e(),E=new URLSearchParams({q:m});h!==void 0&&E.set("limit",String(h));let P=await fetch(`${b}/v1/kb/search?${E}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!P.ok)throw new Error(`kb search failed: ${P.status}`);return Ve(await P.json())}),u.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:A.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:m})=>{let{baseUrl:h,token:b}=await e(),$=await fetch(`${h}/v1/kb/document/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return Ve(await $.json())}),u.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:A.boolean().optional()}},async({recordsOnly:m})=>{let{baseUrl:h,token:b}=await e();return{content:[{type:"text",text:await In({baseUrl:h,token:b,recordsOnly:m})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:A.string(),event:A.string().optional(),template:A.enum(["require-field","enforce-format","blank"]).optional(),field:A.string().optional(),regex:A.string().optional(),source:A.string().optional(),id:A.string().optional()}},async m=>{let h=mr("hook",{recordType:m.recordType,event:m.event,template:m.template,field:m.field,regex:m.regex,source:m.source,id:m.id});return Ve({path:h.relativePath,content:h.content})}),u.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:A.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:A.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:A.string().optional().describe("Target record type (defaults to the trigger record type)."),event:A.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:A.string().optional()}},async m=>{let h=mr("conduit",{recordType:m.recordType,source:m.source,to:m.to,toRecordType:m.toRecordType,event:m.event,id:m.id});return Ve({path:h.relativePath,content:h.content})}),u.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:A.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:A.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:A.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:A.string().optional()}},async m=>{let h=mr("process",{recordType:m.recordType,then:m.then,onFailure:m.onFailure,id:m.id});return Ve({path:h.relativePath,content:h.content})}),u.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:A.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:A.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:A.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:A.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:A.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:A.array(A.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async m=>{let{baseUrl:h,token:b}=await e(),$=new Y({baseUrl:h,token:b});return Ve(await $.authorConduit({intent:m.intent,from:{source:m.fromSource,recordType:m.fromRecordType},to:{source:m.toSource,recordType:m.toRecordType},...m.intentId?{intentId:m.intentId}:{},...m.columns?.length?{columns:m.columns}:{}}))}),u.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:A.string().describe("The extension TS source."),samplesDir:A.string().optional().describe('Samples directory (default "samples").')}},async({source:m,samplesDir:h})=>{let b=rT(h,t.samplesRoot);if(b===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:qM})}],isError:!0};let $;try{$=await cs(b)}catch(z){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw z}let E=await ta(m,$.map(z=>z.fixture)),P=E.filter(z=>!z.pass).length;return Ve({total:E.length,passed:E.length-P,results:E})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:A.string(),recordType:A.string(),event:A.string(),source:A.string().describe('Adapter id or "standalone".'),sourceCode:A.string().describe("The verbatim extension TS."),extensionKind:A.string().optional()}},async m=>{let{baseUrl:h,token:b}=await e(),E=await new Y({baseUrl:h,token:b}).deploy({id:m.id,recordType:m.recordType,event:m.event,source:m.source,sourceCode:m.sourceCode,extensionKind:m.extensionKind});return Ve(E)}),u.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:A.string(),limit:A.number().int().positive().optional()}},async({id:m,limit:h})=>{let{baseUrl:b,token:$}=await e(),E=new Y({baseUrl:b,token:$});return Ve({id:m,logs:await E.logs(m,h)})}),u.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),b=new Y({baseUrl:m,token:h});return Ve(await b.appsList())}),u.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:A.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:A.string().optional().describe("Display name (defaults to the slug)."),description:A.string().optional().describe("Short description.")}},async({slug:m,name:h,description:b})=>{let{baseUrl:$,token:E}=await e(),P=new Y({baseUrl:$,token:E});return Ve(await P.appsCreate({slug:m,name:h,description:b}))}),u.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:A.string().describe("App slug or id.")}},async({app:m})=>{let{baseUrl:h,token:b}=await e(),$=new Y({baseUrl:h,token:b});return Ve(await $.appsPull(m))}),u.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:A.string().describe("App slug or id."),files:A.record(A.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:A.string().optional().describe("Short note stored with the revision.")}},async({app:m,files:h,note:b})=>{let{baseUrl:$,token:E}=await e(),P=new Y({baseUrl:$,token:E});return Ve(await P.appsPush(m,h,{note:b}))});let p=A.object({name:A.string().describe("Field name (lowercase identifier)."),type:A.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:A.boolean().optional()}),w=A.object({slug:A.string().describe("Table slug; the physical table is cr_<slug>."),displayName:A.string().optional(),fields:A.array(p).describe("At least one field."),rowLevelOwner:A.boolean().optional().describe("Restrict non-admins to rows they created.")});return u.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),b=new Y({baseUrl:m,token:h});return Ve(await b.tablesList())}),u.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:A.array(w),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:h})=>{let{baseUrl:b,token:$}=await e(),E=new Y({baseUrl:b,token:$});return Ve(await E.tablesPlan({tables:m,claimedBy:h}))}),u.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:A.array(w),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:h})=>{let{baseUrl:b,token:$}=await e(),E=new Y({baseUrl:b,token:$});return Ve(await E.tablesApply({tables:m,claimedBy:h}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async m=>{let{baseUrl:h,token:b}=await e(),E=await(await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}})).text();return{contents:[{uri:m.href,mimeType:"application/json",text:E}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async m=>{let{baseUrl:h,token:b}=await e(),$=await In({baseUrl:h,token:b});return{contents:[{uri:m.href,mimeType:"text/plain",text:$}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async m=>{let h=dl(process.cwd(),"samples"),b=[];try{b=(await DM.readdir(h)).filter(E=>E.endsWith(".json"))}catch{b=[]}let $=await cs(h);return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({files:b,samples:$.map(E=>E.fixture)},null,2)}]}}),u.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async m=>{let h=await QS(),b=[];if(h){let{baseUrl:$,token:E}=await e();b=await h.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:E},r)}return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({recipes:b})}]}}),u}async function HM(t={}){let e=await nT(t),r=new ul;await e.connect(r)}var YS,XS,eT,tT,qM,oT,ZM,FM,iT=C(()=>{FS();WS();An();Yl();ss();fr();cu();ia();JS();YS=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];eT="turbobase-authoring",tT="0.1.0";qM="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";oT=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],ZM=[...oT,...GS],FM=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as ag}from"node:child_process";import{promises as be}from"node:fs";import{homedir as VM}from"node:os";import{basename as lT,dirname as Lr,join as Ot,relative as hl,resolve as ge,sep as ig}from"node:path";var Tg=bl(Sg(),1),{program:mU,createCommand:gU,createArgument:yU,createOption:bU,CommanderError:wU,InvalidArgumentError:vU,InvalidOptionArgumentError:_U,Command:Eg,Argument:xU,Option:kU,Help:$U}=Tg.default;Yl();ss();fr();cu();ea();import{promises as ky}from"node:fs";function xy(t,e){return e===t?"same-type-merge":"different-type-mint"}var $y=4;function lu(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=uo(t,"id"),r=uo(t,"on"),n=uo(t,"source"),o=uo(t,"recordType"),s=[];for(let c of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let l=uo(c[1]??"","source"),u=uo(c[1]??"","recordType");l&&u&&s.push({source:l,recordType:u})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):$y}}function uo(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function LR(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function Sy(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=lu(t)}catch(l){return{fixtureName:o,conduit:MR(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}let a=LR(e),c=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await Qi(t,{resolveDir:n.resolveDir}),p=!!(await as(l,a,{member:"when",timeoutMs:Xi})).whenResult;s.push({name:"from.when",status:p?"passed":"failed",detail:p?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let w=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${w} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!p)return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[]};let m=[],h=[],b=[];for(let E=0;E<i.targets.length;E+=1){let P=i.targets[E],z=await as(l,{...a,materialized:b.map(Dr=>({...Dr}))},{member:"transform",stepIndex:E,timeoutMs:Xi});m.push(...z.effects.logs);let B=z.effects.result;if(!B||typeof B!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${E+1})`:""} returned no result (expected { patch, createdFrom? })`);let W=B,Ke=xy(i.fromRecordType,P.recordType),{wouldWriteBindings:Ye,masterAction:Gt}=DR(i,P,Ke,e);h.push({to:P,transformResult:W,applyBranch:Ke,wouldWriteBindings:Ye,masterAction:Gt}),b.push({source:P.source,recordType:P.recordType,masterTable:`<${P.recordType} master, dry-run>`,masterRowId:`<dry-run target ${E+1}>`,externalId:null})}let $=h[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,transformResult:$.transformResult,applyBranch:$.applyBranch,wouldWriteBindings:$.wouldWriteBindings,masterAction:$.masterAction,targets:h,logs:m}}catch(l){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function DR(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function MR(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:$y}}async function Ty(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function Ey(t){let e=await ky.readFile(t,"utf8");return JSON.parse(e)}function Ry(t){return ky.readFile(t,"utf8")}function Py(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let n=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(n){let a=t.targets.reduce((c,l)=>c+l.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let o=[];o.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),o.push(`conduit: ${r.id}`);let s=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");o.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${s}${r.on?` on=${r.on}`:""}`),o.push(""),o.push("guards (dispatch order):");for(let a of t.guards){let c=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";o.push(` ${c} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(o.push(""),o.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)o.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)o.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return o.push(""),o.push("transform: SKIPPED (from.when gate did not fire)."),o.join(`
|
|
2052
2052
|
`);let i=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(i.forEach((a,c)=>{let l=n?` (target ${c+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";o.push(""),o.push(`transform${l} \u2192 patch:`),o.push(UR(JSON.stringify(a.transformResult.patch??{},null,2)," ")),a.transformResult.createdFrom&&o.push(` createdFrom: ${JSON.stringify(a.transformResult.createdFrom)}`),o.push(""),o.push(`apply-branch${l}: ${a.applyBranch}`),o.push(` ${a.masterAction}`),o.push(""),o.push(`bindings that WOULD be written (txn_source_link)${l}:`);for(let u of a.wouldWriteBindings)o.push(` ${u.source} role=${u.role} external_id=${u.externalId??"null"} \u2014 ${u.why}`)}),t.logs.length>0){o.push(""),o.push("conduit logs:");for(let a of t.logs)o.push(` [${a.level}] ${a.message}${a.meta?` ${JSON.stringify(a.meta)}`:""}`)}return o.join(`
|
|
2053
2053
|
`)}function UR(t,e){return t.split(`
|
|
2054
2054
|
`).map(r=>e+r).join(`
|
|
@@ -3747,7 +3747,7 @@ ${o.map(iP).join(`
|
|
|
3747
3747
|
`))}async function Bb(t,e,r=bo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await wo(e,r);if(!await ga(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await ae("publishing",()=>o.skillsPublish(n))}catch(a){oe(a,"skills:publish","publish a skill"),k(`publish failed: ${a instanceof Error?a.message:String(a)}`)}v(g.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),q(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function Zb(t,e,r=bo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await wo(e,r);if(!await ga(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await ae("unpublishing",()=>o.skillsUnpublish(n))}catch(a){oe(a,"skills:publish","unpublish a skill"),k(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}v(g.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),q(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Fb(t,e,r=bo){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await wo(e,r);if(await ga(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await ae("rolling back",()=>o.skillsRollback(n));v(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){oe(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Hb(t,e=bo){let r=await wo(t,e),n;try{n=await ae("reading the releases",()=>r.skillsReleases())}catch(o){oe(o,"skills:publish","read the skills releases"),k(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){q("no releases yet.");return}for(let o of n.items){let s=o.is_current?g.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";v(`${s} v${o.version_no} ${o.skill_count} skill(s) ${g.dim(o.published_at)}${o.published_by?g.dim(` by ${o.published_by}`):""}${g.dim(i)}`)}}async function Vb(t,e,r=bo){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&k("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await wo(e,r);if(!await ga(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
|
|
3748
3748
|
${n.join(`
|
|
3749
3749
|
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let l of n)try{i.push(await ae(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof ce&&u.status===404){a.push(l);continue}i.length>0&&q(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),oe(u,"skills:publish","delete a skill"),k(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&v(g.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&q(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(q(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Kb}from"node:fs";import{join as zP,relative as jP,resolve as LP,sep as DP}from"node:path";var MP=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),UP=new Set([".mcp.json",".env"]);function qP(t){return UP.has(t)||t.startsWith(".env.")&&t!==".env.example"}function BP(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function ZP(t){return t.includes(0)}async function Wb(t){let e=LP(t),r={},n=[],o=[],s=[];async function i(a){let c=await Kb.readdir(a,{withFileTypes:!0});for(let l of c){let u=zP(a,l.name);if(MP.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=jP(e,u).split(DP).join("/");if(qP(l.name)){o.push(p);continue}let w=await Kb.readFile(u);if(!BP(w)){n.push(p);continue}ZP(w)&&s.push(p),r[p]=w.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as FP}from"node:crypto";var HP="/_tb/app-assets",VP=16,KP=/^[0-9a-f]{32}$/;function Gb(){return FP(VP).toString("hex")}function WP(t){return KP.test(t)}function Jb(t){if(!WP(t))throw new Error(`not a build id: ${t}`);return`${HP}/${t}/`}var Yb=7;Pu();var Au=50*1024*1024;import ya from"node:fs/promises";import gs from"node:path";var Iu={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ou="@turbobase/isolated-vm-prebuilds";function Cu(t,e){return`${t}-${e}`}function Nu(t=process.versions){return`abi${t.modules}`}var Xb=["darwin-x64","win32-arm64"];async function Qb(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Cu(e,r),o=gs.join(t.home,"node_modules"),s=gs.join(o,...Ou.split("/"),"prebuilds",n),i=gs.join(o,"isolated-vm","prebuilds",n),a;try{a=await ya.readdir(s)}catch{return[]}let c=[];await ya.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=gs.join(i,l);try{await ya.copyFile(gs.join(s,l),u,ya.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as GP}from"node:os";import{join as ew}from"node:path";import{promises as zu}from"node:fs";function rw(){let t=process.env.TURBOBASE_HOME??ew(GP(),".turbobase");return{dir:t,file:ew(t,"sandboxes.json")}}var JP={s:1e3,m:6e4,h:36e5,d:864e5};function YP(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return r*JP[e[2]]}function XP(t,e=Date.now()){return new Date(e+YP(t)).toISOString()}function QP(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function eA(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return r/100}function tA(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var rA="[REDACTED]",ys=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},ju=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function nA(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new ju(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:rA:n[o]=s}return n}function oA(t,e,r){return e.map(n=>nA(t,n,r))}var tw=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),sA=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function iA(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Lu(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of sA)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=iA(t);if(!tw.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...tw].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function aA(t,e=cA){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function cA(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function lA(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function uA(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Du(){let{file:t}=rw();try{let e=await zu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function nw(t){let{dir:e,file:r}=rw();await zu.mkdir(e,{recursive:!0}),await zu.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
3750
|
-
`,{mode:384})}async function dA(t){let e=await Du();e.push(t),await nw(e)}async function ow(t){let e=await Du(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await nw(e),n??null}async function ba(){return Du()}function Mu(t,e=Date.now()){let r=[],n=[];for(let o of t)QP(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function sw(t,e){Lu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new ys(r);let n=eA(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>aA(l)))(e.fromTenant),i=lA(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=tA(l.rows,n),p=oA(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:XP(e.ttl,o),sampleFraction:n,url:uA(s,e.baseUrl)};return await dA(c),c}async function iw(t,e){Lu(t.target());let n=(await ba()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await ow(e),n):null}async function Uu(t,e=Date.now()){Lu(t.target());let r=await ba(),{expired:n}=Mu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await ow(s.name),o.push(s)}return o}var bs={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},rF=Object.keys(bs).filter(t=>bs[t].mintable);var sF=bs.pat.prefix,pA=Object.entries(bs).map(([t,e])=>[e.prefix,t]),hA=/^[A-Za-z0-9_-]{20,}$/;function fA(t){if(typeof t!="string")return null;for(let[e,r]of pA)if(t.startsWith(e)&&hA.test(t.slice(e.length)))return r;return null}function aw(t){return fA(t)==="pat"}ss();var mA=8e3,gA={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function yA(t){return gA[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function bA(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(mA)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function cw(t){return t.state==="accepted"?tt()?g.green("accepted"):"accepted":t.state==="rejected"?tt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:tt()?g.yellow("unreachable"):"unreachable"}async function lw(t={},e=fetch){let r=await Pr(),{file:n}=Vi();if(r.length===0){v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Xt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await bA(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(tt())v(Qt(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),cw(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} ${cw(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${yA(i.check.reason)}.`)),q(g.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function KM(t){let e=await Pr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ft()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await mt(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function WM(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function GM(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function JM(t,e,r){let n=await uy({baseUrl:t,token:e}),o=(await Pr()).length-1;if(v(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),GM(n.baseUrl),!r)return;let s=await WM(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function YM(t){let e=await iu(await ls(t),Lr(t)),r=wu(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);k(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function Xn(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Lr(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function aT(t,e){if(lT(t)!==".gitignore")return Xn(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return Xn(t,e.content,e.executable,e.mode);let n=Xy(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function rg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function pl(t){process.exit(t)}function XM(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function QM(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function eU(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function cT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function cg({includeInternal:t=!0}={}){let e=new Eg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.25.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${hu()}
|
|
3750
|
+
`,{mode:384})}async function dA(t){let e=await Du();e.push(t),await nw(e)}async function ow(t){let e=await Du(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await nw(e),n??null}async function ba(){return Du()}function Mu(t,e=Date.now()){let r=[],n=[];for(let o of t)QP(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function sw(t,e){Lu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new ys(r);let n=eA(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>aA(l)))(e.fromTenant),i=lA(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=tA(l.rows,n),p=oA(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:XP(e.ttl,o),sampleFraction:n,url:uA(s,e.baseUrl)};return await dA(c),c}async function iw(t,e){Lu(t.target());let n=(await ba()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await ow(e),n):null}async function Uu(t,e=Date.now()){Lu(t.target());let r=await ba(),{expired:n}=Mu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await ow(s.name),o.push(s)}return o}var bs={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},rF=Object.keys(bs).filter(t=>bs[t].mintable);var sF=bs.pat.prefix,pA=Object.entries(bs).map(([t,e])=>[e.prefix,t]),hA=/^[A-Za-z0-9_-]{20,}$/;function fA(t){if(typeof t!="string")return null;for(let[e,r]of pA)if(t.startsWith(e)&&hA.test(t.slice(e.length)))return r;return null}function aw(t){return fA(t)==="pat"}ss();var mA=8e3,gA={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function yA(t){return gA[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function bA(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(mA)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function cw(t){return t.state==="accepted"?tt()?g.green("accepted"):"accepted":t.state==="rejected"?tt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:tt()?g.yellow("unreachable"):"unreachable"}async function lw(t={},e=fetch){let r=await Pr(),{file:n}=Vi();if(r.length===0){v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Xt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await bA(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(tt())v(Qt(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),cw(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} ${cw(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${yA(i.check.reason)}.`)),q(g.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function KM(t){let e=await Pr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ft()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await mt(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function WM(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function GM(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function JM(t,e,r){let n=await uy({baseUrl:t,token:e}),o=(await Pr()).length-1;if(v(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),GM(n.baseUrl),!r)return;let s=await WM(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function YM(t){let e=await iu(await ls(t),Lr(t)),r=wu(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);k(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function Xn(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Lr(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function aT(t,e){if(lT(t)!==".gitignore")return Xn(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return Xn(t,e.content,e.executable,e.mode);let n=Xy(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function rg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function pl(t){process.exit(t)}function XM(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function QM(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function eU(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function cT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function cg({includeInternal:t=!0}={}){let e=new Eg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.27.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${hu()}
|
|
3751
3751
|
`),e.hook("preAction",(d,f)=>{db(e.opts(),f.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let f=Dt(d.baseUrl);d.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
3752
3752
|
${hs} auth login --base-url ${f} --token tb_pat_\u2026`),aw(d.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await JM(f,d.token,d.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async d=>lw({probe:d.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let f=d??await KM("Pick the active instance:"),_=await Ki(f);if(!_){let T=await Pr();k(`no stored sign-in for ${Dt(f)}.`+(T.length?` Stored: ${T.map(x=>x.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Dt(f)} --token tb_pat_\u2026\`.`)}v(`active instance \u2192 ${_.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let T=await Pr();for(let x of T)await eu(x.baseUrl);v(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let f=await eu(d.baseUrl);f||k(d.baseUrl?`no stored sign-in for ${Dt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let _=await Xt();v(`signed out of ${f}.`+(_?` Active instance \u2192 ${_.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:f,token:_}=await re(d.baseUrl),T;try{T=await In({baseUrl:f,token:_,recordsOnly:d.recordsOnly})}catch(y){let S=y instanceof Error?y.message:String(y);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(S)){q("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{T=await In({baseUrl:f,token:_,recordsOnly:!0})}catch(R){k(`types generation failed: ${R instanceof Error?R.message:String(R)}`)}}else k(`types generation failed: ${S}`)}let x=ge(process.cwd(),d.out);await be.writeFile(x,T,"utf8"),v(`wrote ${x} (${T.split(`
|
|
3753
3753
|
`).length} lines).`)}),fb(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async d=>{let{baseUrl:f,token:_}=await re(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let x=T.toString(),y=await fetch(`${f}/v1/catalog/grounding${x?`?${x}`:""}`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});y.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let R=((await y.json()).markdown??"").trim(),N=ge(process.cwd(),d.out),L=d.records?` records=${d.records}`:"",D=`<!-- GENERATED by \`turbobase project grounding\` against ${f}${L} \u2014 do not edit; re-run to refresh. -->
|
|
@@ -3777,7 +3777,7 @@ samples init: ${R} written, ${N} skipped.`)});let lr=e.command("guardrails").des
|
|
|
3777
3777
|
`+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));v(Qt(x.map($i),{head:fl})),v(g.dim(" first match wins; lower PRIO is evaluated first."))}),lr.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:_,token:T}=await re(f.baseUrl),x=new Y({baseUrl:_,token:T}),y;try{y=await x.guardrailCreate({name:d,source:f.source,record:f.record,decision:f.decision,...f.op?{op:f.op}:{},...f.target?{target:f.target}:{},...f.actor?{actor:f.actor}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when?{when:f.when}:{},...f.reason?{reason:f.reason}:{},...f.disabled?{enabled:!1}:{},...f.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){oe(S,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} created${y.status==="active"?"":g.dim(` (${y.status} \u2014 activate it to take effect)`)}`),v(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),v(g.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),lr.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{f.decision===void 0&&f.priority===void 0&&f.when===void 0&&f.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:_,token:T}=await re(f.baseUrl),x=new Y({baseUrl:_,token:T}),y;try{y=await x.guardrailUpdate(d,{...f.decision!==void 0?{decision:f.decision}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when!==void 0?{when:f.when}:{},...f.reason!==void 0?{reason:f.reason}:{}})}catch(S){oe(S,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} updated`),v(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,f,_]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])lr.command(`${d} <name>`).description(f==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(T,x)=>{let{baseUrl:y,token:S}=await re(x.baseUrl),R=new Y({baseUrl:y,token:S});try{await R.guardrailUpdate(T,{status:f})}catch(N){oe(N,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${N instanceof Error?N.message:String(N)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(T)} ${_}`),f==="inactive"&&v(g.dim(" writes it was gating now fall through to the other rules."))});lr.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:_,token:T}=await re(f.baseUrl),x=new Y({baseUrl:_,token:T});try{await x.guardrailDelete(d)}catch(y){oe(y,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),lr.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:_,token:T}=await re(f.baseUrl),x=new Y({baseUrl:_,token:T}),y=N=>N==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let N;try{N=await x.guardrailPostureGet()}catch(L){oe(L,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${L instanceof Error?L.message:String(L)}`)}v(`guardrail posture: ${g.bold(y(N.mode))}`),v(g.dim(N.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let S=d.trim().toLowerCase();S!=="allow"&&S!=="deny"&&k("posture must be 'allow' or 'deny'.");let R;try{R=await x.guardrailPostureSet(S)}catch(N){oe(N,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${N instanceof Error?N.message:String(N)}`)}v(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(R.mode))}`),R.mode==="deny"&&v(g.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),lr.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let f;if(d.fields)try{f=JSON.parse(d.fields)}catch(R){k(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:_,token:T}=await re(d.baseUrl),x=new Y({baseUrl:_,token:T}),y;try{y=await x.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...f?{fields:f}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){oe(R,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return v(JSON.stringify(y,null,2));let S=`${d.source}/${y.op??d.record}`;y.degraded?(v(`${g.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),v(g.dim(` ${y.reason}`))):y.allowed?v(`${g.green("\u2713")} ${S} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(v(`${g.red("\u2717")} ${S} \u2014 ${y.decision} by ${g.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&v(g.dim(` ${y.message}`))),y.decision==="require_confirm"&&v(g.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let Go=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Si=(d,f={})=>{let _=`${g.bold(d.table)} ${g.dim(d.displayName)}`;v(d.exists===!1?`${_} ${g.dim("(new)")}`:_);for(let T of d.fields){let x=[T.required?"required":null].filter(Boolean).join(", "),y=f.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";v(` ${T.column.padEnd(28)} ${T.type}${x?` (${x})`:""}${y}`)}f.showClaimants&&d.claimants.length>1&&v(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Ti(d){if(d instanceof ce&&d.status===409){let f=d.body;f?.error==="table_conflict"&&f.message&&(q(f.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let lg=async d=>{let f=Ot(ge(process.cwd(),d),"public","turbobase.json"),_=await be.readFile(f,"utf8").catch(()=>null);if(_===null)return null;let T;try{T=JSON.parse(_)}catch(y){k(`${f} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let x=T.tables;return x===void 0?{tables:[],manifestPath:f}:(Array.isArray(x)||k(`${f}: "tables" must be an array.`),{tables:x,manifestPath:f})};Go.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:f,token:_}=await re(d.baseUrl),T=new Y({baseUrl:f,token:_}),x;try{x=await T.tablesList()}catch(y){oe(y,"extensions:deploy","list tables"),k(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return v(JSON.stringify(x,null,2));if(x.length===0)return v("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");v(Qt(x.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Go.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,f)=>{let _=await lg(d??".");if(_||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),_.tables.length===0)return v(`${_.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:x}=await re(f.baseUrl),y=new Y({baseUrl:T,token:x}),S;try{S=await ae("planning tables",()=>y.tablesPlan({claimedBy:f.as,tables:_.tables}))}catch(R){oe(R,"extensions:deploy","plan tables"),Ti(R)}v(`claiming as ${g.bold(S.claimedBy)}`);for(let R of S.tables)Si(R,{showClaimants:!0});v(""),v(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Go.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,f)=>{let _=await lg(d??".");if(_||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),_.tables.length===0)return v(`${_.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:x}=await re(f.baseUrl),y=new Y({baseUrl:T,token:x}),S;try{S=await ae("applying tables",()=>y.tablesApply({claimedBy:f.as,tables:_.tables}))}catch(R){oe(R,"extensions:deploy","apply tables"),Ti(R)}for(let R of S.tables)Si(R,{showClaimants:!0});v(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),Go.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,f)=>[...f??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let _=f.field.map(R=>{let[N,L,D]=R.split(":");return(!N||!L)&&k(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),D!==void 0&&D!=="required"&&k(`--field "${R}": the third part may only be "required".`),{name:N,type:L,...D==="required"?{required:!0}:{}}}),{baseUrl:T,token:x}=await re(f.baseUrl),y=new Y({baseUrl:T,token:x}),S;try{S=await ae(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:f.name??d,fields:_,...f.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){oe(R,"extensions:deploy","create a table"),Ti(R)}for(let R of S.tables)Si(R);v(""),v(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Go.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{f.confirm!==d&&k(`drop refused: --confirm "${f.confirm}" does not match "${d}".`);let{baseUrl:_,token:T}=await re(f.baseUrl),x=new Y({baseUrl:_,token:T}),y;try{y=await ae(`dropping cr_${d}`,()=>x.tablesDrop(d,f.confirm))}catch(S){oe(S,"extensions:deploy","drop a table"),k(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!y.removed)return v(`no table named "${d}" on this instance \u2014 nothing dropped.`);v(`dropped ${y.table} and every row in it.`)});let ml=e.command("sandbox").description("Ephemeral local authoring sandboxes.");ml.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let f=og(),_;try{_=await sw(f,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof ys&&k(T.message),k(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}v(`sandbox ${_.name} ready.`),v(` source: ${_.fromTenant} (sampled ${Math.round(_.sampleFraction*100)}%, redacted)`),v(` url: ${_.url}`),v(` expires: ${_.expiresAt}`)}),ml.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let f=og();await Uu(f).catch(()=>[]);let _;try{_=await iw(f,d)}catch(T){k(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}_||k(`no sandbox named '${d}'.`),v(`destroyed sandbox ${_.name} (dropped ${_.database}).`)}),ml.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=og(),f=await Uu(d).catch(()=>[]),_=await ba(),{active:T}=Mu(_);if(T.length===0)v("no active sandboxes.");else{for(let x of T)v(` ${x.name} from=${x.fromTenant} expires=${x.expiresAt} ${x.url}`);v(`
|
|
3778
3778
|
${T.length} active sandbox(es).`)}f.length>0&&v(`(reaped ${f.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",ca).action(async d=>{let{baseUrl:f,token:_}=await re(d.baseUrl),T=new Y({baseUrl:f,token:_}),x;try{x=await ae("exporting instance config",()=>T.configExport())}catch(R){R instanceof ce&&(R.status===401||R.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${R instanceof Error?R.message:String(R)}`)}let y=typeof x.serialized=="string"?x.serialized:`${JSON.stringify(x.manifest??x,null,2)}
|
|
3779
3779
|
`,S=ge(process.cwd(),d.out,ds);await be.mkdir(Lr(S),{recursive:!0}),await be.writeFile(S,y,"utf8"),v(`wrote ${d.out}/${ds} (${y.split(`
|
|
3780
|
-
`).length} lines).`)});let ug=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),uT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],dg=()=>process.env.TURBOBASE_HOME?.trim()||Ot(VM(),".turbobase"),dT=()=>"1.
|
|
3780
|
+
`).length} lines).`)});let ug=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),uT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],dg=()=>process.env.TURBOBASE_HOME?.trim()||Ot(VM(),".turbobase"),dT=()=>"1.27.0",Ei=async()=>Promise.all(uT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));ug.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ei();for(let f of d)v(`${f.present?Ce.success("installed"):Ce.warn("missing")} ${g.bold(f.name)} \u2014 ${f.needs}`);d.some(f=>!f.present)&&v(`
|
|
3781
3781
|
run \`${hs} ext extras install\` to fetch them into ${dg()}.`)}),ug.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Ei();if(d.every(N=>N.present)){v(Ce.success("extras already installed \u2014 nothing to do."));return}let f=dg();await be.mkdir(f,{recursive:!0});let _=d.filter(N=>!N.present).map(N=>N.name),T=Cu(process.platform,process.arch),x=async(N,L)=>{let{code:D,stderr:H}=await ki("npm",["install","--prefix",f,"--no-audit","--no-fund",...N]);D!==0&&k(`extras install failed while installing ${L} (npm exited ${D}).
|
|
3782
3782
|
${H.trim()}
|
|
3783
3783
|
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=_.filter(N=>N!=="isolated-vm");if(y.length>0){let N=y.map(L=>`${L}@${Iu[L]??"latest"}`);v(`installing ${N.join(", ")} \u2192 ${f}/node_modules \u2026`),await x(N,y.join(", "))}if(_.includes("isolated-vm")){let N=`isolated-vm@${Iu["isolated-vm"]}`;if(v(`installing ${N} \u2192 ${f}/node_modules \u2026`),await x(["--ignore-scripts",N],"isolated-vm"),Xb.includes(T)){let D=`${Ou}@${dT()}`;v(`fetching ${D} (no upstream binary for ${T}) \u2026`);let{code:H}=await ki("npm",["install","--prefix",f,"--no-audit","--no-fund","--ignore-scripts",D]);H!==0&&v(Ce.warn(`could not fetch ${D} \u2014 falling back to a source build.`))}let L=await Qb({home:f});L.length>0&&v(` ${Ce.success("prebuilt")} ${L.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await Ei(),R=S.filter(N=>!N.present).map(N=>N.name);if(R.includes("isolated-vm")){v(Ce.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${Nu()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:N}=await ki("npm",["rebuild","--prefix",f,"isolated-vm"]);N===0&&(S=await Ei(),R=S.filter(L=>!L.present).map(L=>L.name))}R.length>0&&k(`npm succeeded but ${R.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${Nu()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),v(Ce.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Qn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Qn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let f=d.target==="approved"?"approved":d.target==="auto"?"auto":null;f||k(`--target must be 'auto' or 'approved' (got '${d.target}').`);let _=await iU(ge(process.cwd(),d.project??".")),T=Object.keys(_).length;!d.solution&&T===0&&k("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let y=(d.ref?await sg(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await sg(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await sg(["remote","get-url","origin"]),R=d.gitRef??process.env.GITHUB_REF??null,N=d.prUrl??process.env.PR_URL??null,{baseUrl:L,token:D}=await re(d.baseUrl),H=new Y({baseUrl:L,token:D}),j;try{j=await H.releaseDeploy({solutionId:d.solution??null,target:f,approvedBy:d.approvedBy??null,files:T>0?_:null,gitRepo:S,gitRef:R,gitSha:y,prUrl:N})}catch(ee){oe(ee,"releases:write","release deploy"),ee instanceof ce&&ee.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${ee instanceof Error?ee.message:String(ee)}`)}v(`release ${j.releaseId} enqueued \u2192 taskId=${j.taskId} (target=${f}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await _u(()=>H.releaseStatus(j.releaseId),`release ${j.releaseId}`,d.intervalMs)}),Qn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:_,token:T}=await re(f.baseUrl),x=new Y({baseUrl:_,token:T}),y;try{y=await x.releaseFiles(d)}catch(N){N instanceof ce&&N.status===404&&k(`release ${d} not found.`),N instanceof ce&&N.status===409&&k(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),oe(N,"releases:write","pull a release"),k(`release pull failed: ${N instanceof Error?N.message:String(N)}`)}let S=ge(process.cwd(),f.dir),R=0;for(let[N,L]of[["owned",y.owned],["context",y.context]])for(let[D,H]of Object.entries(L)){let j=Ot(S,N,D);await be.mkdir(Lr(j),{recursive:!0}),await be.writeFile(j,H,"utf8"),R++}await be.writeFile(Ot(S,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),v(`pulled release ${y.releaseId} (${y.status}) \u2192 ${S}
|
package/dist/turbobase.js
CHANGED
|
@@ -2001,7 +2001,7 @@ export { Label };
|
|
|
2001
2001
|
`}var cP,Ri,Xy=j(()=>{Wn();cP=10*1024*1024,Ri=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??cP}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
2002
2002
|
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),dP(n)}clear(){this._buffer=void 0}}});import Qy from"node:process";var Ti,eb=j(()=>{Xy();Ti=class{constructor(e=Qy.stdin,n=Qy.stdout,r){this._stdin=e,this._stdout=n,this._started=!1,this._ondata=s=>{try{this._readBuffer.append(s),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=s=>{this.onerror?.(s)},this._readBuffer=new Ri({maxBufferSize:r?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let r=Zy(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var tb,nb=j(()=>{tb=[]});var ub={};Hd(ub,{AUTHORING_MCP_SERVER_NAME:()=>ib,AUTHORING_MCP_SERVER_VERSION:()=>ab,AUTHORING_RESOURCES:()=>yP,AUTHORING_TOOLS:()=>gP,AUTHORING_TOOLS_PUBLIC:()=>db,buildAuthoringMcpServer:()=>cb,resolveSamplesDir:()=>lb,runAuthoringMcpServer:()=>bP});import{promises as uP}from"node:fs";import{isAbsolute as pP,resolve as Ei,sep as hP}from"node:path";import{z as q}from"zod";function ob(){return sb??=import("../mcp/grounding.js").then(e=>e,()=>null),sb}function lb(t,e){if(e===void 0)return Ei(process.cwd(),t??"samples");let n=Ei(e);if(t===void 0)return n;if(pP(t))return null;let r=Ei(n,t);return r===n||r.startsWith(n+hP)?r:null}function Se(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function mP(t,e={}){let n=e.fetchImpl??fetch;try{let r=await n(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return r.ok?((await r.json()).extensions??[]).map(o=>o.hookId).filter(o=>typeof o=="string"):null}catch{return null}}async function cb(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let b=await pt(t.baseUrl);if(!b)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:b.baseUrl,token:b.token}}let n=t.grounding??{},r=await ob(),s=null;if(r)try{let b=await e();s={surface:"mcp-authoring",baseUrl:b.baseUrl,token:b.token}}catch{s=null}let o=r&&s?await r.loadActiveSources(s,n):[],i={...n,loadActiveSourcesImpl:async()=>o},a=[],l=[];if(r&&s){try{a=await r.listMcpPromptSkills(s,i)}catch{a=[]}try{l=(await r.listRecipesForSurface(s,i)).map(b=>({id:b.id,record_type:b.record_type,intent:b.intent}))}catch{l=[]}}let u=s?await mP(s,n):null,p=new $i({name:ib,version:ab},r?{instructions:r.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??s?.baseUrl??t.baseUrl??"this instance",sources:o,recipeIntents:l,promptNames:a.map(b=>b.id),deployedExtensions:u,docsToken:n.docsToken??r.docsPublicToken()})}:void 0);if(r&&s){let b=s;for(let S of a)p.registerPrompt(S.id,{title:S.name,description:S.description},async()=>{let R=await r.getMcpPromptSkill(b,S.id,n);if(!R)throw new Error(`unknown prompt: ${S.id}`);return{description:R.description,messages:[{role:"user",content:{type:"text",text:(R.prompts??[]).join(`
|
|
2003
2003
|
|
|
2004
|
-
`)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:b,token:S}=await e(),R=await fetch(`${b}/v1/catalog/records`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog fetch failed: ${R.status}`);return Se(await R.json())}),p.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:q.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:q.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:b,source:S})=>{let{baseUrl:R,token:T}=await e(),P=S?`?source=${encodeURIComponent(S)}`:"",N=await fetch(`${R}/v1/catalog/records/${encodeURIComponent(b)}${P}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(N.status===404)throw new Error(`unknown record type "${b}" \u2014 list them with catalog_get.`);if(!N.ok)throw new Error(`record anatomy fetch failed: ${N.status}`);return Se(await N.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:q.array(q.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:q.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:b,source:S})=>{let{baseUrl:R,token:T}=await e(),P=new URLSearchParams({types:b.join(",")});S&&P.set("source",S);let N=await fetch(`${R}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(N.status===404)throw new Error(`none of those record types resolved: ${b.join(", ")} \u2014 list them with catalog_get.`);if(!N.ok)throw new Error(`common columns fetch failed: ${N.status}`);return Se(await N.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:b,token:S}=await e(),R=await fetch(`${b}/v1/catalog/census`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog census failed: ${R.status}`);return Se(await R.json())}),p.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:q.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:q.enum(rb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:q.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:b,kind:S,limit:R})=>{let{baseUrl:T,token:P}=await e(),N=new URLSearchParams({q:b});S&&N.set("kind",S),R!==void 0&&N.set("limit",String(R));let D=await fetch(`${T}/v1/catalog/objects?${N}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return Se(await D.json())}),p.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:q.enum(rb),externalId:q.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:b,externalId:S})=>{let{baseUrl:R,token:T}=await e(),P=await fetch(`${R}/v1/catalog/objects/${encodeURIComponent(b)}/${encodeURIComponent(S)}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${b}:${S} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return Se(await P.json())}),p.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:q.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:q.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:b,limit:S})=>{let{baseUrl:R,token:T}=await e(),P=new URLSearchParams({q:b});S!==void 0&&P.set("limit",String(S));let N=await fetch(`${R}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(!N.ok)throw new Error(`kb search failed: ${N.status}`);return Se(await N.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:q.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:b})=>{let{baseUrl:S,token:R}=await e(),T=await fetch(`${S}/v1/kb/document/${encodeURIComponent(b)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!T.ok&&T.status!==404)throw new Error(`kb document fetch failed: ${T.status}`);return Se(await T.json())}),p.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:q.boolean().optional()}},async({recordsOnly:b})=>{let{baseUrl:S,token:R}=await e();return{content:[{type:"text",text:await pn({baseUrl:S,token:R,recordsOnly:b})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:q.string(),event:q.string().optional(),template:q.enum(["require-field","enforce-format","blank"]).optional(),field:q.string().optional(),regex:q.string().optional(),source:q.string().optional(),id:q.string().optional()}},async b=>{let S=$t("hook",{recordType:b.recordType,event:b.event,template:b.template,field:b.field,regex:b.regex,source:b.source,id:b.id});return Se({path:S.relativePath,content:S.content})}),p.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:q.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:q.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:q.string().optional().describe("Target record type (defaults to the trigger record type)."),event:q.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:q.string().optional()}},async b=>{let S=$t("conduit",{recordType:b.recordType,source:b.source,to:b.to,toRecordType:b.toRecordType,event:b.event,id:b.id});return Se({path:S.relativePath,content:S.content})}),p.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:q.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:q.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:q.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:q.string().optional()}},async b=>{let S=$t("process",{recordType:b.recordType,then:b.then,onFailure:b.onFailure,id:b.id});return Se({path:S.relativePath,content:S.content})}),p.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:q.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:q.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:q.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:q.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:q.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:q.array(q.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async b=>{let{baseUrl:S,token:R}=await e(),T=new B({baseUrl:S,token:R});return Se(await T.authorConduit({intent:b.intent,from:{source:b.fromSource,recordType:b.fromRecordType},to:{source:b.toSource,recordType:b.toRecordType},...b.intentId?{intentId:b.intentId}:{},...b.columns?.length?{columns:b.columns}:{}}))}),p.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:q.string().describe("The extension TS source."),samplesDir:q.string().optional().describe('Samples directory (default "samples").')}},async({source:b,samplesDir:S})=>{let R=lb(S,t.samplesRoot);if(R===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:fP})}],isError:!0};let T;try{T=await br(R)}catch(D){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw D}let P=await qs(b,T.map(D=>D.fixture)),N=P.filter(D=>!D.pass).length;return Se({total:P.length,passed:P.length-N,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:q.string(),recordType:q.string(),event:q.string(),source:q.string().describe('Adapter id or "standalone".'),sourceCode:q.string().describe("The verbatim extension TS."),extensionKind:q.string().optional()}},async b=>{let{baseUrl:S,token:R}=await e(),P=await new B({baseUrl:S,token:R}).deploy({id:b.id,recordType:b.recordType,event:b.event,source:b.source,sourceCode:b.sourceCode,extensionKind:b.extensionKind});return Se(P)}),p.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:q.string(),limit:q.number().int().positive().optional()}},async({id:b,limit:S})=>{let{baseUrl:R,token:T}=await e(),P=new B({baseUrl:R,token:T});return Se({id:b,logs:await P.logs(b,S)})}),p.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:b,token:S}=await e(),R=new B({baseUrl:b,token:S});return Se(await R.appsList())}),p.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:q.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:q.string().optional().describe("Display name (defaults to the slug)."),description:q.string().optional().describe("Short description.")}},async({slug:b,name:S,description:R})=>{let{baseUrl:T,token:P}=await e(),N=new B({baseUrl:T,token:P});return Se(await N.appsCreate({slug:b,name:S,description:R}))}),p.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:q.string().describe("App slug or id.")}},async({app:b})=>{let{baseUrl:S,token:R}=await e(),T=new B({baseUrl:S,token:R});return Se(await T.appsPull(b))}),p.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:q.string().describe("App slug or id."),files:q.record(q.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:q.string().optional().describe("Short note stored with the revision.")}},async({app:b,files:S,note:R})=>{let{baseUrl:T,token:P}=await e(),N=new B({baseUrl:T,token:P});return Se(await N.appsPush(b,S,{note:R}))});let g=q.object({name:q.string().describe("Field name (lowercase identifier)."),type:q.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:q.boolean().optional()}),$=q.object({slug:q.string().describe("Table slug; the physical table is cr_<slug>."),displayName:q.string().optional(),fields:q.array(g).describe("At least one field."),rowLevelOwner:q.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:b,token:S}=await e(),R=new B({baseUrl:b,token:S});return Se(await R.tablesList())}),p.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:q.array($),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:S})=>{let{baseUrl:R,token:T}=await e(),P=new B({baseUrl:R,token:T});return Se(await P.tablesPlan({tables:b,claimedBy:S}))}),p.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:q.array($),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:S})=>{let{baseUrl:R,token:T}=await e(),P=new B({baseUrl:R,token:T});return Se(await P.tablesApply({tables:b,claimedBy:S}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async b=>{let{baseUrl:S,token:R}=await e(),P=await(await fetch(`${S}/v1/catalog/records`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}})).text();return{contents:[{uri:b.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async b=>{let{baseUrl:S,token:R}=await e(),T=await pn({baseUrl:S,token:R});return{contents:[{uri:b.href,mimeType:"text/plain",text:T}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async b=>{let S=Ei(process.cwd(),"samples"),R=[];try{R=(await uP.readdir(S)).filter(P=>P.endsWith(".json"))}catch{R=[]}let T=await br(S);return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({files:R,samples:T.map(P=>P.fixture)},null,2)}]}}),p.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async b=>{let S=await ob(),R=[];if(S){let{baseUrl:T,token:P}=await e();R=await S.listRecipesForSurface({surface:"mcp-authoring",baseUrl:T,token:P},n)}return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({recipes:R})}]}}),p}async function bP(t={}){let e=await cb(t),n=new Ti;await e.connect(n)}var rb,sb,ib,ab,fP,db,gP,yP,pb=j(()=>{Yy();eb();Wi();mr();xt();oa();Ks();nb();rb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];ib="turbobase-authoring",ab="0.1.0";fP="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";db=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],gP=[...db,...tb],yP=["catalog:///","types://all","samples:///","recipes:///"]});Wi();mr();xt();oa();import{spawn as Md}from"node:child_process";import{promises as oe}from"node:fs";import{homedir as wP}from"node:os";import{basename as mb,dirname as Mt,join as Qe,relative as Ai,resolve as se,sep as Ud}from"node:path";import{Command as vP}from"commander";Ms();import{promises as Tu}from"node:fs";function Ru(t,e){return e===t?"same-type-merge":"different-type-mint"}var Eu=4;function ia(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Cn(t,"id"),n=Cn(t,"on"),r=Cn(t,"source"),s=Cn(t,"recordType"),o=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let u=Cn(l[1]??"","source"),p=Cn(l[1]??"","recordType");u&&p&&o.push({source:u,recordType:p})}let i=o[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!r||!s||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:n,fromSource:r,fromRecordType:s,toSource:i.source,toRecordType:i.recordType,targets:o,cycleBudget:a?Number(a[1]):Eu}}function Cn(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function yw(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function Pu(t,e,n="fixture",r={}){let s=e.name??n,o=[],i;try{i=ia(t)}catch(u){return{fixtureName:s,conduit:ww(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:u instanceof Error?u.message:String(u)}}let a=yw(e),l=Object.entries(e.atlasLinks??{}).map(([u,p])=>({key:u,resolved:p}));try{let u=await Us(t,{resolveDir:r.resolveDir}),g=!!(await yr(u,a,{member:"when",timeoutMs:Ds})).whenResult;o.push({name:"from.when",status:g?"passed":"failed",detail:g?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let $=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${$} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),o.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),o.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!g)return{fixtureName:s,conduit:i,guards:o,whenPassed:g,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[]};let b=[],S=[],R=[];for(let P=0;P<i.targets.length;P+=1){let N=i.targets[P],D=await yr(u,{...a,materialized:R.map(zt=>({...zt}))},{member:"transform",stepIndex:P,timeoutMs:Ds});b.push(...D.effects.logs);let J=D.effects.result;if(!J||typeof J!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${P+1})`:""} returned no result (expected { patch, createdFrom? })`);let K=J,Ae=Ru(i.fromRecordType,N.recordType),{wouldWriteBindings:Le,masterAction:qt}=bw(i,N,Ae,e);S.push({to:N,transformResult:K,applyBranch:Ae,wouldWriteBindings:Le,masterAction:qt}),R.push({source:N.source,recordType:N.recordType,masterTable:`<${N.recordType} master, dry-run>`,masterRowId:`<dry-run target ${P+1}>`,externalId:null})}let T=S[0];return{fixtureName:s,conduit:i,guards:o,whenPassed:g,atlasResolutions:l,transformResult:T.transformResult,applyBranch:T.applyBranch,wouldWriteBindings:T.wouldWriteBindings,masterAction:T.masterAction,targets:S,logs:b}}catch(u){return{fixtureName:s,conduit:i,guards:o,whenPassed:!1,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[],error:u instanceof Error?u.message:String(u)}}}function bw(t,e,n,r){return n==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:r.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function ww(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Eu}}async function Au(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function Iu(t){let e=await Tu.readFile(t,"utf8");return JSON.parse(e)}function Cu(t){return Tu.readFile(t,"utf8")}function Ou(t,e){let n=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let r=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${n.id}]: WHEN-FAILED (conduit short-circuited)`;if(r){let a=t.targets.reduce((l,u)=>l+u.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let s=[];s.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),s.push(`conduit: ${n.id}`);let o=(n.targets.length>0?n.targets:[{source:n.toSource,recordType:n.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");s.push(`route: ${n.fromSource}.${n.fromRecordType} \u2192 ${o}${n.on?` on=${n.on}`:""}`),s.push(""),s.push("guards (dispatch order):");for(let a of t.guards){let l=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";s.push(` ${l} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(s.push(""),s.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)s.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return s.push(""),s.push("transform: SKIPPED (from.when gate did not fire)."),s.join(`
|
|
2004
|
+
`)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:b,token:S}=await e(),R=await fetch(`${b}/v1/catalog/records`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog fetch failed: ${R.status}`);return Se(await R.json())}),p.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:q.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:q.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:b,source:S})=>{let{baseUrl:R,token:T}=await e(),P=S?`?source=${encodeURIComponent(S)}`:"",N=await fetch(`${R}/v1/catalog/records/${encodeURIComponent(b)}${P}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(N.status===404)throw new Error(`unknown record type "${b}" \u2014 list them with catalog_get.`);if(!N.ok)throw new Error(`record anatomy fetch failed: ${N.status}`);return Se(await N.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:q.array(q.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:q.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:b,source:S})=>{let{baseUrl:R,token:T}=await e(),P=new URLSearchParams({types:b.join(",")});S&&P.set("source",S);let N=await fetch(`${R}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(N.status===404)throw new Error(`none of those record types resolved: ${b.join(", ")} \u2014 list them with catalog_get.`);if(!N.ok)throw new Error(`common columns fetch failed: ${N.status}`);return Se(await N.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:b,token:S}=await e(),R=await fetch(`${b}/v1/catalog/census`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog census failed: ${R.status}`);return Se(await R.json())}),p.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:q.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:q.enum(rb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:q.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:b,kind:S,limit:R})=>{let{baseUrl:T,token:P}=await e(),N=new URLSearchParams({q:b});S&&N.set("kind",S),R!==void 0&&N.set("limit",String(R));let D=await fetch(`${T}/v1/catalog/objects?${N}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return Se(await D.json())}),p.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:q.enum(rb),externalId:q.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:b,externalId:S})=>{let{baseUrl:R,token:T}=await e(),P=await fetch(`${R}/v1/catalog/objects/${encodeURIComponent(b)}/${encodeURIComponent(S)}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${b}:${S} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return Se(await P.json())}),p.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:q.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:q.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:b,limit:S})=>{let{baseUrl:R,token:T}=await e(),P=new URLSearchParams({q:b});S!==void 0&&P.set("limit",String(S));let N=await fetch(`${R}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(!N.ok)throw new Error(`kb search failed: ${N.status}`);return Se(await N.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:q.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:b})=>{let{baseUrl:S,token:R}=await e(),T=await fetch(`${S}/v1/kb/document/${encodeURIComponent(b)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!T.ok&&T.status!==404)throw new Error(`kb document fetch failed: ${T.status}`);return Se(await T.json())}),p.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:q.boolean().optional()}},async({recordsOnly:b})=>{let{baseUrl:S,token:R}=await e();return{content:[{type:"text",text:await pn({baseUrl:S,token:R,recordsOnly:b})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:q.string(),event:q.string().optional(),template:q.enum(["require-field","enforce-format","blank"]).optional(),field:q.string().optional(),regex:q.string().optional(),source:q.string().optional(),id:q.string().optional()}},async b=>{let S=$t("hook",{recordType:b.recordType,event:b.event,template:b.template,field:b.field,regex:b.regex,source:b.source,id:b.id});return Se({path:S.relativePath,content:S.content})}),p.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:q.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:q.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:q.string().optional().describe("Target record type (defaults to the trigger record type)."),event:q.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:q.string().optional()}},async b=>{let S=$t("conduit",{recordType:b.recordType,source:b.source,to:b.to,toRecordType:b.toRecordType,event:b.event,id:b.id});return Se({path:S.relativePath,content:S.content})}),p.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:q.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:q.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:q.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:q.string().optional()}},async b=>{let S=$t("process",{recordType:b.recordType,then:b.then,onFailure:b.onFailure,id:b.id});return Se({path:S.relativePath,content:S.content})}),p.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:q.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:q.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:q.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:q.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:q.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:q.array(q.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async b=>{let{baseUrl:S,token:R}=await e(),T=new B({baseUrl:S,token:R});return Se(await T.authorConduit({intent:b.intent,from:{source:b.fromSource,recordType:b.fromRecordType},to:{source:b.toSource,recordType:b.toRecordType},...b.intentId?{intentId:b.intentId}:{},...b.columns?.length?{columns:b.columns}:{}}))}),p.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:q.string().describe("The extension TS source."),samplesDir:q.string().optional().describe('Samples directory (default "samples").')}},async({source:b,samplesDir:S})=>{let R=lb(S,t.samplesRoot);if(R===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:fP})}],isError:!0};let T;try{T=await br(R)}catch(D){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw D}let P=await qs(b,T.map(D=>D.fixture)),N=P.filter(D=>!D.pass).length;return Se({total:P.length,passed:P.length-N,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:q.string(),recordType:q.string(),event:q.string(),source:q.string().describe('Adapter id or "standalone".'),sourceCode:q.string().describe("The verbatim extension TS."),extensionKind:q.string().optional()}},async b=>{let{baseUrl:S,token:R}=await e(),P=await new B({baseUrl:S,token:R}).deploy({id:b.id,recordType:b.recordType,event:b.event,source:b.source,sourceCode:b.sourceCode,extensionKind:b.extensionKind});return Se(P)}),p.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:q.string(),limit:q.number().int().positive().optional()}},async({id:b,limit:S})=>{let{baseUrl:R,token:T}=await e(),P=new B({baseUrl:R,token:T});return Se({id:b,logs:await P.logs(b,S)})}),p.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:b,token:S}=await e(),R=new B({baseUrl:b,token:S});return Se(await R.appsList())}),p.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:q.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:q.string().optional().describe("Display name (defaults to the slug)."),description:q.string().optional().describe("Short description.")}},async({slug:b,name:S,description:R})=>{let{baseUrl:T,token:P}=await e(),N=new B({baseUrl:T,token:P});return Se(await N.appsCreate({slug:b,name:S,description:R}))}),p.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:q.string().describe("App slug or id.")}},async({app:b})=>{let{baseUrl:S,token:R}=await e(),T=new B({baseUrl:S,token:R});return Se(await T.appsPull(b))}),p.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:q.string().describe("App slug or id."),files:q.record(q.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:q.string().optional().describe("Short note stored with the revision.")}},async({app:b,files:S,note:R})=>{let{baseUrl:T,token:P}=await e(),N=new B({baseUrl:T,token:P});return Se(await N.appsPush(b,S,{note:R}))});let g=q.object({name:q.string().describe("Field name (lowercase identifier)."),type:q.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:q.boolean().optional()}),$=q.object({slug:q.string().describe("Table slug; the physical table is cr_<slug>."),displayName:q.string().optional(),fields:q.array(g).describe("At least one field."),rowLevelOwner:q.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:b,token:S}=await e(),R=new B({baseUrl:b,token:S});return Se(await R.tablesList())}),p.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:q.array($),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:S})=>{let{baseUrl:R,token:T}=await e(),P=new B({baseUrl:R,token:T});return Se(await P.tablesPlan({tables:b,claimedBy:S}))}),p.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:q.array($),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:S})=>{let{baseUrl:R,token:T}=await e(),P=new B({baseUrl:R,token:T});return Se(await P.tablesApply({tables:b,claimedBy:S}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async b=>{let{baseUrl:S,token:R}=await e(),P=await(await fetch(`${S}/v1/catalog/records`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}})).text();return{contents:[{uri:b.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async b=>{let{baseUrl:S,token:R}=await e(),T=await pn({baseUrl:S,token:R});return{contents:[{uri:b.href,mimeType:"text/plain",text:T}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async b=>{let S=Ei(process.cwd(),"samples"),R=[];try{R=(await uP.readdir(S)).filter(P=>P.endsWith(".json"))}catch{R=[]}let T=await br(S);return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({files:R,samples:T.map(P=>P.fixture)},null,2)}]}}),p.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async b=>{let S=await ob(),R=[];if(S){let{baseUrl:T,token:P}=await e();R=await S.listRecipesForSurface({surface:"mcp-authoring",baseUrl:T,token:P},n)}return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({recipes:R})}]}}),p}async function bP(t={}){let e=await cb(t),n=new Ti;await e.connect(n)}var rb,sb,ib,ab,fP,db,gP,yP,pb=j(()=>{Yy();eb();Wi();mr();xt();oa();Ks();nb();rb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];ib="turbobase-authoring",ab="0.1.0";fP="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";db=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],gP=[...db,...tb],yP=["catalog:///","types://all","samples:///","recipes:///"]});Wi();mr();xt();oa();import{spawn as Md}from"node:child_process";import{promises as oe}from"node:fs";import{homedir as wP}from"node:os";import{basename as mb,dirname as Mt,join as Qe,relative as Ai,resolve as se,sep as Ud}from"node:path";import{Command as vP}from"commander";Ms();import{promises as Tu}from"node:fs";function Ru(t,e){return e===t?"same-type-merge":"different-type-mint"}var Eu=4;function ia(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Cn(t,"id"),n=Cn(t,"on"),r=Cn(t,"source"),s=Cn(t,"recordType"),o=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let u=Cn(l[1]??"","source"),p=Cn(l[1]??"","recordType");u&&p&&o.push({source:u,recordType:p})}let i=o[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!r||!s||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:n,fromSource:r,fromRecordType:s,toSource:i.source,toRecordType:i.recordType,targets:o,cycleBudget:a?Number(a[1]):Eu}}function Cn(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function yw(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function Pu(t,e,n="fixture",r={}){let s=e.name??n,o=[],i;try{i=ia(t)}catch(u){return{fixtureName:s,conduit:ww(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:u instanceof Error?u.message:String(u)}}let a=yw(e),l=Object.entries(e.atlasLinks??{}).map(([u,p])=>({key:u,resolved:p}));try{let u=await Us(t,{resolveDir:r.resolveDir}),g=!!(await yr(u,a,{member:"when",timeoutMs:Ds})).whenResult;o.push({name:"from.when",status:g?"passed":"failed",detail:g?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let $=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${$} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),o.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),o.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!g)return{fixtureName:s,conduit:i,guards:o,whenPassed:g,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[]};let b=[],S=[],R=[];for(let P=0;P<i.targets.length;P+=1){let N=i.targets[P],D=await yr(u,{...a,materialized:R.map(zt=>({...zt}))},{member:"transform",stepIndex:P,timeoutMs:Ds});b.push(...D.effects.logs);let J=D.effects.result;if(!J||typeof J!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${P+1})`:""} returned no result (expected { patch, createdFrom? })`);let K=J,Ae=Ru(i.fromRecordType,N.recordType),{wouldWriteBindings:Le,masterAction:qt}=bw(i,N,Ae,e);S.push({to:N,transformResult:K,applyBranch:Ae,wouldWriteBindings:Le,masterAction:qt}),R.push({source:N.source,recordType:N.recordType,masterTable:`<${N.recordType} master, dry-run>`,masterRowId:`<dry-run target ${P+1}>`,externalId:null})}let T=S[0];return{fixtureName:s,conduit:i,guards:o,whenPassed:g,atlasResolutions:l,transformResult:T.transformResult,applyBranch:T.applyBranch,wouldWriteBindings:T.wouldWriteBindings,masterAction:T.masterAction,targets:S,logs:b}}catch(u){return{fixtureName:s,conduit:i,guards:o,whenPassed:!1,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[],error:u instanceof Error?u.message:String(u)}}}function bw(t,e,n,r){return n==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function ww(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Eu}}async function Au(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function Iu(t){let e=await Tu.readFile(t,"utf8");return JSON.parse(e)}function Cu(t){return Tu.readFile(t,"utf8")}function Ou(t,e){let n=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let r=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${n.id}]: WHEN-FAILED (conduit short-circuited)`;if(r){let a=t.targets.reduce((l,u)=>l+u.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let s=[];s.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),s.push(`conduit: ${n.id}`);let o=(n.targets.length>0?n.targets:[{source:n.toSource,recordType:n.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");s.push(`route: ${n.fromSource}.${n.fromRecordType} \u2192 ${o}${n.on?` on=${n.on}`:""}`),s.push(""),s.push("guards (dispatch order):");for(let a of t.guards){let l=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";s.push(` ${l} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(s.push(""),s.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)s.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return s.push(""),s.push("transform: SKIPPED (from.when gate did not fire)."),s.join(`
|
|
2005
2005
|
`);let i=t.targets.length>0?t.targets:[{to:{source:n.toSource,recordType:n.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(i.forEach((a,l)=>{let u=r?` (target ${l+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";s.push(""),s.push(`transform${u} \u2192 patch:`),s.push(vw(JSON.stringify(a.transformResult.patch??{},null,2)," ")),a.transformResult.createdFrom&&s.push(` createdFrom: ${JSON.stringify(a.transformResult.createdFrom)}`),s.push(""),s.push(`apply-branch${u}: ${a.applyBranch}`),s.push(` ${a.masterAction}`),s.push(""),s.push(`bindings that WOULD be written (txn_source_link)${u}:`);for(let p of a.wouldWriteBindings)s.push(` ${p.source} role=${p.role} external_id=${p.externalId??"null"} \u2014 ${p.why}`)}),t.logs.length>0){s.push(""),s.push("conduit logs:");for(let a of t.logs)s.push(` [${a.level}] ${a.message}${a.meta?` ${JSON.stringify(a.meta)}`:""}`)}return s.join(`
|
|
2006
2006
|
`)}function vw(t,e){return t.split(`
|
|
2007
2007
|
`).map(n=>e+n).join(`
|
|
@@ -3700,7 +3700,7 @@ ${s.map(qv).join(`
|
|
|
3700
3700
|
`))}async function Vp(t,e,n=Mn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let s=await qn(e,n);if(!await to(`Publish ${r.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await Z("publishing",()=>s.skillsPublish(r))}catch(a){W(a,"skills:publish","publish a skill"),k(`publish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(f.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function Gp(t,e,n=Mn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let s=await qn(e,n);if(!await to(`Move ${r.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await Z("unpublishing",()=>s.skillsUnpublish(r))}catch(a){W(a,"skills:publish","unpublish a skill"),k(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(f.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Wp(t,e,n=Mn){let r=Number(t);(!Number.isInteger(r)||r<1)&&k(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let s=await qn(e,n);if(await to(`Roll the skills back to release v${r}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await Z("rolling back",()=>s.skillsRollback(r));y(f.green(`rolled back to v${i.version.version_no}.`))}catch(i){W(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Jp(t,e=Mn){let n=await qn(t,e),r;try{r=await Z("reading the releases",()=>n.skillsReleases())}catch(s){W(s,"skills:publish","read the skills releases"),k(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(r.items.length===0){L("no releases yet.");return}for(let s of r.items){let o=s.is_current?f.green("*"):" ",i=s.release_note?` \u2014 ${s.release_note}`:"";y(`${o} v${s.version_no} ${s.skill_count} skill(s) ${f.dim(s.published_at)}${s.published_by?f.dim(` by ${s.published_by}`):""}${f.dim(i)}`)}}async function Yp(t,e,n=Mn){let r=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];r.length===0&&k("name at least one skill to delete. `turbobase skills list` shows the slugs.");let s=await qn(e,n);if(!await to(r.length===1?`Delete the skill '${r[0]}'?`:`Delete ${r.length} skills?
|
|
3701
3701
|
${r.join(`
|
|
3702
3702
|
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let u of r)try{i.push(await Z(`deleting ${u}`,()=>s.skillsDelete(u)))}catch(p){if(p instanceof X&&p.status===404){a.push(u);continue}i.length>0&&L(f.dim(`deleted before the error: ${i.map(g=>g.slug).join(", ")}`)),W(p,"skills:publish","delete a skill"),k(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&y(f.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&L(f.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(f.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Zp}from"node:fs";import{join as mk,relative as gk,resolve as yk,sep as bk}from"node:path";var wk=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),vk=new Set([".mcp.json",".env"]);function kk(t){return vk.has(t)||t.startsWith(".env.")&&t!==".env.example"}function Sk(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function _k(t){return t.includes(0)}async function Xp(t){let e=yk(t),n={},r=[],s=[],o=[];async function i(a){let l=await Zp.readdir(a,{withFileTypes:!0});for(let u of l){let p=mk(a,u.name);if(wk.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let g=gk(e,p).split(bk).join("/");if(kk(u.name)){s.push(g);continue}let $=await Zp.readFile(p);if(!Sk($)){r.push(g);continue}_k($)&&o.push(g),n[g]=$.toString("utf8")}}return await i(e),{files:n,skipped:r,secrets:s,unstorable:o}}import{randomBytes as xk}from"node:crypto";var $k="/_tb/app-assets",Rk=16,Tk=/^[0-9a-f]{32}$/;function Qp(){return xk(Rk).toString("hex")}function Ek(t){return Tk.test(t)}function eh(t){if(!Ek(t))throw new Error(`not a build id: ${t}`);return`${$k}/${t}/`}var th=7;Ra();var Ta=50*1024*1024;import no from"node:fs/promises";import Rr from"node:path";var Ea={esbuild:"0.28.1","isolated-vm":"6.1.2"},Pa="@turbobase/isolated-vm-prebuilds";function Aa(t,e){return`${t}-${e}`}function Ia(t=process.versions){return`abi${t.modules}`}var nh=["darwin-x64","win32-arm64"];async function rh(t){let e=t.platform??process.platform,n=t.arch??process.arch,r=Aa(e,n),s=Rr.join(t.home,"node_modules"),o=Rr.join(s,...Pa.split("/"),"prebuilds",r),i=Rr.join(s,"isolated-vm","prebuilds",r),a;try{a=await no.readdir(o)}catch{return[]}let l=[];await no.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=Rr.join(i,u);try{await no.copyFile(Rr.join(o,u),p,no.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as Pk}from"node:os";import{join as sh}from"node:path";import{promises as Ca}from"node:fs";function ih(){let t=process.env.TURBOBASE_HOME??sh(Pk(),".turbobase");return{dir:t,file:sh(t,"sandboxes.json")}}var Ak={s:1e3,m:6e4,h:36e5,d:864e5};function Ik(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let n=Number(e[1]);if(!Number.isFinite(n)||n<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return n*Ak[e[2]]}function Ck(t,e=Date.now()){return new Date(e+Ik(t)).toISOString()}function Ok(t,e=Date.now()){let n=Date.parse(t);return Number.isNaN(n)?!0:n<=e}function Nk(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let n=Number(e[1]);if(!Number.isFinite(n)||n<0||n>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return n/100}function Lk(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let n=Math.max(1,Math.round(1/e)),r=[];for(let s=0;s<t.length;s+=n)r.push(t[s]);return r}var jk="[REDACTED]",Tr=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Oa=class extends Error{table;column;constructor(e,n,r){super(`Refusing to copy ${e}.${n} into a sandbox: ${r}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=n}};function Dk(t,e,n){let r={};for(let[s,o]of Object.entries(e)){let i=n[s];if(i===void 0)throw new Oa(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?r[s]=o==null?o:jk:r[s]=o}return r}function Uk(t,e,n){return e.map(r=>Dk(t,r,n))}var oh=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),Mk=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function qk(t){let e=t.trim();try{let s=new URL(e);if(s.hostname)return s.hostname.toLowerCase()}catch{}let n=e.replace(/^[a-z]+:\/\//i,""),r=(n.split("/")[0]??n).split("@").pop()??n;return(r.split(":")[0]??r).toLowerCase()}function Na(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let r of Mk)if(e.includes(r))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${r}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let n=qk(t);if(!oh.has(n))throw new Error(`local-only guard: target host '${n}' is not a recognised local Postgres (${[...oh].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function zk(t,e=Bk){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function Bk(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function Fk(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function Hk(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function La(){let{file:t}=ih();try{let e=await Ca.readFile(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function ah(t){let{dir:e,file:n}=ih();await Ca.mkdir(e,{recursive:!0}),await Ca.writeFile(n,`${JSON.stringify(t,null,2)}
|
|
3703
|
-
`,{mode:384})}async function Kk(t){let e=await La();e.push(t),await ah(e)}async function lh(t){let e=await La(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await ah(e),r??null}async function ro(){return La()}function ja(t,e=Date.now()){let n=[],r=[];for(let s of t)Ok(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function ch(t,e){Na(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new Tr(n);let r=Nk(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>zk(u)))(e.fromTenant),i=Fk(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=Lk(u.rows,r),g=Uk(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:Ck(e.ttl,s),sampleFraction:r,url:Hk(o,e.baseUrl)};return await Kk(l),l}async function dh(t,e){Na(t.target());let r=(await ro()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await lh(e),r):null}async function Da(t,e=Date.now()){Na(t.target());let n=await ro(),{expired:r}=ja(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await lh(o.name),s.push(o)}return s}var Er={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},zC=Object.keys(Er).filter(t=>Er[t].mintable);var HC=Er.pat.prefix,Vk=Object.entries(Er).map(([t,e])=>[e.prefix,t]),Gk=/^[A-Za-z0-9_-]{20,}$/;function Wk(t){if(typeof t!="string")return null;for(let[e,n]of Vk)if(t.startsWith(e)&&Gk.test(t.slice(e.length)))return n;return null}function uh(t){return Wk(t)==="pat"}mr();var Jk=8e3,Yk={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function Zk(t){return Yk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Xk(t,e,n=fetch){let r;try{r=await n(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(Jk)})}catch(o){return{state:"unreachable",detail:o instanceof Error?o.message:String(o)}}if(r.status===200||r.status===403)return{state:"accepted"};if(r.status===401){let o=await r.json().catch(()=>null);return{state:"rejected",reason:typeof o?.reason=="string"&&o.reason?o.reason:"unknown"}}return(r.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${r.status} \u2014 this host does not serve the /v1 API`}}function ph(t){return t.state==="accepted"?Pe()?f.green("accepted"):"accepted":t.state==="rejected"?Pe()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Pe()?f.yellow("unreachable"):"unreachable"}async function hh(t={},e=fetch){let n=await Ct(),{file:r}=Is();if(n.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(f.dim(`no sign-ins stored in ${r}.`));return}let s=await pt(),o=await Promise.all(n.map(async i=>({baseUrl:i.baseUrl,active:!!s&&i.baseUrl===s.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await Xk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Pe())y(ht(o.map(i=>[i.active?f.green("*"):" ",f.bold(i.baseUrl),ph(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${ph(i.check)} (updated ${i.updatedAt})`);L(f.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(f.red(`${i.baseUrl}: ${Zk(i.check.reason)}.`)),L(f.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));s||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function kP(t){let e=await Ct();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ze()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Be(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{k("cancelled.")}}async function SP(t,e){let n;try{n=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let r=(n.headers.get("content-type")??"").includes("application/json");return n.status===200||n.status===403?{ok:!0}:n.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${n.status}`}:r?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${n.status}`}}function _P(t){L(""),L("Sharing is ON. Two things reach the Turbobase product team from this instance:"),L(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),L(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),L(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),L(" about OUR platform, with instance name, user names and ids masked before they leave."),L(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),L("")}async function xP(t,e,n){let r=await fu({baseUrl:t,token:e}),s=(await Ct()).length-1;if(y(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),_P(r.baseUrl),!n)return;let o=await SP(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(L(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?L(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function $P(t){let e=await ra(await wr(t),Mt(t)),n=ga(e);if(!n){let r=/\bdefineConduit\s*[<(]/.test(e);k(r?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...n,sourceCode:e}}async function En(t,e,n,r){try{return await oe.access(t),"skipped"}catch{}return await oe.mkdir(Mt(t),{recursive:!0}),await oe.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await oe.chmod(t,r),"wrote"}async function hb(t,e){if(mb(t)!==".gitignore")return En(t,e.content,e.executable,e.mode);let n=await oe.readFile(t,"utf8").catch(()=>null);if(n===null)return En(t,e.content,e.executable,e.mode);let r=np(n);return r===null?"skipped":(await oe.writeFile(t,r,"utf8"),"merged")}function Nd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Pi(t){process.exit(t)}function RP(t){return{name:"turbobase ext test",cases:t.map(n=>{if(n.pass)return{name:n.name,status:"passed"};let r=n.error?"error":n.rejection?.code??"mismatch",s=n.error?`error: ${n.error}`:n.observed!==n.expected?`expected ${n.expected}, observed ${n.observed}`+(n.rejection?` (rejected: ${n.rejection.code??"rejected"}${n.rejection.message?` \u2014 ${n.rejection.message}`:""})`:""):`rejected: ${n.rejection?.code??"rejected"}${n.rejection?.message?` \u2014 ${n.rejection.message}`:""}`;return{name:n.name,status:"failed",detail:s,type:r}})}}function TP(t,e){let n=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(r=>({name:`${t}: ${r.rule}`,status:"failed",type:r.rule,detail:`${r.message} \u2192 fix: ${r.fix}`}));return{name:`turbobase ext lint ${t}`,cases:n}}function EP(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let n of t.guards)e.push(n.status==="failed"?{name:`guard: ${n.name}`,status:"failed",type:n.name,detail:n.detail}:{name:`guard: ${n.name}`,status:"passed",detail:n.status==="skipped-offline"?`skipped-offline: ${n.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function fb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function qd({includeInternal:t=!0}={}){let e=new vP;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.25.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${da()}
|
|
3703
|
+
`,{mode:384})}async function Kk(t){let e=await La();e.push(t),await ah(e)}async function lh(t){let e=await La(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await ah(e),r??null}async function ro(){return La()}function ja(t,e=Date.now()){let n=[],r=[];for(let s of t)Ok(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function ch(t,e){Na(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new Tr(n);let r=Nk(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>zk(u)))(e.fromTenant),i=Fk(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=Lk(u.rows,r),g=Uk(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:Ck(e.ttl,s),sampleFraction:r,url:Hk(o,e.baseUrl)};return await Kk(l),l}async function dh(t,e){Na(t.target());let r=(await ro()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await lh(e),r):null}async function Da(t,e=Date.now()){Na(t.target());let n=await ro(),{expired:r}=ja(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await lh(o.name),s.push(o)}return s}var Er={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},zC=Object.keys(Er).filter(t=>Er[t].mintable);var HC=Er.pat.prefix,Vk=Object.entries(Er).map(([t,e])=>[e.prefix,t]),Gk=/^[A-Za-z0-9_-]{20,}$/;function Wk(t){if(typeof t!="string")return null;for(let[e,n]of Vk)if(t.startsWith(e)&&Gk.test(t.slice(e.length)))return n;return null}function uh(t){return Wk(t)==="pat"}mr();var Jk=8e3,Yk={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function Zk(t){return Yk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Xk(t,e,n=fetch){let r;try{r=await n(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(Jk)})}catch(o){return{state:"unreachable",detail:o instanceof Error?o.message:String(o)}}if(r.status===200||r.status===403)return{state:"accepted"};if(r.status===401){let o=await r.json().catch(()=>null);return{state:"rejected",reason:typeof o?.reason=="string"&&o.reason?o.reason:"unknown"}}return(r.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${r.status} \u2014 this host does not serve the /v1 API`}}function ph(t){return t.state==="accepted"?Pe()?f.green("accepted"):"accepted":t.state==="rejected"?Pe()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Pe()?f.yellow("unreachable"):"unreachable"}async function hh(t={},e=fetch){let n=await Ct(),{file:r}=Is();if(n.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(f.dim(`no sign-ins stored in ${r}.`));return}let s=await pt(),o=await Promise.all(n.map(async i=>({baseUrl:i.baseUrl,active:!!s&&i.baseUrl===s.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await Xk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Pe())y(ht(o.map(i=>[i.active?f.green("*"):" ",f.bold(i.baseUrl),ph(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${ph(i.check)} (updated ${i.updatedAt})`);L(f.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(f.red(`${i.baseUrl}: ${Zk(i.check.reason)}.`)),L(f.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));s||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function kP(t){let e=await Ct();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ze()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Be(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{k("cancelled.")}}async function SP(t,e){let n;try{n=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let r=(n.headers.get("content-type")??"").includes("application/json");return n.status===200||n.status===403?{ok:!0}:n.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${n.status}`}:r?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${n.status}`}}function _P(t){L(""),L("Sharing is ON. Two things reach the Turbobase product team from this instance:"),L(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),L(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),L(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),L(" about OUR platform, with instance name, user names and ids masked before they leave."),L(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),L("")}async function xP(t,e,n){let r=await fu({baseUrl:t,token:e}),s=(await Ct()).length-1;if(y(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),_P(r.baseUrl),!n)return;let o=await SP(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(L(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?L(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function $P(t){let e=await ra(await wr(t),Mt(t)),n=ga(e);if(!n){let r=/\bdefineConduit\s*[<(]/.test(e);k(r?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...n,sourceCode:e}}async function En(t,e,n,r){try{return await oe.access(t),"skipped"}catch{}return await oe.mkdir(Mt(t),{recursive:!0}),await oe.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await oe.chmod(t,r),"wrote"}async function hb(t,e){if(mb(t)!==".gitignore")return En(t,e.content,e.executable,e.mode);let n=await oe.readFile(t,"utf8").catch(()=>null);if(n===null)return En(t,e.content,e.executable,e.mode);let r=np(n);return r===null?"skipped":(await oe.writeFile(t,r,"utf8"),"merged")}function Nd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Pi(t){process.exit(t)}function RP(t){return{name:"turbobase ext test",cases:t.map(n=>{if(n.pass)return{name:n.name,status:"passed"};let r=n.error?"error":n.rejection?.code??"mismatch",s=n.error?`error: ${n.error}`:n.observed!==n.expected?`expected ${n.expected}, observed ${n.observed}`+(n.rejection?` (rejected: ${n.rejection.code??"rejected"}${n.rejection.message?` \u2014 ${n.rejection.message}`:""})`:""):`rejected: ${n.rejection?.code??"rejected"}${n.rejection?.message?` \u2014 ${n.rejection.message}`:""}`;return{name:n.name,status:"failed",detail:s,type:r}})}}function TP(t,e){let n=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(r=>({name:`${t}: ${r.rule}`,status:"failed",type:r.rule,detail:`${r.message} \u2192 fix: ${r.fix}`}));return{name:`turbobase ext lint ${t}`,cases:n}}function EP(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let n of t.guards)e.push(n.status==="failed"?{name:`guard: ${n.name}`,status:"failed",type:n.name,detail:n.detail}:{name:`guard: ${n.name}`,status:"passed",detail:n.status==="skipped-offline"?`skipped-offline: ${n.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function fb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function qd({includeInternal:t=!0}={}){let e=new vP;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.27.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${da()}
|
|
3704
3704
|
`),e.hook("preAction",(d,h)=>{mp(e.opts(),h.opts())});let n=e.command("auth").description("Sign in to an instance and manage stored credentials."),r=e.command("project").description("Set up the local project and the files an agent session reads."),s=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),o=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");n.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let h=tt(d.baseUrl);d.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
3705
3705
|
${_r} auth login --base-url ${h} --token tb_pat_\u2026`),uh(d.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await xP(h,d.token,d.verify)}),n.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async d=>hh({probe:d.probe})),n.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let h=d??await kP("Pick the active instance:"),w=await Cs(h);if(!w){let x=await Ct();k(`no stored sign-in for ${tt(h)}.`+(x.length?` Stored: ${x.map(v=>v.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${tt(h)} --token tb_pat_\u2026\`.`)}y(`active instance \u2192 ${w.baseUrl}.`)}),n.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let x=await Ct();for(let v of x)await Zi(v.baseUrl);y(`removed ${x.length} stored sign-in${x.length===1?"":"s"}.`);return}let h=await Zi(d.baseUrl);h||k(d.baseUrl?`no stored sign-in for ${tt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await pt();y(`signed out of ${h}.`+(w?` Active instance \u2192 ${w.baseUrl}.`:""))}),r.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:h,token:w}=await G(d.baseUrl),x;try{x=await pn({baseUrl:h,token:w,recordsOnly:d.recordsOnly})}catch(m){let _=m instanceof Error?m.message:String(m);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(_)){L("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{x=await pn({baseUrl:h,token:w,recordsOnly:!0})}catch(E){k(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else k(`types generation failed: ${_}`)}let v=se(process.cwd(),d.out);await oe.writeFile(v,x,"utf8"),y(`wrote ${v} (${x.split(`
|
|
3706
3706
|
`).length} lines).`)}),bp(r),r.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async d=>{let{baseUrl:h,token:w}=await G(d.baseUrl),x=new URLSearchParams;d.records&&x.set("records",d.records),d.query&&x.set("query",d.query);let v=x.toString(),m=await fetch(`${h}/v1/catalog/grounding${v?`?${v}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});m.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${m.status}`);let E=((await m.json()).markdown??"").trim(),A=se(process.cwd(),d.out),C=d.records?` records=${d.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${C} \u2014 do not edit; re-run to refresh. -->
|
|
@@ -3730,7 +3730,7 @@ samples init: ${E} written, ${A} skipped.`)});let St=e.command("guardrails").des
|
|
|
3730
3730
|
`+f.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));y(ht(v.map(vs),{head:Ii})),y(f.dim(" first match wins; lower PRIO is evaluated first."))}),St.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:x}=await G(h.baseUrl),v=new B({baseUrl:w,token:x}),m;try{m=await v.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(_){W(_,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} created${m.status==="active"?"":f.dim(` (${m.status} \u2014 activate it to take effect)`)}`),y(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.actor?` actor=${m.actor}`:""}${m.when?` where ${m.when}`:""} @prio ${m.priority}`)),y(f.dim(` verify with: turbobase guardrails test --source ${m.source==="*"?"<source>":m.source} --record <record>`))}),St.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:w,token:x}=await G(h.baseUrl),v=new B({baseUrl:w,token:x}),m;try{m=await v.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(_){W(_,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} updated`),y(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.when?` where ${m.when}`:""} @prio ${m.priority}`))});for(let[d,h,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])St.command(`${d} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(x,v)=>{let{baseUrl:m,token:_}=await G(v.baseUrl),E=new B({baseUrl:m,token:_});try{await E.guardrailUpdate(x,{status:h})}catch(A){W(A,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(x)} ${w}`),h==="inactive"&&y(f.dim(" writes it was gating now fall through to the other rules."))});St.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:x}=await G(h.baseUrl),v=new B({baseUrl:w,token:x});try{await v.guardrailDelete(d)}catch(m){W(m,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${m instanceof Error?m.message:String(m)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(d)} deleted`)}),St.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:x}=await G(h.baseUrl),v=new B({baseUrl:w,token:x}),m=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await v.guardrailPostureGet()}catch(C){W(C,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}y(`guardrail posture: ${f.bold(m(A.mode))}`),y(f.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let _=d.trim().toLowerCase();_!=="allow"&&_!=="deny"&&k("posture must be 'allow' or 'deny'.");let E;try{E=await v.guardrailPostureSet(_)}catch(A){W(A,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail posture set to ${f.bold(m(E.mode))}`),E.mode==="deny"&&y(f.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),St.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let h;if(d.fields)try{h=JSON.parse(d.fields)}catch(E){k(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:w,token:x}=await G(d.baseUrl),v=new B({baseUrl:w,token:x}),m;try{m=await v.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(E){W(E,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return y(JSON.stringify(m,null,2));let _=`${d.source}/${m.op??d.record}`;m.degraded?(y(`${f.red("\u2717")} ${_} \u2014 guardrail policy is UNREADABLE; writes fail closed`),y(f.dim(` ${m.reason}`))):m.allowed?y(`${f.green("\u2713")} ${_} \u2014 ${m.decision}`+(m.blockedBy?f.dim(` (rule ${m.blockedBy})`):f.dim(" (no rule matched)"))):(y(`${f.red("\u2717")} ${_} \u2014 ${m.decision} by ${f.bold(m.blockedBy??"?")} at the ${m.phase} gate`),m.message&&y(f.dim(` ${m.message}`))),m.decision==="require_confirm"&&y(f.yellow(" this write is HELD for operator approval, not refused.")),m.allowed||(process.exitCode=1)});let pr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),ks=(d,h={})=>{let w=`${f.bold(d.table)} ${f.dim(d.displayName)}`;y(d.exists===!1?`${w} ${f.dim("(new)")}`:w);for(let x of d.fields){let v=[x.required?"required":null].filter(Boolean).join(", "),m=h.showClaimants&&x.claimedBy?.length?` ${f.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";y(` ${x.column.padEnd(28)} ${x.type}${v?` (${v})`:""}${m}`)}h.showClaimants&&d.claimants.length>1&&y(f.dim(` claimed by ${d.claimants.join(", ")}`))};function Ss(d){if(d instanceof X&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let zd=async d=>{let h=Qe(se(process.cwd(),d),"public","turbobase.json"),w=await oe.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let x;try{x=JSON.parse(w)}catch(m){k(`${h} is not valid JSON: ${m instanceof Error?m.message:String(m)}`)}let v=x.tables;return v===void 0?{tables:[],manifestPath:h}:(Array.isArray(v)||k(`${h}: "tables" must be an array.`),{tables:v,manifestPath:h})};pr.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await G(d.baseUrl),x=new B({baseUrl:h,token:w}),v;try{v=await x.tablesList()}catch(m){W(m,"extensions:deploy","list tables"),k(`list tables failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return y(JSON.stringify(v,null,2));if(v.length===0)return y("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");y(ht(v.map(m=>[m.table,m.displayName,String(m.fields.length),m.status,m.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),pr.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,h)=>{let w=await zd(d??".");if(w||k(`no public/turbobase.json under ${se(process.cwd(),d??".")}.`),w.tables.length===0)return y(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:x,token:v}=await G(h.baseUrl),m=new B({baseUrl:x,token:v}),_;try{_=await Z("planning tables",()=>m.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch(E){W(E,"extensions:deploy","plan tables"),Ss(E)}y(`claiming as ${f.bold(_.claimedBy)}`);for(let E of _.tables)ks(E,{showClaimants:!0});y(""),y(f.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),pr.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,h)=>{let w=await zd(d??".");if(w||k(`no public/turbobase.json under ${se(process.cwd(),d??".")}.`),w.tables.length===0)return y(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:x,token:v}=await G(h.baseUrl),m=new B({baseUrl:x,token:v}),_;try{_=await Z("applying tables",()=>m.tablesApply({claimedBy:h.as,tables:w.tables}))}catch(E){W(E,"extensions:deploy","apply tables"),Ss(E)}for(let E of _.tables)ks(E,{showClaimants:!0});y(`applied ${_.tables.length} table${_.tables.length===1?"":"s"} as ${_.claimedBy}.`)}),pr.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,h)=>[...h??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let w=h.field.map(E=>{let[A,C,O]=E.split(":");return(!A||!C)&&k(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&k(`--field "${E}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:x,token:v}=await G(h.baseUrl),m=new B({baseUrl:x,token:v}),_;try{_=await Z(`creating cr_${d}`,()=>m.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){W(E,"extensions:deploy","create a table"),Ss(E)}for(let E of _.tables)ks(E);y(""),y(f.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),pr.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.confirm!==d&&k(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:w,token:x}=await G(h.baseUrl),v=new B({baseUrl:w,token:x}),m;try{m=await Z(`dropping cr_${d}`,()=>v.tablesDrop(d,h.confirm))}catch(_){W(_,"extensions:deploy","drop a table"),k(`drop failed: ${_ instanceof Error?_.message:String(_)}`)}if(!m.removed)return y(`no table named "${d}" on this instance \u2014 nothing dropped.`);y(`dropped ${m.table} and every row in it.`)});let Ci=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ci.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let h=jd(),w;try{w=await ch(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(x){x instanceof Tr&&k(x.message),k(`sandbox create failed: ${x instanceof Error?x.message:String(x)}`)}y(`sandbox ${w.name} ready.`),y(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),y(` url: ${w.url}`),y(` expires: ${w.expiresAt}`)}),Ci.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let h=jd();await Da(h).catch(()=>[]);let w;try{w=await dh(h,d)}catch(x){k(`sandbox destroy failed: ${x instanceof Error?x.message:String(x)}`)}w||k(`no sandbox named '${d}'.`),y(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Ci.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=jd(),h=await Da(d).catch(()=>[]),w=await ro(),{active:x}=ja(w);if(x.length===0)y("no active sandboxes.");else{for(let v of x)y(` ${v.name} from=${v.fromTenant} expires=${v.expiresAt} ${v.url}`);y(`
|
|
3731
3731
|
${x.length} active sandbox(es).`)}h.length>0&&y(`(reaped ${h.length} expired sandbox(es).)`)}),s.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Gs).action(async d=>{let{baseUrl:h,token:w}=await G(d.baseUrl),x=new B({baseUrl:h,token:w}),v;try{v=await Z("exporting instance config",()=>x.configExport())}catch(E){E instanceof X&&(E.status===401||E.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let m=typeof v.serialized=="string"?v.serialized:`${JSON.stringify(v.manifest??v,null,2)}
|
|
3732
3732
|
`,_=se(process.cwd(),d.out,kr);await oe.mkdir(Mt(_),{recursive:!0}),await oe.writeFile(_,m,"utf8"),y(`wrote ${d.out}/${kr} (${m.split(`
|
|
3733
|
-
`).length} lines).`)});let Bd=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),gb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Fd=()=>process.env.TURBOBASE_HOME?.trim()||Qe(wP(),".turbobase"),yb=()=>"1.
|
|
3733
|
+
`).length} lines).`)});let Bd=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),gb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Fd=()=>process.env.TURBOBASE_HOME?.trim()||Qe(wP(),".turbobase"),yb=()=>"1.27.0",_s=async()=>Promise.all(gb.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Bd.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await _s();for(let h of d)y(`${h.present?be.success("installed"):be.warn("missing")} ${f.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
|
|
3734
3734
|
run \`${_r} ext extras install\` to fetch them into ${Fd()}.`)}),Bd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await _s();if(d.every(A=>A.present)){y(be.success("extras already installed \u2014 nothing to do."));return}let h=Fd();await oe.mkdir(h,{recursive:!0});let w=d.filter(A=>!A.present).map(A=>A.name),x=Aa(process.platform,process.arch),v=async(A,C)=>{let{code:O,stderr:U}=await ws("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&k(`extras install failed while installing ${C} (npm exited ${O}).
|
|
3735
3735
|
${U.trim()}
|
|
3736
3736
|
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},m=w.filter(A=>A!=="isolated-vm");if(m.length>0){let A=m.map(C=>`${C}@${Ea[C]??"latest"}`);y(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await v(A,m.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${Ea["isolated-vm"]}`;if(y(`installing ${A} \u2192 ${h}/node_modules \u2026`),await v(["--ignore-scripts",A],"isolated-vm"),nh.includes(x)){let O=`${Pa}@${yb()}`;y(`fetching ${O} (no upstream binary for ${x}) \u2026`);let{code:U}=await ws("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);U!==0&&y(be.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await rh({home:h});C.length>0&&y(` ${be.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${x}`)}let _=await _s(),E=_.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){y(be.warn(`no prebuilt isolated-vm for ${x} / Node ${process.versions.node} (${Ia()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await ws("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(_=await _s(),E=_.filter(C=>!C.present).map(C=>C.name))}E.length>0&&k(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${x} / Node ${process.versions.node} (${Ia()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),y(be.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Pn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Pn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let h=d.target==="approved"?"approved":d.target==="auto"?"auto":null;h||k(`--target must be 'auto' or 'approved' (got '${d.target}').`);let w=await NP(se(process.cwd(),d.project??".")),x=Object.keys(w).length;!d.solution&&x===0&&k("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let m=(d.ref?await Dd(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Dd(["rev-parse","HEAD"]),_=d.gitRepo??process.env.GITHUB_REPOSITORY??await Dd(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await G(d.baseUrl),U=new B({baseUrl:C,token:O}),I;try{I=await U.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:x>0?w:null,gitRepo:_,gitRef:E,gitSha:m,prUrl:A})}catch(H){W(H,"releases:write","release deploy"),H instanceof X&&H.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${H instanceof Error?H.message:String(H)}`)}y(`release ${I.releaseId} enqueued \u2192 taskId=${I.taskId} (target=${h}`+(x>0?`, uploaded ${x} bundle file(s)`:", live-fetch")+")."),d.follow&&await ba(()=>U.releaseStatus(I.releaseId),`release ${I.releaseId}`,d.intervalMs)}),Pn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:x}=await G(h.baseUrl),v=new B({baseUrl:w,token:x}),m;try{m=await v.releaseFiles(d)}catch(A){A instanceof X&&A.status===404&&k(`release ${d} not found.`),A instanceof X&&A.status===409&&k(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),W(A,"releases:write","pull a release"),k(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let _=se(process.cwd(),h.dir),E=0;for(let[A,C]of[["owned",m.owned],["context",m.context]])for(let[O,U]of Object.entries(C)){let I=Qe(_,A,O);await oe.mkdir(Mt(I),{recursive:!0}),await oe.writeFile(I,U,"utf8"),E++}await oe.writeFile(Qe(_,".turbobase-release.json"),JSON.stringify({releaseId:m.releaseId,version:m.version,contentDigest:m.contentDigest},null,2),"utf8"),y(`pulled release ${m.releaseId} (${m.status}) \u2192 ${_}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@turbobase/cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.27.0",
|
|
4
4
|
"description": "Author, test, and deploy Turbobase extensions (hooks + conduits) against a tenant over HTTP + a personal access token.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE",
|