kenobi-pages 0.1.15 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.mjs CHANGED
@@ -1,82 +1,95 @@
1
1
  #!/usr/bin/env node
2
- var R=Object.defineProperty;var t=(e,o)=>R(e,"name",{value:o,configurable:!0});import{existsSync as v,readFileSync as E,writeFileSync as x,appendFileSync as _}from"node:fs";import{readFile as U}from"node:fs/promises";import{resolve as k}from"node:path";import{createInterface as j}from"node:readline";var K="https://kenobi.ai",u="KENOBI_PAGES_KEY",I=[".env.local",".env",".env.development",".env.development.local"],T=t(()=>{let e={},o=process.cwd();for(let n of I){let s=k(o,n);if(!v(s))continue;let r=E(s,"utf-8");for(let i of r.split(`
3
- `)){let a=i.trim();if(!a||a.startsWith("#"))continue;let c=a.match(/^([A-Z_][A-Z0-9_]*)=["']?([^"']*)["']?$/);c&&(e[c[1]]??=c[2])}}return e},"loadEnvFromCwd"),$=null,O=t(e=>process.env[e]?process.env[e]:($??=T(),$[e]),"getEnvVar"),J=t(()=>{let e=O(u);return e||(console.error("Error: No API key found."),console.error(""),console.error("Run 'npx kenobi-pages init' to set up your API key,"),console.error("or add KENOBI_PAGES_KEY to your project's env file (e.g. .env or .env.local)."),process.exit(1)),e},"getApiKey"),F=t(()=>(O("KENOBI_BASE_URL")??K).replace(/\/+$/,""),"getBaseUrl"),p=t(async(e,o={})=>{let n=`${F()}${e}`,s=await fetch(n,{method:o.method??"GET",headers:{"x-kenobi-key":J(),"Content-Type":"application/json"},body:o.body?JSON.stringify(o.body):void 0});if(!s.ok){let r=await s.text().catch(()=>"Unknown error"),i=s.status===401||s.status===403?4:s.status===404?3:1;console.error(`Error ${s.status}: ${r}`),i===4&&console.error("If you're using a custom base URL, make sure KENOBI_BASE_URL is set in your project's env file."),process.exit(i)}return s.json()},"fetchKenobi"),y=t(e=>new Promise(o=>{let n=j({input:process.stdin,output:process.stderr});n.question(e,s=>{n.close(),o(s.trim())})}),"prompt"),A=t(()=>new Promise((e,o)=>{let n="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",s=>{n+=s}),process.stdin.on("end",()=>e(n)),process.stdin.on("error",o),process.stdin.isTTY&&e("")}),"readStdin"),P=t(async e=>{let o=e.indexOf("--file");return o!==-1&&e[o+1]?U(e[o+1],"utf-8"):null},"parseFileArg"),L=t(()=>{let e=process.cwd();return I.filter(o=>v(k(e,o)))},"discoverEnvFiles"),B=t((e,o,n)=>{let s=E(e,"utf-8");if(s.includes(o)){console.error(` \u2713 ${o} already present in ${e.split("/").pop()}`);return}let r=s.endsWith(`
2
+ var Oe=Object.defineProperty;var r=(t,e)=>Oe(t,"name",{value:e,configurable:!0});var k=class extends Error{static{r(this,"CliError")}exitCode;payload;constructor(e,n=1){super(e.message),this.name="CliError",this.exitCode=n,this.payload={ok:!1,...e}}},d=r((t,e)=>new k({status:null,code:"invalid_usage",message:t,details:e},2),"usageError"),C=r((t,e)=>new k({status:404,code:"not_found",message:t,details:e},3),"notFoundError"),p=r((t,e,n)=>{if(!t)throw d(e,n);return t},"assertArg"),l=r(t=>{console.log(JSON.stringify(t,null,2))},"printJson"),Z=r(t=>{console.error(JSON.stringify(t,null,2))},"writeError"),X=r(t=>{t instanceof k&&(Z(t.payload),process.exit(t.exitCode));let e=t instanceof Error?t.message:"Unknown error";Z({ok:!1,status:null,code:"runtime_error",message:e}),process.exit(1)},"handleCliError");var g=r((t,e)=>{let n=t.indexOf(e);return n!==-1?t[n+1]:void 0},"parseFlag"),m=r((t,e)=>t.includes(e),"hasFlag"),f=r((t,e,n)=>{let s=g(t,e);if(!s||s.startsWith("--"))throw d(n);return s},"parseRequiredFlag"),W=r((t,e)=>{let n=g(t,e);if(n===void 0)return;let s=Number(n);if(!Number.isInteger(s)||s<=0)throw d(`${e} must be a positive integer`);return s},"parseOptionalPositiveIntFlag"),M=r((t,e)=>{let n=g(t,e);if(n===void 0)return;let s=Number(n);if(!Number.isInteger(s)||s<0)throw d(`${e} must be a non-negative integer`);return s},"parseOptionalNonNegativeIntFlag");import{appendFileSync as Pe,existsSync as B,readFileSync as H,writeFileSync as ee}from"node:fs";import{resolve as te}from"node:path";var Te="https://kenobi.ai",w="KENOBI_PAGES_KEY",ne=[".env.local",".env",".env.development",".env.development.local"],Ce=r(()=>{let t={},e=process.cwd();for(let n of ne){let s=te(e,n);if(!B(s))continue;let o=H(s,"utf-8");for(let i of o.split(`
3
+ `)){let c=i.trim();if(!c||c.startsWith("#"))continue;let a=c.match(/^([A-Z_][A-Z0-9_]*)=["']?([^"']*)["']?$/);a&&(t[a[1]]??=a[2])}}return t},"loadEnvFromCwd"),L=null,R=r(t=>process.env[t]?process.env[t]:(L??=Ce(),L[t]),"getEnvVar"),je=r(()=>{L=null},"resetEnvCache"),v=r(()=>(R("KENOBI_BASE_URL")??Te).replace(/\/+$/,""),"getBaseUrl"),se=r(()=>{let t=R(w);if(t)return t;throw new k({status:null,code:"missing_api_key",message:`No API key found. Run 'npx kenobi-pages init' or set ${w}.`},4)},"getApiKey"),oe=r(()=>R(w),"getApiKeyOptional"),U=r(()=>{let t=process.cwd();return ne.filter(e=>B(te(t,e)))},"discoverEnvFiles"),re=r((t,e,n)=>{let s=H(t,"utf-8");if(s.includes(e)){console.error(` ${e} already present in ${t.split("/").pop()}`);return}let o=s.endsWith(`
4
4
  `)?"":`
5
- `;_(e,`${r}${o}="${n}"
6
- `),console.error(` \u2713 Added ${o} to ${e.split("/").pop()}`)},"appendEnvVar"),W=t((e,o)=>{B(e,u,o)},"appendKeyToEnvFile"),D=t(async()=>{console.error(""),console.error(" Kenobi Pages \u2014 Setup"),console.error(""),console.error(" Find your API key at: https://kenobi.ai/setup"),console.error("");let e=await y(" Paste your API key (pk_live_... or pk_test_...): ");e||(console.error(" No key provided. Aborting."),process.exit(1)),!e.startsWith("pk_live_")&&!e.startsWith("pk_test_")&&(console.error(` Warning: "${e}" doesn't look like a Kenobi key (expected pk_live_... or pk_test_...).`),(await y(" Continue anyway? (y/N): ")).toLowerCase()!=="y"&&(console.error(" Aborting."),process.exit(1))),console.error("");let o=L();if(o.length>0){console.error(""),console.error(" Found env files in this project:"),o.forEach((r,i)=>console.error(` ${i+1}. ${r}`)),console.error(` ${o.length+1}. Create a new file`),console.error(` ${o.length+2}. Skip`),console.error("");let n=await y(` Which file should ${u} be added to? [1]: `),s=n===""?0:parseInt(n,10)-1;if(s===o.length){let r=await y(" Filename (e.g. .env.local): ");if(r){let i=k(process.cwd(),r);x(i,`${u}="${e}"
7
- `),console.error(` \u2713 Created ${r} with ${u}`)}}else s>=0&&s<o.length&&W(k(process.cwd(),o[s]),e)}else{console.error("");let n=await y(" No env files found. Create one? (filename or 'n' to skip) [.env.local]: "),s=`${u}="${e}"
8
- `;if(n.toLowerCase()!=="n"&&n!==""){let r=k(process.cwd(),n);x(r,s),console.error(` \u2713 Created ${n} with ${u}`)}else if(n===""){let r=k(process.cwd(),".env.local");x(r,s),console.error(` \u2713 Created .env.local with ${u}`)}}console.error(""),console.error(" Done! Your agent can now use kenobi-pages commands."),console.error(" Run 'npx kenobi-pages --help' to see what's available."),console.error("")},"initCommand"),G=t(async e=>{let o=e[0];o||(console.error("Usage: kenobi-pages schema get <workflowId>"),process.exit(2));let n=await p(`/api/v1/pages/${o}/schema`);console.log(JSON.stringify(n,null,2))},"schemaGet"),S=t((e,o)=>{let n=" ".repeat(o);switch(e.type){case"string":case"url":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return e.items?.type==="object"&&e.items.fields?`Array<{
9
- ${Object.entries(e.items.fields).map(([i,a])=>`${n} ${i}: ${S(a,o+2)}`).join(`
5
+ `;Pe(t,`${o}${e}="${n}"
6
+ `),console.error(` Added ${e} to ${t.split("/").pop()}`)},"appendEnvVar"),j=r((t,e,n)=>{ee(t,`${e}="${n}"
7
+ `)},"writeEnvFile"),G=r((t,e,n)=>{let s=B(t)?H(t,"utf-8"):"",o=`${e}="${n}"`,i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`^${i}=.*$`,"m"),a=c.test(s)?s.replace(c,o):`${s}${s.length>0&&!s.endsWith(`
8
+ `)?`
9
+ `:""}${o}
10
+ `;ee(t,a),je()},"upsertEnvVar");var Ae=r(async t=>{let e=await t.text().catch(()=>"");if(!e)return null;try{return JSON.parse(e)}catch{return e}},"parseErrorBody"),Ke=r(t=>{if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&"error"in t){let e=t.error;return typeof e=="string"?e:JSON.stringify(e)}return"Kenobi API request failed"},"errorMessageFromBody"),_e=r(t=>t===401||t===403?4:t===404?3:1,"exitCodeForStatus"),u=r(async(t,e={})=>{let n=await fetch(`${v()}${t}`,{method:e.method??"GET",headers:{"x-kenobi-key":se(),"Content-Type":"application/json"},body:e.body?JSON.stringify(e.body):void 0});if(n.ok)return await n.json();let s=await Ae(n);throw new k({status:n.status,code:n.status===401||n.status===403?"unauthorized":"api_error",message:Ke(s),details:s},_e(n.status))},"fetchKenobi"),$=r(t=>{let e=new URLSearchParams;for(let[n,s]of Object.entries(t))s!==void 0&&e.set(n,s);return e.toString()},"buildQuery");var I=r(t=>Object.keys(t??{}),"keys"),ie=r(t=>{let e=t.packJson??null,n=e?.tokens??{},s=e?.surfaces??{},o=e?.typography??{},i=e?.accents??{};return{designPack:{id:t.id,status:t.status,hostDomain:e?.hostDomain??t.hostDomain??null,raw:e},templateGuidance:{brandSummary:e?.compositionDescription??"Use the raw design pack tokens and recipes as the source of truth.",tokens:{color:n.color??{},font:n.font??{},radius:n.radius??{},container:n.container??{},section:n.section??{}},surfaces:s,typography:o,accents:i,use:["Use color, font, radius, spacing, surface, and typography recipes from this design pack before inventing new styles.","Preserve the source site's visual rhythm, density, button treatment, and section composition.","Keep the template source self-contained and accept all dynamic values through the Template content prop."],avoid:["Do not use generic SaaS gradients, decorative orbs, or unrelated stock-style visuals.","Do not introduce a new palette when the design pack already contains brand colors.","Do not hard-code personalized copy that should come from the content schema."],availableRecipes:{colors:I(n.color),fonts:I(n.font),radii:I(n.radius),surfaces:I(s),typography:I(o),accents:I(i)}}}},"exportDesignPackForAgent");var De=new Set(["COMPLETED","FAILED","CANCELED","SYSTEM_FAILURE","CRASHED"]),Ne=r(t=>new Promise(e=>setTimeout(e,t)),"sleep"),Je=r(async(t,e)=>{let n=2e3,s=15e3;for(;;){await Ne(n);let o=await u(`/api/v1/pages/evidence-bundles/${t}/design-packs/runs/${e}`),i=typeof o.status=="string"?o.status:"UNKNOWN";if(console.error(`Status: ${i}`),De.has(i)){l(o),i!=="COMPLETED"&&process.exit(1);return}n=Math.min(n*1.5,s)}},"pollDesignPack"),ae=r(async t=>{let[e,...n]=t,s=n[0];if(e==="list"){p(s,"Usage: kenobi-pages design-pack list <bundleId>"),l(await u(`/api/v1/pages/evidence-bundles/${s}/design-packs`));return}if(e==="generate"){p(s,"Usage: kenobi-pages design-pack generate <bundleId> [--wait]");let o=await u(`/api/v1/pages/evidence-bundles/${s}/design-packs`,{method:"POST",body:m(n.slice(1),"--dry-run")?{dryRun:!0}:{}});if(m(n.slice(1),"--dry-run")){l(o);return}if(!m(n.slice(1),"--wait")){l(o);return}let i=typeof o.taskId=="string"?o.taskId:void 0;if(!i){l(o);return}console.error(`Design pack generation queued: ${i}`),await Je(s,i);return}if(e==="status"){let o=p(n[1],"Usage: kenobi-pages design-pack status <bundleId> <taskId>");p(s,"Usage: kenobi-pages design-pack status <bundleId> <taskId>"),l(await u(`/api/v1/pages/evidence-bundles/${s}/design-packs/runs/${o}`));return}if(e==="get"){let o=p(n[1],"Usage: kenobi-pages design-pack get <bundleId> <designPackId>");p(s,"Usage: kenobi-pages design-pack get <bundleId> <designPackId>"),l(await u(`/api/v1/pages/evidence-bundles/${s}/design-packs/${o}`));return}if(e==="export"){let o=p(n[1],"Usage: kenobi-pages design-pack export <bundleId> <designPackId>");p(s,"Usage: kenobi-pages design-pack export <bundleId> <designPackId>");let i=await u(`/api/v1/pages/evidence-bundles/${s}/design-packs/${o}`);l(ie(i.designPack??{}));return}throw d(`Unknown design-pack command: ${t.join(" ")}`)},"handleDesignPack");import{existsSync as We,readFileSync as Me}from"node:fs";import{dirname as ce,join as Le}from"node:path";import{fileURLToPath as Be}from"node:url";var He=r(()=>{let t=ce(Be(import.meta.url));for(let e=0;e<6;e+=1){let n=Le(t,"package.json");if(We(n))try{let s=JSON.parse(Me(n,"utf-8"));if(s.name==="kenobi-pages"&&s.version)return s.version}catch{return"unknown"}t=ce(t)}return"unknown"},"findPackageVersion"),le=He();var Ge=r(async t=>{try{let e=await fetch(`${v()}/api/v1/cortex/sources`,{headers:{"x-kenobi-key":t,"Content-Type":"application/json"}});if(!e.ok)return{auth:{ok:!1,status:e.status},sources:{count:null}};let n=await e.json();return{auth:{ok:!0,status:e.status},sources:{count:Array.isArray(n.sources)?n.sources.length:0}}}catch(e){return{auth:{ok:!1,status:null,error:e instanceof Error?e.message:"Unknown error"},sources:{count:null}}}},"authCheck"),ue=r(async()=>{let t=oe(),e=U(),n=t?await Ge(t):{auth:{ok:!1,status:null,skipped:!0},sources:{count:null}},s=[];t?n.auth.ok||s.push("Check that the Kenobi API key is valid for this org."):s.push(`Run 'kenobi-pages init' or set ${w}.`),t&&n.auth.ok&&n.sources.count===0&&s.push("Connect at least one source in Kenobi before building data-backed workflows."),l({ok:!!(t&&n.auth.ok),cli:{version:le},env:{hasApiKey:!!t,apiKeyEnvVar:w,baseUrl:v(),envFiles:e},auth:n.auth,sources:n.sources,nextSteps:s})},"handleDoctor");import{readFile as pe}from"node:fs/promises";var de=r(()=>new Promise((t,e)=>{if(process.stdin.isTTY){t("");return}let n="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",s=>{n+=s}),process.stdin.on("end",()=>t(n)),process.stdin.on("error",e)}),"readStdin"),y=r((t,e)=>{try{return JSON.parse(t)}catch{throw d(`Invalid JSON for ${e}`)}},"parseJson"),x=r(async(t,e)=>y(await pe(t,"utf-8"),e),"readJsonFile"),F=r(async(t,e)=>{if(!t){let n=await de();if(!n.trim())throw d(`Missing ${e}`);return y(n,e)}if(t==="-"){let n=await de();if(!n.trim())throw d(`Missing ${e} on stdin`);return y(n,e)}return t.trim().startsWith("{")||t.trim().startsWith("[")?y(t,e):x(t,e)},"readJsonSource"),O=r(async(t,e="JSON")=>{let n=g(t,"--file");if(n)return x(n,e);let s=t.find(o=>o.trim().startsWith("{")||o.trim().startsWith("["));return F(s,e)},"readJsonInput"),ge=r(async(t,e,n)=>{let s=g(t,e);if(s!==void 0)return F(s,n)},"readJsonFlag"),A=r(async(t,e,n)=>F(g(t,e),n),"readRequiredJsonFlag"),fe=r(async(t,e,n)=>{let s=g(t,e);if(!s||s.startsWith("--"))throw d(`Missing ${n}`);return pe(s,"utf-8")},"readTextFileFlag");var Ve=r((t,e)=>{let n={url:t},s=g(e,"--viewport"),o=g(e,"--headers"),i=g(e,"--wait-for-selector"),c=M(e,"--wait-timeout"),a=g(e,"--wait-until"),h=M(e,"--extra-wait-ms");return s&&(n.viewport=y(s,"--viewport")),o&&(n.headers=y(o,"--headers")),i&&(n.waitForSelector=i),c!==void 0&&(n.waitTimeout=c),a&&(n.waitUntil=a.trim().startsWith("[")?y(a,"--wait-until"):a),h!==void 0&&(n.extraWaitMs=h),m(e,"--block-annoyances")&&(n.blockAnnoyances=!0),m(e,"--dry-run")&&(n.dryRun=!0),n},"createEvidenceBody"),me=r(async t=>{let[e,...n]=t;if(e==="list"){l(await u("/api/v1/pages/evidence-bundles"));return}if(e==="create"){let s=p(n[0],"Usage: kenobi-pages evidence create <url> [flags]");l(await u("/api/v1/pages/evidence-bundles",{method:"POST",body:Ve(s,n.slice(1))}));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages evidence get <bundleId>");l(await u(`/api/v1/pages/evidence-bundles/${s}`));return}throw d(`Unknown evidence command: ${t.join(" ")}`)},"handleEvidence");var qe="kenobi.page",Ye=r(t=>(t??qe).replace(/^https?:\/\//,"").replace(/\/+$/,"").toLowerCase(),"normalizeHostedDomain"),ze=r(()=>Ye(R("KENOBI_PAGES_HOSTED_DOMAIN")),"getHostedPagesDomain"),E=r(({siteSlug:t,templateSlug:e,itemSlug:n})=>`https://${t}.${ze()}/${e}/${n}`,"buildHostedPublicUrl"),we=r((t,e)=>{if(typeof t!="object"||t===null)return t;let n=t,s=typeof n.siteSlug=="string"?n.siteSlug:e?.siteSlug,o=typeof n.templateSlug=="string"?n.templateSlug:e?.templateSlug,i=typeof n.itemSlug=="string"?n.itemSlug:e?.itemSlug;return!s||!o||!i?t:{...t,publicUrl:E({siteSlug:s,templateSlug:o,itemSlug:i})}},"maybeDecorateHostedContent"),V=r((t,e)=>({...t,publicUrl:E(e)}),"decorateHostedContentResponse");var he=r(async t=>{let e=f(t,"--template-slug","Usage: kenobi-pages hosted draft save --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file>"),n=f(t,"--template-name","Usage: kenobi-pages hosted draft save --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file>"),s=await fe(t,"--source","--source <tsx-file>"),o=f(t,"--schema","Missing --schema <json-file>"),i=f(t,"--content","Missing --content <json-file>"),c=W(t,"--design-pack-id"),a=g(t,"--site-slug"),h=g(t,"--site-name"),b={templateSlug:e,templateName:n,sourceTsx:s,contentSchema:{title:n,schemaJson:await x(o,"--schema")},defaultContentJson:await x(i,"--content"),setCurrentDraft:!m(t,"--no-current-draft")};return c!==void 0&&(b.designPackId=c),a&&(b.site={slug:a,...h?{name:h}:{}}),b},"parseHostedDraftBody"),ke=r(t=>{let e=typeof t.previewPath=="string"?t.previewPath:null;return{...t,...e?{previewUrl:`${v()}${e}`}:{}}},"withPreviewUrl"),Qe=r(async t=>{let[e,...n]=t;if(e==="list"){l(await u("/api/v1/pages/hosted/sites"));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages hosted site get <siteSlug>");l(await u(`/api/v1/pages/hosted/sites?${$({slug:s})}`));return}throw d(`Unknown hosted site command: ${t.join(" ")}`)},"handleHostedSite"),Ze=r(async t=>{let[e,...n]=t;if(e==="list"){let s=$({full:m(n,"--full")?"true":void 0});l(await u(`/api/v1/pages/hosted/templates${s?`?${s}`:""}`));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages hosted template get <templateIdOrSlug> [--full]"),o=$({full:m(n.slice(1),"--full")?"true":void 0});l(await u(`/api/v1/pages/hosted/templates/${s}${o?`?${o}`:""}`));return}throw d(`Unknown hosted template command: ${t.join(" ")}`)},"handleHostedTemplate"),Xe=r(async t=>{let[e,...n]=t;if(e==="list"){let s=p(n[0],"Usage: kenobi-pages hosted publication list <templateIdOrSlug>");l(await u(`/api/v1/pages/hosted/templates/${s}/publications`));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages hosted publication get <templateIdOrSlug> <publicationId>"),o=p(n[1],"Usage: kenobi-pages hosted publication get <templateIdOrSlug> <publicationId>");l(await u(`/api/v1/pages/hosted/templates/${s}/publications/${o}`));return}throw d(`Unknown hosted publication command: ${t.join(" ")}`)},"handleHostedPublication"),et=r(async t=>{let[e,...n]=t;if(e==="list"){let s=f(n,"--site","Usage: kenobi-pages hosted content list --site <siteSlug> [--template <templateSlug>]"),o=g(n,"--template"),i=await u(`/api/v1/pages/hosted/instances?${$({siteSlug:s,templateSlug:o})}`);l({...i,instances:(i.instances??[]).map(c=>we(c,{siteSlug:s,templateSlug:o}))});return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),o=p(n[1],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),i=p(n[2],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),c=await u(`/api/v1/pages/hosted/instances/${s}/${o}/${i}`);l(V(c,{siteSlug:s,templateSlug:o,itemSlug:i}));return}if(e==="upsert"){let s=f(n,"--site","Usage: kenobi-pages hosted content upsert --site <siteSlug> --template <templateSlug> --item <itemSlug> --content <json|file|->"),o=f(n,"--template","Missing --template <templateSlug>"),i=f(n,"--item","Missing --item <itemSlug>"),c=W(n,"--publication-id"),a=await A(n,"--content","--content"),h=await u("/api/v1/pages/hosted/instances",{method:"POST",body:{siteSlug:s,templateSlug:o,itemSlug:i,contentJson:a,...c!==void 0?{publicationId:c}:{}}});l(V(h,{siteSlug:s,templateSlug:o,itemSlug:i}));return}if(e==="verify"){let s=p(n[0],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),o=p(n[1],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),i=p(n[2],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),c=E({siteSlug:s,templateSlug:o,itemSlug:i});try{let a=await u(`/api/v1/pages/hosted/instances/${s}/${o}/${i}`);l({ok:!0,publicUrl:c,resolved:!0,contentValid:!0,publication:a.templatePublication??null})}catch(a){if(!(a instanceof k))throw a;let b=(typeof a.payload.details=="object"&&a.payload.details!==null&&"stage"in a.payload.details?a.payload.details.stage:null)==="invalid-content"?!1:null;l({ok:!1,publicUrl:c,resolved:a.payload.status!==404,contentValid:b,publication:null,error:a.payload}),process.exit(a.exitCode)}return}throw d(`Unknown hosted content command: ${t.join(" ")}`)},"handleHostedContent"),tt=r(async t=>{let[e,...n]=t;if(e==="create"){let s=["--site-slug",f(n,"--site-slug","Missing --site-slug <siteSlug>"),...g(n,"--site-name")?["--site-name",g(n,"--site-name")]:[],"--template-slug",f(n,"--template-slug","Missing --template-slug <templateSlug>"),"--template-name",f(n,"--template-name","Missing --template-name <templateName>"),"--source",f(n,"--source","Missing --source <tsx-file>"),"--schema",f(n,"--schema","Missing --schema <json-file>"),"--content",f(n,"--content","Missing --content <json-file>"),...g(n,"--design-pack-id")?["--design-pack-id",g(n,"--design-pack-id")]:[],...m(n,"--no-current-draft")?["--no-current-draft"]:[]];l(ke(await u("/api/v1/pages/hosted/templates/drafts",{method:"POST",body:await he(s)})));return}throw d(`Unknown hosted page command: ${t.join(" ")}`)},"handleHostedPage"),ye=r(async t=>{let[e,n,...s]=t;if(e==="site")return Qe([n,...s].filter(Boolean));if(e==="template")return Ze([n,...s].filter(Boolean));if(e==="publication")return Xe([n,...s].filter(Boolean));if(e==="content")return et([n,...s].filter(Boolean));if(e==="page")return tt([n,...s].filter(Boolean));if(e==="draft"&&n==="save"){l(ke(await u("/api/v1/pages/hosted/templates/drafts",{method:"POST",body:await he(s)})));return}if(e==="publish"){let o=p(n,"Usage: kenobi-pages hosted publish <templateIdOrSlug>");l(await u(`/api/v1/pages/hosted/templates/${o}/publish`,{method:"POST"}));return}throw d(`Unknown hosted command: ${t.join(" ")}`)},"handleHosted");import{readFile as nt}from"node:fs/promises";var st=new Set(["COMPLETED","FAILED","CANCELED","SYSTEM_FAILURE","CRASHED"]),ot="Usage: kenobi-pages run <workflowIdOrSlug> [--dry-run] [--debug] [--params '<json>'|--params-file params.json] [--context <text>|--context-file notes.md]",rt=r(t=>new Promise(e=>setTimeout(e,t)),"sleep"),it=r(t=>{if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&"message"in t){let e=t.message;if(typeof e=="string")return e}return"Unknown error"},"runStatusErrorMessage"),be=r(async t=>{let e=p(t[0],ot),n=t.slice(1),s=g(n,"--params"),o=g(n,"--params-file"),i=g(n,"--context"),c=g(n,"--context-file"),a=m(n,"--dry-run"),h=m(n,"--debug");if(o?.startsWith("--"))throw d("Missing --params-file <path>");if(c?.startsWith("--"))throw d("Missing --context-file <path>");let b=o?await x(o,"--params-file"):s?y(s,"--params"):{},Q=c?await nt(c,"utf-8"):i,_={params:b};Q&&(_.context=Q),a&&(_.dryRun=!0);let D=await u(`/api/v1/cortex/workflows/${e}/run`,{method:"POST",body:_});if(a){l(D);return}let N=typeof D.runId=="string"?D.runId:void 0;if(!N)throw d("Run did not return a runId");console.error(`Run triggered: ${N}`),console.error("Polling for completion...");let J=2e3,Fe=15e3;for(;;){await rt(J);let S=await u(`/api/v1/cortex/workflows/${e}/runs/${N}${h?"?debug=true":""}`);if(console.error(`Status: ${S.status}`),st.has(S.status)){S.status!=="COMPLETED"&&(console.error(`Run failed (${S.status}): ${it(S.error)}`),l(S),process.exit(1)),l(S);return}J=Math.min(J*1.5,Fe)}},"handleRun");var K=r((t,e)=>{let n=" ".repeat(e);switch(t.type){case"string":case"url":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return t.items?.type==="object"&&t.items.fields?`Array<{
11
+ ${Object.entries(t.items.fields).map(([i,c])=>`${n} ${i}: ${K(c,e+2)}`).join(`
10
12
  `)}
11
- ${n} }>`:`${e.items?S(e.items,o):"unknown"}[]`;case"object":return e.fields?`{
12
- ${Object.entries(e.fields).map(([r,i])=>`${n} ${r}: ${S(i,o+1)}`).join(`
13
+ ${n} }>`:`${t.items?K(t.items,e):"unknown"}[]`;case"object":return t.fields?`{
14
+ ${Object.entries(t.fields).map(([o,i])=>`${n} ${o}: ${K(i,e+1)}`).join(`
13
15
  `)}
14
- ${n}}`:"Record<string, unknown>";default:return"unknown"}},"schemaTypeToTs"),M=t(async e=>{let o=e[0];o||(console.error("Usage: kenobi-pages schema codegen <workflowId>"),console.error(" npx kenobi-pages schema codegen 42 > lib/kenobi-types.ts"),process.exit(2));let n=await p(`/api/v1/pages/${o}/schema`),r=(n.title??"KenobiPage").replace(/[^a-zA-Z0-9\s]/g,"").split(/\s+/).map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join("")+"Content",i=Object.entries(n.schema).map(([a,c])=>`${c.description?` /** ${c.description} */
15
- `:""} ${a}: ${S(c,1)}`).join(`
16
- `);console.log(`export interface ${r} {
16
+ ${n}}`:"Record<string, unknown>";default:return"unknown"}},"schemaTypeToTs"),at=r(t=>`${t.replace(/[^a-zA-Z0-9\s]/g,"").split(/\s+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}Content`,"interfaceNameFromTitle"),ct=r(async t=>(await u(`/api/v1/cortex/workflows/${t}`)).id,"resolveWorkflowId"),lt=r(async t=>{let[e,...n]=t;if(e==="list"){l(await u("/api/v1/pages/self-hosted/schemas"));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages self-hosted schema get <workflowIdOrSlug>");l(await u(`/api/v1/pages/self-hosted/${s}/schema`));return}if(e==="codegen"){let s=p(n[0],"Usage: kenobi-pages self-hosted schema codegen <workflowIdOrSlug>"),o=await u(`/api/v1/pages/self-hosted/${s}/schema`),i=Object.entries(o.schema).map(([c,a])=>`${a.description?` /** ${a.description} */
17
+ `:""} ${c}: ${K(a,1)}`).join(`
18
+ `);console.log(`export interface ${at(o.title??"KenobiPage")} {
17
19
  ${i}
18
- }`),console.error(`Generated interface ${r} from workflow ${o}`)},"schemaCodegen"),Y=t(async e=>{let o=e[0];o||(console.error("Usage: kenobi-pages schema push <name> '<json>'"),console.error(" kenobi-pages schema push <name> --file schema.json"),console.error(" echo '<json>' | kenobi-pages schema push <name>"),process.exit(2));let n=e.slice(1),s=await P(n),r=s?null:n.find(h=>h.startsWith("{")),i=!s&&!r?await A():null,a=s??r??i;(!a||a.trim().length===0)&&(console.error("Error: No schema provided."),console.error("Pass inline JSON, --file <path>, or pipe to stdin."),process.exit(2));let c;try{c=JSON.parse(a)}catch{console.error("Error: Invalid JSON."),process.exit(2)}let d=await p("/api/v1/pages/schema",{method:"POST",body:{name:o,schema:c}});console.log(JSON.stringify(d,null,2)),console.error(`Schema "${d.name}" pushed successfully.`),console.error(`Source key: ${d.sourceKey}`),console.error("You can now select this schema as an output target in the Kenobi workflow builder.")},"schemaPush"),V=t(async e=>{let o=e[0];o||(console.error("Usage: kenobi-pages pages <workflowId>"),process.exit(2));let n=await p(`/api/v1/pages/${o}`);console.log(JSON.stringify(n,null,2))},"listPages"),z=t(async e=>{let[o,n]=e;(!o||!n)&&(console.error("Usage: kenobi-pages page get <workflowId> <slug>"),process.exit(2));let s=await p(`/api/v1/pages/${o}/${n}`);console.log(JSON.stringify(s,null,2))},"pageGet"),Z=new Set(["COMPLETED","FAILED","CANCELED","SYSTEM_FAILURE","CRASHED"]),q=t(e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"message"in e){let o=e.message;if(typeof o=="string")return o}return"Unknown error"},"runStatusErrorMessage"),H=t(e=>new Promise(o=>setTimeout(o,e)),"sleep"),m=t((e,o)=>{let n=e.indexOf(o);return n!==-1&&e[n+1]?e[n+1]:void 0},"parseFlag"),X=t(async e=>{let o=e[0];o||(console.error("Usage: kenobi-pages run <workflowId> [--params '<json>'] [--context '<text>']"),process.exit(2));let n=e.slice(1),s={},r=m(n,"--params");if(r)try{s=JSON.parse(r)}catch{console.error("Error: Invalid JSON in --params"),process.exit(2)}let i=m(n,"--context"),a={params:s};i&&(a.context=i);let c=await p(`/api/v1/workflows/${o}/run`,{method:"POST",body:a});console.error(`Run triggered: ${c.runId}`),console.error("Polling for completion...");let d=2e3,h=15e3;for(;;){await H(d);let w=await p(`/api/v1/workflows/${o}/runs/${c.runId}`);if(console.error(` Status: ${w.status}`),Z.has(w.status)){if(w.status!=="COMPLETED"){let C=q(w.error);console.error(`
19
- Run failed (${w.status}): ${C}`),console.log(JSON.stringify(w,null,2)),process.exit(1)}console.log(JSON.stringify(w,null,2));return}d=Math.min(d*1.5,h)}},"runWorkflow"),Q=t(async()=>{let e=await p("/api/v1/workflows");console.log(JSON.stringify(e,null,2))},"listWorkflows"),ee=t(async()=>{let e=await p("/api/v1/sources");console.log(JSON.stringify(e,null,2))},"listSources"),oe=t(async e=>{let o=await p(`/api/v1/sources/${encodeURIComponent(e)}/sample`);console.log(JSON.stringify(o,null,2))},"sampleSource"),N=t(async e=>{let o=await P(e),n=o?null:e.find(i=>i.startsWith("{")),s=!o&&!n?await A():null,r=o??n??s;(!r||r.trim().length===0)&&(console.error("Error: No JSON provided."),console.error("Pass inline JSON, --file <path>, or pipe to stdin."),process.exit(2));try{return JSON.parse(r)}catch{console.error("Error: Invalid JSON."),process.exit(2)}},"readJsonInput"),ne=t(async e=>{let o=m(e,"--name"),n=m(e,"--slug");(!o||!n)&&(console.error("Usage: kenobi-pages workflow create --name '<name>' --slug '<slug>' --config '<json>'"),console.error(" kenobi-pages workflow create --name '<name>' --slug '<slug>' --file config.json"),process.exit(2));let s=m(e,"--description"),r=e.indexOf("--config"),i=r!==-1&&e[r+1]?[e[r+1]]:e,a=await N(i),c={name:o,slug:n,config:a};s&&(c.description=s);let d=await p("/api/v1/workflows",{method:"POST",body:c});console.log(JSON.stringify(d,null,2)),console.error(`Workflow "${o}" created.`)},"workflowCreate"),se=t(async e=>{let o=e[0];o||(console.error("Usage: kenobi-pages workflow get <workflowId>"),process.exit(2));let n=await p(`/api/v1/workflows/${o}?full=true`);console.log(JSON.stringify(n,null,2))},"workflowGet"),re=t(async e=>{let o=e[0];o||(console.error("Usage: kenobi-pages workflow update <workflowId> --config '<json>'"),console.error(" kenobi-pages workflow update <workflowId> --file config.json"),process.exit(2));let n=e.slice(1),s=m(n,"--name"),r=m(n,"--description"),i=n.indexOf("--config"),a=i!==-1&&n[i+1]?[n[i+1]]:n,c={};s&&(c.name=s),r!==void 0&&(c.description=r),(n.includes("--config")||n.includes("--file"))&&(c.config=await N(a)),Object.keys(c).length===0&&(console.error("Error: Nothing to update. Pass --name, --description, --config, or --file."),process.exit(2));let h=await p(`/api/v1/workflows/${o}`,{method:"PUT",body:c});console.log(JSON.stringify(h,null,2)),console.error("Workflow updated.")},"workflowUpdate"),te=t(async e=>{let o=e[0];o||(console.error("Usage: kenobi-pages workflow delete <workflowId>"),process.exit(2)),await p(`/api/v1/workflows/${o}`,{method:"DELETE"}),console.error("Workflow deleted.")},"workflowDelete"),ie=`kenobi-pages \u2014 Kenobi Pages CLI
20
+ }`);return}if(e==="push"){let s=p(n[0],"Usage: kenobi-pages self-hosted schema push <name> '<json>'"),o=await O(n.slice(1),"schema");l(await u("/api/v1/pages/self-hosted/schemas",{method:"POST",body:{title:s,schemaJson:o}}));return}throw d(`Unknown self-hosted schema command: ${t.join(" ")}`)},"handleSchema"),ut=r(async t=>{let[e,...n]=t;if(e==="list"){let s=p(n[0],"Usage: kenobi-pages self-hosted content list <workflowIdOrSlug>");l(await u(`/api/v1/pages/self-hosted/content-entries?${$({workflowId:s})}`));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages self-hosted content get <workflowIdOrSlug> <slug>"),o=p(n[1],"Usage: kenobi-pages self-hosted content get <workflowIdOrSlug> <slug>");l(await u(`/api/v1/pages/self-hosted/${s}/${o}`));return}if(e==="upsert"){let s=f(n,"--workflow","Missing --workflow <idOrSlug>"),o=f(n,"--source-key","Missing --source-key <sourceKey>"),i=f(n,"--slug","Missing --slug <slug>"),c=await A(n,"--content","--content"),a=await ge(n,"--metadata","--metadata");l(await u("/api/v1/pages/self-hosted/content-entries",{method:"POST",body:{workflowId:await ct(s),slug:i,sourceKey:o,contentJson:c,...a!==void 0?{metadataJson:a}:{}}}));return}throw d(`Unknown self-hosted content command: ${t.join(" ")}`)},"handleContent"),Se=r(async t=>{let[e,n,...s]=t;if(e==="schema")return lt([n,...s].filter(Boolean));if(e==="content")return ut([n,...s].filter(Boolean));throw d(`Unknown self-hosted command: ${t.join(" ")}`)},"handleSelfHosted");var ve=r(async t=>{let[e,...n]=t;if(e===void 0||e==="list"){l(await u("/api/v1/cortex/sources"));return}if(e==="sample"){let s=p(n[0],"Usage: kenobi-pages sources sample <sourceKey>");l(await u(`/api/v1/cortex/sources/${encodeURIComponent(s)}/sample`));return}if(e==="schema"){let s=p(n[0],"Usage: kenobi-pages sources schema <sourceKey>"),i=(await u("/api/v1/cortex/sources")).sources.find(c=>c.sourceKey===s);if(!i)throw C(`Source not found: ${s}`);l({sourceKey:s,schema:i.schema??null});return}throw d(`Unknown sources command: ${t.join(" ")}`)},"handleSources");var dt=r(t=>{let e=t.resolution;return e?e.kind==="single"?"Use one record from this source.":e.kind==="lookup"?`Look up one record where ${e.field??"(missing field)"} equals runtime param ${e.param??"(missing param)"}.`:e.kind==="collection"?"Use this source as a collection.":`Unknown source resolution: ${e.kind??"(missing kind)"}.`:"Resolution is not configured."},"formatSourceResolution"),$e=r((t,e)=>{let n=new Set;for(let s of Object.values(t.output?.fields??{}))s.binding?.strategy==="passthrough"&&s.binding.sourceId===e&&s.binding.sourceField&&n.add(s.binding.sourceField);for(let s of t.generationGroups??[])for(let o of s.contextSources??[])o.sourceId===e&&(o.fields?o.fields.forEach(i=>n.add(i)):Object.keys((t.sources??[]).find(i=>i.id===e)?.schema??{}).forEach(i=>n.add(i)));return[...n].sort((s,o)=>s.localeCompare(o))},"fieldsForSource"),xe=r((t,e)=>Object.entries(t.output?.fields??{}).filter(([,n])=>n.binding?.groupId===e).map(([n])=>n).sort((n,s)=>n.localeCompare(s)),"producedByGroup"),pt=r(t=>{let e=t.adapterConfig??{},n=typeof e.slugField=="string"?e.slugField:null;if(t.adapter==="hosted-pages"){let s=typeof e.siteSlug=="string"?e.siteSlug:null,o=typeof e.templateSlug=="string"?e.templateSlug:null;return{id:t.id,type:t.adapter,writes:s&&o&&n?E({siteSlug:s,templateSlug:o,itemSlug:`{${n}}`}):"Hosted page URL pattern is incomplete.",slugField:n}}return t.adapter==="self-hosted-pages"?{id:t.id,type:t.adapter,writes:n?`Self-hosted page content keyed by workflowId + {${n}}.`:"Self-hosted page slug field is not configured.",slugField:n}:{id:t.id,type:t.adapter??"unknown",writes:"Destination is not a Kenobi Pages destination.",slugField:n}},"destinationSummary"),gt=r(t=>{let e=[],n=new Set((t.params??[]).map(i=>i.name)),s=t.output?.fields??{},o=new Set;for(let[i,c]of Object.entries(s)){let a=c.binding;(!a||a.strategy==="unconfigured")&&e.push(`Output field "${i}" is unconfigured.`),a?.strategy==="param"&&a.paramName&&!n.has(a.paramName)&&e.push(`Output field "${i}" references missing param "${a.paramName}".`),(a?.strategy==="generate"||a?.strategy==="generate-image")&&o.add(i)}for(let i of t.sources??[])i.resolution?.kind==="lookup"&&i.resolution.param&&(n.has(i.resolution.param)||e.push(`Source "${i.id}" lookup references missing param "${i.resolution.param}".`));for(let i of t.generationGroups??[])xe(t,i.id).length===0&&e.push(`Generation group "${i.id}" does not produce any output fields.`);for(let i of t.destinations??[]){let c=i.adapterConfig??{},a=typeof c.slugField=="string"?c.slugField:null;if(!a){e.push(`Destination "${i.id}" is missing adapterConfig.slugField.`);continue}s[a]?s[a].type!=="string"&&e.push(`Destination "${i.id}" slugField "${a}" is not a string field.`):e.push(`Destination "${i.id}" slugField "${a}" is not in output.fields.`)}return e},"collectWarnings"),Ie=r(t=>({summary:t.description??t.output?.title??t.id??"Kenobi workflow",inputs:(t.params??[]).map(e=>({name:e.name,description:e.description??null})),sources:(t.sources??[]).map(e=>({id:e.id,title:e.title??e.id,provider:e.provider??null,sourceKey:e.dataSourceKey??null,resolution:dt(e),fieldsUsed:$e(t,e.id)})),generation:(t.generationGroups??[]).map(e=>({group:e.id,strategy:e.strategy??null,uses:(e.contextSources??[]).map(n=>({sourceId:n.sourceId,fields:n.fields??$e(t,n.sourceId)})),produces:xe(t,e.id)})),output:{dataSourceKey:t.output?.dataSourceKey??null,title:t.output?.title??null,fields:Object.keys(t.output?.fields??{})},destinations:(t.destinations??[]).map(pt),warnings:gt(t)}),"explainWorkflow");var Ee=r((t,e)=>Object.fromEntries(Object.entries(t).map(([n,s])=>[n,{...s,binding:n===e?{strategy:"param",paramName:e}:{strategy:"unconfigured"}}])),"asUnconfiguredOutputFields"),Re=r((t,e)=>({...t,[e]:{type:"string",description:"URL slug for the generated page.",...t[e]}}),"ensureSlugField"),ft=r(t=>t.split(":").pop()?.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()||"pages-workflow","slugFromSourceKey"),q=r(async t=>{let e=g(t,"--config");if(e!==void 0){if(e.startsWith("--"))throw d("Missing --config '<json>'");return F(e,"workflow config")}return O(t,"workflow config")},"readWorkflowConfig"),mt=r(async t=>{let e=f(t,"--template-publication","Usage: kenobi-pages workflow scaffold hosted --template-publication <templateId:publicationId> --site <siteSlug> --template <templateSlug> --slug-field <field>"),[n,s]=e.split(":");if(!n||!s)throw d("--template-publication must be <templateId:publicationId>");let o=f(t,"--site","Missing --site <siteSlug>"),i=f(t,"--template","Missing --template <templateSlug>"),c=f(t,"--slug-field","Missing --slug-field <field>"),h=(await u(`/api/v1/pages/hosted/templates/${n}/publications/${s}`)).cortexOutputFieldSpecs??{},b=Ee(Re(h,c),c);l({id:`${o}-${i}`,params:[{name:c,description:"Public hosted page item slug."}],sources:[],output:{dataSourceKey:`hosted-pages:${i}`,title:`${i} hosted page`,fields:b},generationGroups:[],destinations:[{id:"hosted-pages",adapter:"hosted-pages",adapterConfig:{siteSlug:o,templateSlug:i,slugField:c,publicationId:Number(s)}}]})},"scaffoldHosted"),wt=r(async t=>{let e=f(t,"--source-key","Usage: kenobi-pages workflow scaffold self-hosted --source-key <sourceKey> --slug-field <field>"),n=f(t,"--slug-field","Missing --slug-field <field>"),o=(await u("/api/v1/cortex/sources")).sources.find(a=>a.sourceKey===e);if(!o)throw C(`Source not found: ${e}`);let i=Ee(Re(o.schema??{},n),n),c=ft(e);l({id:c,params:[{name:n,description:"URL slug for the generated page."}],sources:[],output:{dataSourceKey:e,title:o.sourceTitle??c,fields:i},generationGroups:[],destinations:[{id:"self-hosted-pages",adapter:"self-hosted-pages",adapterConfig:{slugField:n}}]})},"scaffoldSelfHosted"),ht=r(async t=>{let[e,...n]=t;if(e==="hosted")return mt(n);if(e==="self-hosted")return wt(n);throw d(`Unknown workflow scaffold command: ${t.join(" ")}`)},"handleScaffold"),Y=r(async t=>{let[e,...n]=t;if(e===void 0||e==="list"){l(await u("/api/v1/cortex/workflows"));return}if(e==="create"){let s=f(n,"--name","Missing --name <name>"),o=f(n,"--slug","Missing --slug <slug>"),i=g(n,"--description"),c=m(n,"--dry-run"),a={name:s,slug:o,config:await q(n)};i&&(a.description=i),c&&(a.dryRun=!0),l(await u("/api/v1/cortex/workflows",{method:"POST",body:a}));return}if(e==="validate"){let s=f(n,"--name","Missing --name <name>"),o=f(n,"--slug","Missing --slug <slug>"),i=g(n,"--description"),c={name:s,slug:o,config:await q(n)};i&&(c.description=i),l(await u("/api/v1/cortex/workflows/validate",{method:"POST",body:c}));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages workflow get <workflowIdOrSlug>");l(await u(`/api/v1/cortex/workflows/${s}?full=true`));return}if(e==="update"){let s=p(n[0],"Usage: kenobi-pages workflow update <workflowIdOrSlug> [flags]"),o=n.slice(1),i={},c=m(o,"--dry-run"),a=g(o,"--name"),h=g(o,"--description");if(a&&(i.name=a),h!==void 0&&(i.description=h),(o.includes("--config")||o.includes("--file"))&&(i.config=await q(o)),c&&(i.dryRun=!0),Object.keys(i).length===(c?1:0))throw d("Nothing to update");l(await u(`/api/v1/cortex/workflows/${s}`,{method:"PUT",body:i}));return}if(e==="delete"){let s=p(n[0],"Usage: kenobi-pages workflow delete <workflowIdOrSlug>");l(await u(`/api/v1/cortex/workflows/${s}`,{method:"DELETE"}));return}if(e==="explain"){let s=await O(n,"workflow config");l(Ie(s));return}if(e==="scaffold")return ht(n);throw d(`Unknown workflow command: ${t.join(" ")}`)},"handleWorkflows");var kt=`kenobi-pages - Kenobi Pages CLI
20
21
 
21
22
  Commands:
22
- init Set up your API key (interactive)
23
+ doctor
24
+ init
25
+ init --key <key> [--env-file <path>] [--base-url <url>]
23
26
 
24
- schema get <workflowId> Fetch a workflow's output schema
25
- schema codegen <workflowId> Generate a TypeScript interface from a schema
26
- schema push <name> '<json>' Push a schema to Kenobi (inline JSON)
27
- schema push <name> --file f Push a schema to Kenobi (from file)
27
+ evidence list
28
+ evidence create <url> [flags] [--dry-run]
29
+ evidence get <bundleId>
28
30
 
29
- pages <workflowId> List all generated pages for a workflow
30
- page get <workflowId> <slug> Fetch page content for a specific lead
31
+ design-pack list <bundleId>
32
+ design-pack generate <bundleId> [--wait] [--dry-run]
33
+ design-pack status <bundleId> <taskId>
34
+ design-pack get <bundleId> <designPackId>
35
+ design-pack export <bundleId> <designPackId>
31
36
 
32
- sources List connected data sources
33
- sources sample <sourceKey> Preview sample rows from a source
34
- sources schema <sourceKey> Show schema for a specific source
35
- workflows List workflows for your org
37
+ hosted site list
38
+ hosted site get <siteSlug>
39
+ hosted page create --site-slug <slug> --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file> [flags]
40
+ hosted template list [--full]
41
+ hosted template get <templateIdOrSlug> [--full]
42
+ hosted draft save --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file> [flags]
43
+ hosted publish <templateIdOrSlug>
44
+ hosted publication list <templateIdOrSlug>
45
+ hosted publication get <templateIdOrSlug> <publicationId>
46
+ hosted content list --site <siteSlug> [--template <templateSlug>]
47
+ hosted content get <siteSlug> <templateSlug> <itemSlug>
48
+ hosted content upsert --site <siteSlug> --template <templateSlug> --item <itemSlug> --content <json|file|->
49
+ hosted content verify <siteSlug> <templateSlug> <itemSlug>
36
50
 
37
- workflow create --name '\u2026' --slug '\u2026' --config '<json>' Create a workflow
38
- workflow create --name '\u2026' --slug '\u2026' --file config.json Create from file
39
- workflow get <id> Get full workflow config
40
- workflow update <id> --config '<json>' Update workflow config
41
- workflow update <id> --file config.json Update from file
42
- workflow delete <id> Delete a workflow
51
+ self-hosted schema list
52
+ self-hosted schema get <workflowIdOrSlug>
53
+ self-hosted schema codegen <workflowIdOrSlug>
54
+ self-hosted schema push <name> '<json>'
55
+ self-hosted content list <workflowIdOrSlug>
56
+ self-hosted content get <workflowIdOrSlug> <slug>
57
+ self-hosted content upsert --workflow <idOrSlug> --source-key <sourceKey> --slug <slug> --content <json|file|-> [--metadata <json|file|->]
43
58
 
44
- run <workflowId> [flags] Trigger a workflow run and poll to completion
59
+ sources [list]
60
+ sources sample <sourceKey>
61
+ sources schema <sourceKey>
62
+ workflows
63
+ workflow validate --name <name> --slug <slug> --config '<json>'
64
+ workflow validate --name <name> --slug <slug> --file config.json
65
+ workflow create --name <name> --slug <slug> --config '<json>' [--dry-run]
66
+ workflow create --name <name> --slug <slug> --file config.json [--dry-run]
67
+ workflow get <idOrSlug>
68
+ workflow update <idOrSlug> [--dry-run] [--name <name>] [--description <description>] [--config '<json>'|--file config.json]
69
+ workflow delete <idOrSlug>
70
+ workflow explain --file workflow.json
71
+ workflow explain --config '<json>'
72
+ workflow scaffold hosted --template-publication <templateId:publicationId> --site <siteSlug> --template <templateSlug> --slug-field <field>
73
+ workflow scaffold self-hosted --source-key <sourceKey> --slug-field <field>
74
+ run <workflowIdOrSlug> [--dry-run] [--debug] [--params '<json>'|--params-file params.json] [--context <text>|--context-file notes.md]
45
75
 
46
- Examples:
47
- npx kenobi-pages init
48
- npx kenobi-pages sources
49
- npx kenobi-pages sources sample "notion:abc123"
50
- npx kenobi-pages sources schema "webflow-cms:prospect-landing-pages"
51
- npx kenobi-pages schema get 42
52
- npx kenobi-pages schema codegen 42 > lib/kenobi-types.ts
53
- npx kenobi-pages schema push "My Page" '{"fields":{"headline":{"type":"string"}}}'
54
- npx kenobi-pages pages 42
55
- npx kenobi-pages page get 42 acme-corp
56
- npx kenobi-pages workflows
57
- npx kenobi-pages workflow create --name "Lead page" --slug "lead-page" --config '{...}'
58
- npx kenobi-pages workflow get 42
59
- npx kenobi-pages workflow update 42 --config '{...}'
60
- npx kenobi-pages workflow delete 42
61
- npx kenobi-pages run 42 --params '{"slug":"acme-corp"}'
62
- npx kenobi-pages run 42 --params '{"slug":"acme-corp"}' --context "Call transcript: ..."
76
+ Agent-first examples:
77
+ kenobi-pages doctor
78
+ kenobi-pages init --key pk_test_... --env-file .env.local
79
+ kenobi-pages evidence create https://example.com --block-annoyances
80
+ kenobi-pages design-pack generate 123 --wait
81
+ kenobi-pages design-pack export 123 456
82
+ kenobi-pages hosted page create --site-slug acme --template-slug follow-up --template-name "Follow-up" --source template.tsx --schema schema.json --content preview.json --design-pack-id 456
83
+ kenobi-pages workflow explain --file workflow.json
84
+ kenobi-pages workflow validate --name "Post-call follow-up" --slug post-call-follow-up --file workflow.json
85
+ kenobi-pages run workflow-slug --dry-run --params-file params.json --context-file transcript.md
86
+ kenobi-pages run workflow-slug --params-file params.json --context-file transcript.md
87
+ kenobi-pages hosted content verify acme follow-up globex
63
88
 
64
89
  Output:
65
- All data is written as JSON to stdout. Status messages go to stderr.
66
- Pipe stdout to jq, a file, or another command safely.
67
-
68
- Exit codes:
69
- 0 Success
70
- 1 API or network error
71
- 2 Invalid usage (bad arguments)
72
- 3 Resource not found (404)
73
- 4 Unauthorized (invalid API key)
90
+ Data is JSON on stdout. Progress goes to stderr. Errors are JSON on stderr.
74
91
 
75
92
  Environment:
76
- KENOBI_PAGES_KEY Org public key. Set via 'init' or in your env file.
77
- KENOBI_BASE_URL Optional. Override the Kenobi API base URL.
78
-
79
- Key resolution order:
80
- 1. Shell environment variables
81
- 2. Env files in working directory (.env.local, .env, .env.development, etc.)
82
- `,[,,...b]=process.argv;(b.length===0||b[0]==="--help"||b[0]==="-h")&&(console.log(ie),process.exit(0));var[g,l,...f]=b;if(g==="init")await D();else if(g==="schema"&&l==="get")await G(f);else if(g==="schema"&&l==="codegen")await M(f);else if(g==="schema"&&l==="push")await Y(f);else if(g==="pages")await V([l,...f].filter(Boolean));else if(g==="page"&&l==="get")await z(f);else if(g==="sources")if(l==="sample"){let e=f[0];e||(console.error("Usage: kenobi-pages sources sample <sourceKey>"),process.exit(2)),await oe(e)}else if(l==="schema"){let e=f[0];e||(console.error("Usage: kenobi-pages sources schema <sourceKey>"),console.error(" Shows the schema for a specific source (fields and types)."),process.exit(2));let n=(await p("/api/v1/sources")).sources.find(s=>s.sourceKey===e);n||(console.error(`Source not found: ${e}`),process.exit(3)),console.log(JSON.stringify({sourceKey:e,schema:n.normalizedSchema??n.rawSchema},null,2))}else l===void 0||l==="list"?await ee():(console.error(`Unknown sources subcommand: ${l}`),console.error("Run 'kenobi-pages --help' for usage."),process.exit(2));else g==="workflows"||g==="workflow"&&!l?await Q():g==="workflow"&&l==="create"?await ne(f):g==="workflow"&&l==="get"?await se(f):g==="workflow"&&l==="update"?await re(f):g==="workflow"&&l==="delete"?await te(f):g==="run"?await X([l,...f].filter(Boolean)):(console.error(`Unknown command: ${b.join(" ")}`),console.error("Run 'kenobi-pages --help' for usage."),process.exit(1));
93
+ KENOBI_PAGES_KEY Org public key. Set via init or in your env file.
94
+ KENOBI_BASE_URL Optional API base URL override.
95
+ `,z=r(()=>{console.log(kt)},"printHelp");import{resolve as P}from"node:path";import{createInterface as yt}from"node:readline";var T=r(t=>new Promise(e=>{let n=yt({input:process.stdin,output:process.stderr});n.question(t,s=>{n.close(),e(s.trim())})}),"prompt"),bt=r(async t=>t.startsWith("pk_live_")||t.startsWith("pk_test_")?!0:(console.error(` Warning: "${t}" does not look like a Kenobi key (expected pk_live_... or pk_test_...).`),(await T(" Continue anyway? (y/N): ")).toLowerCase()==="y"),"validateKey"),St=r(()=>U()[0]??".env.local","defaultEnvFile"),vt=r(t=>{let e=g(t,"--key");if(!e||e.startsWith("--"))throw d("Usage: kenobi-pages init --key <key> [--env-file <path>] [--base-url <url>]");let n=g(t,"--env-file")??St(),s=g(t,"--base-url"),o=P(process.cwd(),n);G(o,w,e),s&&!s.startsWith("--")&&G(o,"KENOBI_BASE_URL",s),l({ok:!0,envFile:n,wrote:{[w]:!0,KENOBI_BASE_URL:!!(s&&!s.startsWith("--"))}})},"nonInteractiveInit"),Ue=r(async(t=[])=>{if(g(t,"--key")!==void 0){vt(t);return}console.error(""),console.error(" Kenobi Pages - Setup"),console.error(""),console.error(" Find your API key at: https://kenobi.ai/setup"),console.error("");let e=await T(" Paste your API key (pk_live_... or pk_test_...): ");e||(console.error(" No key provided. Aborting."),process.exit(1)),await bt(e)||(console.error(" Aborting."),process.exit(1));let n=U();if(n.length>0){console.error(""),console.error(" Found env files in this project:"),n.forEach((i,c)=>console.error(` ${c+1}. ${i}`)),console.error(` ${n.length+1}. Create a new file`),console.error(` ${n.length+2}. Skip`),console.error("");let s=await T(` Which file should ${w} be added to? [1]: `),o=s===""?0:parseInt(s,10)-1;if(o===n.length){let i=await T(" Filename (e.g. .env.local): ");i&&(j(P(process.cwd(),i),w,e),console.error(` Created ${i} with ${w}`))}else o>=0&&o<n.length&&re(P(process.cwd(),n[o]),w,e)}else{console.error("");let s=await T(" No env files found. Create one? (filename or 'n' to skip) [.env.local]: ");s.toLowerCase()!=="n"&&s!==""?(j(P(process.cwd(),s),w,e),console.error(` Created ${s} with ${w}`)):s===""&&(j(P(process.cwd(),".env.local"),w,e),console.error(` Created .env.local with ${w}`))}console.error(""),console.error(" Done. Your agent can now use kenobi-pages commands."),console.error(" Run 'npx kenobi-pages --help' to see what is available."),console.error("")},"initCommand");var $t=r(async t=>{if(t.length===0||t[0]==="--help"||t[0]==="-h"){z();return}let[e,...n]=t;if(n.includes("--help")||n.includes("-h")){z();return}if(e==="init")return Ue(n);if(e==="doctor")return ue();if(e==="evidence")return me(n);if(e==="design-pack")return ae(n);if(e==="hosted")return ye(n);if(e==="self-hosted")return Se(n);if(e==="sources")return ve(n);if(e==="workflows")return Y(["list",...n]);if(e==="workflow")return Y(n);if(e==="run")return be(n);throw d(`Unknown command: ${t.join(" ")}`)},"main");$t(process.argv.slice(2)).catch(X);
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- var b=Object.defineProperty;var o=(i,s)=>b(i,"name",{value:s,configurable:!0});import{KenobiPagesError as c,KenobiNotFoundError as a,KenobiUnauthorizedError as f}from"./errors";const K="https://kenobi.ai",l=o(async(i,s,e)=>{const r=(i.baseUrl??K).replace(/\/+$/,""),n={headers:{"x-kenobi-key":i.apiKey}};(e?.revalidate!==void 0||e?.tags)&&(n.next={},e.revalidate!==void 0&&(n.next.revalidate=e.revalidate),e.tags&&(n.next.tags=[...e.tags]));const t=await fetch(`${r}${s}`,n);if(t.ok)return t;if(t.status===401)throw new f;if(t.status===404)throw new a;const g=await t.text().catch(()=>"Unknown error");throw new c(`Kenobi API error (${t.status}): ${g}`,t.status,"API_ERROR")},"fetchPage"),h=o(i=>({getPage:o(async(s,e,r)=>{try{return await(await l(i,`/api/v1/pages/${s}/${e}`,r)).json()}catch(n){if(n instanceof a)return null;throw n}},"getPage")}),"createKenobiPagesClient");export{h as createKenobiPagesClient};
1
+ var l=Object.defineProperty;var o=(s,e)=>l(s,"name",{value:e,configurable:!0});import{KenobiPagesError as d,KenobiNotFoundError as c,KenobiUnauthorizedError as u}from"./errors";const b="https://kenobi.ai",p=o(async(s,e,n,t)=>{const r=(s.baseUrl??b).replace(/\/+$/,""),a={...n,headers:{"x-kenobi-key":s.apiKey,...n?.headers}};(t?.revalidate!==void 0||t?.tags)&&(a.next={},t.revalidate!==void 0&&(a.next.revalidate=t.revalidate),t.tags&&(a.next.tags=[...t.tags]));const i=await fetch(`${r}${e}`,a);if(i.ok)return i;if(i.status===401)throw new u;if(i.status===404)throw new c;const g=await i.text().catch(()=>"Unknown error");throw new d(`Kenobi API error (${i.status}): ${g}`,i.status,"API_ERROR")},"fetchPage"),f=o(s=>({selfHosted:{getPage:o(async(e,n,t)=>{try{return await(await p(s,`/api/v1/pages/self-hosted/${e}/${n}`,void 0,t)).json()}catch(r){if(r instanceof c)return null;throw r}},"getPage")},hosted:{getPageInstance:o(async(e,n,t,r)=>{try{return await(await p(s,`/api/v1/pages/hosted/instances/${e}/${n}/${t}`,void 0,r)).json()}catch(a){if(a instanceof c)return null;throw a}},"getPageInstance"),upsertPageInstance:o(async e=>await(await p(s,"/api/v1/pages/hosted/instances",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})).json(),"upsertPageInstance"),saveTemplateDraft:o(async e=>await(await p(s,"/api/v1/pages/hosted/templates/drafts",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)})).json(),"saveTemplateDraft"),publishTemplate:o(async e=>await(await p(s,`/api/v1/pages/hosted/templates/${e}/publish`,{method:"POST"})).json(),"publishTemplate")}}),"createKenobiPagesClient");export{f as createKenobiPagesClient};
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { createKenobiPagesClient } from "./client";
2
- export { KenobiPagesError, KenobiUnauthorizedError, KenobiNotFoundError } from "./errors";
3
- export type { KenobiPagesClient, KenobiPagesConfig, KenobiFetchOptions, KenobiPageResponse, } from "./types";
2
+ export { KenobiNotFoundError, KenobiPagesError, KenobiUnauthorizedError, } from "./errors";
3
+ export type { KenobiFetchOptions, KenobiHostedPagesClient, KenobiPageInstanceResponse, KenobiPageResponse, KenobiPagesClient, KenobiPagesConfig, KenobiSelfHostedPagesClient, PublishTemplateResponse, UpsertPageInstanceInput, } from "./types";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{createKenobiPagesClient as r}from"./client";import{KenobiPagesError as i,KenobiUnauthorizedError as t,KenobiNotFoundError as b}from"./errors";export{b as KenobiNotFoundError,i as KenobiPagesError,t as KenobiUnauthorizedError,r as createKenobiPagesClient};
1
+ import{createKenobiPagesClient as n}from"./client";import{KenobiNotFoundError as s,KenobiPagesError as i,KenobiUnauthorizedError as r}from"./errors";export{s as KenobiNotFoundError,i as KenobiPagesError,r as KenobiUnauthorizedError,n as createKenobiPagesClient};
package/dist/types.d.ts CHANGED
@@ -13,8 +13,62 @@ export interface KenobiFetchOptions {
13
13
  export interface KenobiPageResponse {
14
14
  readonly content: Record<string, unknown>;
15
15
  readonly metadata: Record<string, unknown> | null;
16
+ readonly outputSchemaSnapshot?: Record<string, unknown> | null;
16
17
  readonly updatedAt: string;
17
18
  }
18
- export interface KenobiPagesClient {
19
+ export interface KenobiPageInstanceResponse {
20
+ readonly pageInstance: Record<string, unknown>;
21
+ readonly templatePublication?: Record<string, unknown>;
22
+ readonly content?: Record<string, unknown>;
23
+ }
24
+ export interface UpsertPageInstanceInput {
25
+ readonly siteSlug: string;
26
+ readonly templateSlug: string;
27
+ readonly itemSlug: string;
28
+ readonly publicationId?: number;
29
+ readonly contentJson: Record<string, unknown>;
30
+ readonly metadataJson?: Record<string, unknown> | null;
31
+ readonly sourceWorkflowId?: number | null;
32
+ readonly sourceRunId?: string | null;
33
+ }
34
+ export interface PublishTemplateResponse {
35
+ readonly publication: Record<string, unknown>;
36
+ readonly currentPublishedPublicationId: number | null;
37
+ }
38
+ export interface SaveHostedTemplateDraftInput {
39
+ readonly templateSlug: string;
40
+ readonly templateName: string;
41
+ readonly sourceTsx: string;
42
+ readonly contentSchema: {
43
+ readonly sourceKey?: string;
44
+ readonly title?: string;
45
+ readonly schemaJson: Record<string, unknown>;
46
+ };
47
+ readonly defaultContentJson: Record<string, unknown>;
48
+ readonly designPackId?: number | null;
49
+ readonly site?: {
50
+ readonly slug: string;
51
+ readonly name?: string | null;
52
+ };
53
+ readonly setCurrentDraft?: boolean;
54
+ }
55
+ export interface SaveHostedTemplateDraftResponse {
56
+ readonly template: Record<string, unknown>;
57
+ readonly revision: Record<string, unknown>;
58
+ readonly contentSchema: Record<string, unknown>;
59
+ readonly site: Record<string, unknown> | null;
60
+ readonly previewPath: string;
61
+ }
62
+ export interface KenobiSelfHostedPagesClient {
19
63
  readonly getPage: (workflowId: number | string, slug: string, opts?: KenobiFetchOptions) => Promise<KenobiPageResponse | null>;
20
64
  }
65
+ export interface KenobiHostedPagesClient {
66
+ readonly getPageInstance: (siteSlug: string, templateSlug: string, itemSlug: string, opts?: KenobiFetchOptions) => Promise<KenobiPageInstanceResponse | null>;
67
+ readonly upsertPageInstance: (input: UpsertPageInstanceInput) => Promise<KenobiPageInstanceResponse>;
68
+ readonly saveTemplateDraft: (input: SaveHostedTemplateDraftInput) => Promise<SaveHostedTemplateDraftResponse>;
69
+ readonly publishTemplate: (templateId: number | string) => Promise<PublishTemplateResponse>;
70
+ }
71
+ export interface KenobiPagesClient {
72
+ readonly selfHosted: KenobiSelfHostedPagesClient;
73
+ readonly hosted: KenobiHostedPagesClient;
74
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kenobi-pages",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "Kenobi Pages SDK — fetch personalized page content from Kenobi workflows",
5
5
  "type": "module",
6
6
  "exports": {