@npayload/sdk 5.0.4 → 5.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/chunk-5KFQTEH3.mjs +1 -0
- package/dist/{chunk-FNAZW7X3.mjs → chunk-5WGVEULS.mjs} +1 -1
- package/dist/{chunk-2PCG57PX.mjs → chunk-6BBB7BRP.mjs} +1 -1
- package/dist/chunk-6HF3N3NR.mjs +1 -0
- package/dist/{chunk-5YK2JKKH.mjs → chunk-6ITUDSL7.mjs} +2 -2
- package/dist/{chunk-EL7XOWA4.mjs → chunk-CNAIHF3M.mjs} +1 -1
- package/dist/chunk-CWBN2DOO.mjs +1 -0
- package/dist/chunk-I3UZ2FRE.mjs +1 -0
- package/dist/chunk-I7YPDC7V.mjs +2 -0
- package/dist/{chunk-RIBBVOCC.mjs → chunk-IK32U5FV.mjs} +1 -1
- package/dist/chunk-JNYV4RW3.mjs +1 -0
- package/dist/{chunk-6ZOPXG44.mjs → chunk-JUXYOKI2.mjs} +4 -4
- package/dist/{chunk-6NCRQ746.mjs → chunk-K3SNPW2B.mjs} +1 -1
- package/dist/{chunk-UMQ2SWSM.mjs → chunk-LVVHOJLW.mjs} +1 -1
- package/dist/{chunk-2OCUKD3K.mjs → chunk-MW4TLR2T.mjs} +1 -1
- package/dist/chunk-O7HHWVMT.mjs +1 -0
- package/dist/{chunk-BMMAZIUY.mjs → chunk-P5GCOROB.mjs} +1 -1
- package/dist/{chunk-2N25V56J.mjs → chunk-PYLSDRRO.mjs} +2 -2
- package/dist/chunk-QGH4LHSH.mjs +4 -0
- package/dist/{chunk-4HVQZC7R.mjs → chunk-QHGF2GC6.mjs} +1 -1
- package/dist/{chunk-76OM2ZBO.mjs → chunk-SRQQNHSX.mjs} +3 -3
- package/dist/chunk-UJP3Q23X.mjs +1 -0
- package/dist/{chunk-6RMN6EHY.mjs → chunk-UNDT7J2V.mjs} +1 -1
- package/dist/chunk-X3VVI7V3.mjs +1 -0
- package/dist/cli/index.js +175 -173
- package/dist/cli/index.mjs +15 -13
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
- package/dist/chunk-22PYMXSS.mjs +0 -1
- package/dist/chunk-52ZB3ZAG.mjs +0 -1
- package/dist/chunk-GKDZ7663.mjs +0 -1
- package/dist/chunk-II74EBLQ.mjs +0 -1
- package/dist/chunk-JBAV2AQK.mjs +0 -1
- package/dist/chunk-LT2DQLXJ.mjs +0 -1
- package/dist/chunk-QUJ2IZXU.mjs +0 -1
- package/dist/chunk-WE3NRBO6.mjs +0 -1
- package/dist/chunk-YHY7Y4HD.mjs +0 -4
- package/dist/chunk-YQVQTVHK.mjs +0 -2
package/dist/cli/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as Pn,b as on,c as bh,d as wh,e as xh,f as cn,g as Pt,h as Jh,i as yc,j as Sr,k as Cn,m as Kh}from"../chunk-
|
|
2
|
+
import{a as Pn,b as on,c as bh,d as wh,e as xh,f as cn,g as Pt,h as Jh,i as yc,j as Sr,k as Cn,m as Kh}from"../chunk-6ITUDSL7.mjs";import{a as vc,b as Ir,c as bc,g as Wh}from"../chunk-PYLSDRRO.mjs";import"../chunk-MDW42OG6.mjs";import{a as ei,b as Ch,c as Rh,d as Oh}from"../chunk-MPYL6HQR.mjs";import"../chunk-UNDT7J2V.mjs";import"../chunk-IK32U5FV.mjs";import{b as Zh,c as Gh}from"../chunk-SRQQNHSX.mjs";import"../chunk-MW4TLR2T.mjs";import{A as Fh,B as An,C as mc,D as $r,E as qh,F as Ke,G as le,I as It,J as Vh,Q as gc,R as dt,S as hc,X as Bh,Y as xe,Z as We,a as Y,b as ph,c as mh,d as ut,e as yh,h as Xo,i as kh,j as _h,l as Nh,m as Dh,n as jh,o as En,p as Uh,q as ti,r as _r,s as un,t as Tn,u as dc,v as ni,w as Lh,x as zh,y as pc,z as Mh}from"../chunk-JUXYOKI2.mjs";import{a as lc,c as kr}from"../chunk-TQFAYJEP.mjs";import"../chunk-4NWQCPI4.mjs";import{c as fc}from"../chunk-KUJJYP3K.mjs";import"../chunk-FAO3QJC5.mjs";import{a as we}from"../chunk-455C67EN.mjs";import{a as ac,b as Yg,c as Qg,e as Xg,f as eh,g as th,h as cc,i as nh,j as rh,l as ih}from"../chunk-CWBN2DOO.mjs";import"../chunk-CJDCY2NH.mjs";import{a as sh,c as ah,f as ch}from"../chunk-2XQXDEXA.mjs";import{d as uh,e as Yo,h as lh,k as dh}from"../chunk-XLK55DEY.mjs";import{a as fh,b as C,c as gh,e as Ie,f as se,h as hh,i as de}from"../chunk-LVVHOJLW.mjs";import{a as sn,b as uc,c as vh,d as an,e as Qo,f as xr,g as Th,h as lt,j as Me,l as Ah}from"../chunk-5WGVEULS.mjs";import{a as ne,b as $h,c as Sh,d as Ih,e as ze,f as wr,g as Ph}from"../chunk-I7YPDC7V.mjs";import{e as Eh}from"../chunk-OA73YMB6.mjs";import{a as oh}from"../chunk-JNYV4RW3.mjs";import"../chunk-P5GCOROB.mjs";import{b as Nt,c as In,d as Hg,e as rn,g as Ho,h as F}from"../chunk-UJP3Q23X.mjs";import{B as Bg,O as ic,Q as Jg,R as Ko,Y as sc,a as Go,c as Dg,ca as be,d as Vo,e as jg,fa as Kg,g as Ug,ga as Wo,h as Lg,ha as Wg,i as zg,j as Mg,k as Fg,m as rc,n as oc,o as Bo,p as Jo,t as qg,v as Zg,x as Gg,z as Vg}from"../chunk-QGH4LHSH.mjs";import"../chunk-GGXNXM73.mjs";import{a,c as St}from"../chunk-LJNU5QHZ.mjs";import{Command as cA}from"commander";import{realpathSync as uA}from"fs";import{pathToFileURL as lA}from"url";var Hh={"POST /v1/subscriptions/:subscriptionId/queue/purge":{confirm:"Purge ALL buffered messages in this queue? This cannot be undone."},"POST /v1/dlq/:dlqEntryId/discard":{confirm:"Discard this DLQ entry? The message will not be redelivered."},"POST /v1/dlq/discard":{confirm:"Bulk-discard DLQ entries? Discarded messages will not be redelivered."}};function Yh(e){return Hh[e]}a(Yh,"getOverride");var hA=Object.keys(Hh);var ge={OK:0,USER_ERROR:1,AUTH_ERROR:2,SERVER_ERROR:3,NETWORK_ERROR:4,PROTOCOL_ERROR:5},ck={auth:ge.AUTH_ERROR,deferred:ge.SERVER_ERROR,admission:ge.USER_ERROR,protocol:ge.PROTOCOL_ERROR},ey=`
|
|
3
3
|
Exit codes
|
|
4
4
|
0 ok
|
|
5
5
|
1 user error (bad args, missing file, a 4xx refusal of the request as issued)
|
|
@@ -163,20 +163,22 @@ export default defineConnectConfig({
|
|
|
163
163
|
`}a(Oc,"renderMcpConfig");function ui(e,t={}){let r=e.apiUrl?`
|
|
164
164
|
# API URL
|
|
165
165
|
NPAYLOAD_API_URL=${e.apiUrl}
|
|
166
|
-
`:"",o
|
|
166
|
+
`:"",o=`
|
|
167
|
+
# NPAYLOAD_AUTH_URL=<token host> (optional; with none named, the token is minted at the API's own /oauth/token)
|
|
168
|
+
`,n=e.transport??"npp",i=e.edgeUrl?`NPAYLOAD_EDGE_URL=${e.edgeUrl}
|
|
167
169
|
`:t.namesEdge?"":`# NPAYLOAD_EDGE_URL=<edge URL> (optional on npayload's production API, whose edge is the default; required for any other API)
|
|
168
|
-
`,
|
|
170
|
+
`,s=e.dpop?`
|
|
169
171
|
# Signing key for the secure transport (provisioned by \`npayload init\`).
|
|
170
172
|
NPAYLOAD_DPOP_KID=${e.dpop.kid}
|
|
171
173
|
NPAYLOAD_DPOP_PRIVATE_JWK=${JSON.stringify(e.dpop.privateJwk)}
|
|
172
|
-
`:"",
|
|
174
|
+
`:"",c=n==="http"?`
|
|
173
175
|
# Transport: HTTP/JSON (opted in via --http). Re-run \`npayload init\` for the default secure transport.
|
|
174
176
|
NPAYLOAD_TRANSPORT=http
|
|
175
177
|
`:`
|
|
176
178
|
# Transport: the default secure binary wire. The SDK provisions and registers a
|
|
177
179
|
# signing key automatically on first use \u2014 nothing for you to manage.
|
|
178
180
|
NPAYLOAD_TRANSPORT=npp
|
|
179
|
-
${
|
|
181
|
+
${i}`;return`# npayload credentials
|
|
180
182
|
# Created by: npayload init
|
|
181
183
|
${cn(e.clientId)?`# Not connected yet. These are PLACEHOLDERS \u2014 run \`npayload login\` to fill in
|
|
182
184
|
# your real app credentials. The project is safe to import; only the first
|
|
@@ -185,7 +187,7 @@ ${cn(e.clientId)?`# Not connected yet. These are PLACEHOLDERS \u2014 run \`npayl
|
|
|
185
187
|
NPAYLOAD_CLIENT_ID=${e.clientId}
|
|
186
188
|
NPAYLOAD_HMAC_SECRET=${e.hmacSecret}
|
|
187
189
|
NPAYLOAD_APP_ID=${e.appId}
|
|
188
|
-
${r}${
|
|
190
|
+
${r}${o}${c}${s}`}a(ui,"renderEnvFile");var li=["","# npayload \u2014 credentials (never commit)",".env",".npayload.json","# npayload \u2014 local machine state (regenerated; like .next/)",".npayload/"],Nc=["npayload/_generated/","npayload/_generated"];var my=[{step:1,do:"Check the project state: credentials, endpoint reachability, generated artifacts.",mcpTool:"npayload_status",cli:"npayload doctor",expect:"ok:true with a credential source present. If not, stop and show the user the remediation lines."},{step:2,do:"Fetch the config contract for the product you are wiring \u2014 Events (channels/eventTypes/subscriptions), Pipes (workflows/credentials), or Primus AI agents (agents/skills/tools/triggers). Each returns JSON Schema + capability catalog + guidance: the ONLY source for what that config may contain \u2014 never guess fields.",mcpTool:"events_contract / pipes_contract / primus_contract",cli:null,expect:"The schema you will author npayload/<product>.config.ts against."},{step:3,do:"Study the app's own data model (its schema/models/types) and design the topology in the product config(s): npayload/events.config.ts (channels, typed eventTypes, subscriptions), npayload/pipes.config.ts (workflows, vault-referenced credentials), npayload/primus.config.ts (agents, skills, tools, triggers).",mcpTool:null,cli:null,expect:"One default-exported define<Product>Config({...}) per product the app uses, reflecting its real domain."},{step:4,do:"Validate each config offline against its contract.",mcpTool:"events_validate / pipes_validate / primus_validate",cli:"npayload validate",expect:"ok:true per product. Fix every issue it returns before going further."},{step:5,do:"Preview the plan \u2014 nothing is applied.",mcpTool:"events_deploy / pipes_deploy / primus_deploy (check:true)",cli:"npayload diff",expect:"A plan of creates/updates/no-ops (and orphans). Review it; surprises here mean the config is wrong."},{step:6,do:"Apply to the sandbox. This also regenerates npayload/permissions.generated.ts (the per-object scope union across EVERY product config present) and npayload/_generated/events.d.ts (typed payloads).",mcpTool:"events_deploy / pipes_deploy / primus_deploy",cli:"npayload push",expect:"Resources reconciled; generated files updated. A second run is all no-ops (idempotent)."},{step:7,do:'Wire the app code: np.events.publish("<channel-slug>", payload) \u2014 payloads are typed by _generated/events.d.ts after the push; np.pipes.* / np.primus.* for the other products. Use events_usage for copy-ready runtime recipes; one-off operations on ANY product go through npayload_catalog \u2192 npayload_invoke.',mcpTool:"events_usage",cli:null,expect:"App code compiles against the generated payload types."},{step:8,do:"Prove it end to end: publish one real event from the app, watch it arrive.",mcpTool:null,cli:"npayload tail <channel-slug>",expect:"The published event printed live in the terminal."}],fy=["Never guess config fields or operations. The config schema comes from the product's contract tool (`events_contract` / `pipes_contract` / `primus_contract`, or `npayload validate`); the full operation surface comes from `npayload_catalog`. If it is not there, it does not exist.","Never edit anything under npayload/_generated/ or npayload/permissions.generated.ts \u2014 they are generated on push and committed; hand edits are overwritten and fail drift checks.","Never read, print, or edit .env or .npayload.json \u2014 credentials are already wired; tools and the CLI resolve them automatically.","Config references take the NATURAL identity, never an id: channel refs take the channel's SLUG (subscriptions[].channelGid, eventTypes[].channels, consumerGroups[].channelGid); a Primus trigger's agentGid and an agent's skills[] take the NAMES declared in the same config \u2014 all resolved to ids at push. Do not invent ids.","Event payload schemas (eventTypes[].schema) are append-only: changing one registers a NEW catalogue version on push; it never mutates the old version.","Primus naming rule: skill and tool names are lowercase + digits + underscores \u2014 a hyphenated name is rejected by the platform. Agent and trigger names may use hyphens.","Pipes lifecycle: a config-declared workflow is created as a DRAFT; activation is deliberate (dashboard, CLI, or pipes_create's activate flag for imperative builds). NEVER put a plaintext secret in pipes.config.ts \u2014 credentials carry a vault REFERENCE only.","`npayload push` / the *_deploy tools target the SANDBOX. Production is only `npayload deploy`, run deliberately by a human \u2014 never call it as an agent.","The .npayload/ directory (dot-prefixed) is local machine state written by `npayload pull`; its absence is normal. The committed workspace is npayload/ (no dot).","If a call fails, run npayload_status / `npayload doctor` first and act on its remediation \u2014 do not retry blindly or invent workarounds."],gy=[{path:"npayload/events.config.ts",what:"Events topology you author: channels, typed eventTypes, subscriptions. Committed."},{path:"npayload/pipes.config.ts",what:"Pipes topology you author: workflows + vault-referenced credentials. Committed."},{path:"npayload/primus.config.ts",what:"Primus (AI agents) topology you author: agents, skills, tools, triggers. Committed."},{path:"npayload/permissions.generated.ts",what:"Per-object permission model \u2014 the union across every product config present, generated on push. Committed, never hand-edited."},{path:"npayload/_generated/",what:"contract.lock + events.d.ts (typed payloads), generated on push. Committed, never hand-edited."},{path:"npayload/AGENTS.md",what:"This guide. Regenerated by `npx @npayload/sdk init`."},{path:".npayload/",what:"Local machine state (pull snapshots). Gitignored; absent until `npayload pull` runs."},{path:".env + .npayload.json",what:"Credentials. Gitignored; never read or edit them."},{path:".mcp.json",what:"Connects your editor's agent to the npayload MCP server."}];function hy(e){let t=["# npayload \u2014 guide for coding agents","",`<!-- Generated by \`npx @npayload/sdk init\` (@npayload/sdk@${e}). Re-run init to refresh. -->`,"","npayload is communication infrastructure for autonomous systems, and it is","configuration-driven: you author the product configs under `npayload/`","(`events.config.ts`, `pipes.config.ts`, `primus.config.ts`), validate them,","push them, and the platform reconciles everything else. There is nothing to","reverse-engineer \u2014 follow the loop below exactly. The npayload MCP server","(already wired via `.mcp.json`) serves the same loop as tools; start with","the `npayload_overview` tool when connected.","","## The workspace","","| Path | What it is |","|------|------------|",...gy.map(r=>`| \`${r.path}\` | ${r.what} |`),"","## The loop \u2014 do these steps in order",""];for(let r of my){let o=[r.mcpTool?`MCP \`${r.mcpTool}\``:null,r.cli?`CLI \`${r.cli}\``:null].filter(Boolean).join(" \xB7 ");t.push(`${r.step}. ${r.do}${o?` (${o})`:""}`),t.push(` Expect: ${r.expect}`)}return t.push("","## Hard rules","",...fy.map(r=>`- ${r}`),"","## Where facts come from (never from memory)","","- Config schema + capabilities: the product's contract tool \u2014 `events_contract` / `pipes_contract` / `primus_contract` \u2014 or `npayload validate` offline.","- Full operation surface (every product, incl. AI `primus.*` ops): `npayload_catalog` tool (invoke via `npayload_invoke`).","- Runtime code recipes: `events_usage` tool; imperative workflow building: `pipes_catalog` \u2192 `pipes_build` \u2192 `pipes_create` \u2192 `pipes_run` \u2192 `pipes_get_execution`.","- Project/stack health: `npayload_status` tool, or `npayload doctor`.",""),t.join(`
|
|
189
191
|
`)}a(hy,"renderAgentsMd");function yy(){return{workflow:my,rules:fy,workspace:gy}}a(yy,"overviewRails");import*as Mk from"fs";function Ye(e,t,r={}){let o=r.fs??Mk;if(o.existsSync(e)){try{o.chmodSync(e,384)}catch{}r.append?o.appendFileSync(e,t,"utf8"):o.writeFileSync(e,t,"utf8");return}o.writeFileSync(e,t,{encoding:"utf8",mode:384})}a(Ye,"writeSecretFile");function vy(e,t,r={}){let o=ln(e,"npayload"),n=[],i=[],s=[],c=[];t.dpop||(t.dpop=Tr(e)??ci());let u=[o,ln(o,"_generated")];for(let m of u)r.dryRun||Fk(m,{recursive:!0}),c.push(m.replace(e+"/",""));let l=[["npayload.toml",py(t,r.firstEnv??"sandbox")],["npayload/events.config.ts",Tc(t)],["npayload/primus.config.ts",Ac(t)],["npayload/pipes.config.ts",Cc(t)],["npayload/connect.config.ts",Rc(t)],["npayload/_generated/contract.lock",Ar(t)],["npayload/AGENTS.md",hy(an())],[".mcp.json",Oc(t)]],d=new Set(["npayload/AGENTS.md"]);for(let[m,p]of l){let f=ln(e,m);if(n.push(m),Cr(f)&&!r.force&&!d.has(m)){s.push(m);continue}r.dryRun||di(f,p,"utf8"),i.push(m)}return n.push(".env",".npayload.json"),r.dryRun?n.push():(Zk(e,t,r.force)?i.push(".env"):s.push(".env"),Gk(e,t,r.force)?i.push(".npayload.json"):s.push(".npayload.json"),Vk(e)&&i.push("package.json"),jc(e)),{files:n,written:i,skipped:s,directories:c}}a(vy,"scaffold");function Zk(e,t,r){let o=ln(e,".env");if(Cr(o)){let n=Dc(o,"utf8");if(n.includes("NPAYLOAD_CLIENT_ID")&&!r||n.includes("NPAYLOAD_CLIENT_ID")&&r)return!1;let i=Yo(n),s=ui(t,{namesEdge:!!i.NPAYLOAD_EDGE_URL?.trim()});return Ye(o,`
|
|
190
192
|
`+s,{append:!0}),!0}return Ye(o,ui(t)),!0}a(Zk,"writeEnvFile");function Gk(e,t,r){let o=ln(e,".npayload.json");if(Cr(o)&&!r)return!1;let n={clientId:t.clientId,hmacSecret:t.hmacSecret,...t.targetEnv?{targetEnv:t.targetEnv}:{}};return t.dpop&&(n.dpopKid=t.dpop.kid,n.dpopPrivateJwk=t.dpop.privateJwk,n.dpopPublicJwk=t.dpop.publicJwk),Ye(o,JSON.stringify(n,null,2)+`
|
|
191
193
|
`),!0}a(Gk,"writeProjectCredentials");function Vk(e){let t=ln(e,"package.json");if(!Cr(t))return!1;let r=vh();if(!r)return!1;let o=Dc(t,"utf8"),n;try{n=JSON.parse(o)}catch{return!1}let i=!1;for(let c of["dependencies","devDependencies"]){let u=n[c];if(!u||typeof u!="object")continue;let l=u;if(uc.some(d=>typeof l[d]=="string")){let d={};for(let[m,p]of Object.entries(l))uc.includes(m)&&typeof p=="string"?!(sn in d)&&!(sn in l)&&(d[sn]=r):d[m]=p;n[c]=l=d,i=!0}typeof l[sn]=="string"&&l[sn]!==r&&(l[sn]=r,i=!0)}if(!i)return!1;let s=/^(\s+)"/m.exec(o)?.[1]??" ";return di(t,JSON.stringify(n,null,s)+(o.endsWith(`
|
|
@@ -241,7 +243,7 @@ After 6 months post-GA this command exits non-zero; set NPAYLOAD_FEDERATION_HARD
|
|
|
241
243
|
`));for(let v of g)process.stderr.write(` ${Ge.yellow(v.path)} ${v.message}
|
|
242
244
|
`);process.exit(1)}let i=t.config??We(),s=await le(i),u=Jr(s,{allowInternalUrls:n}),l=yv(s);if(l.length>0&&(u.ok=!1,u.issues.push(...l)),u.ok){process.stdout.write(Ge.green.bold(`\u2713 events.config is valid.
|
|
243
245
|
`));let d=hv(process.cwd(),"npayload","_generated","contract.lock");if(Z$(d))try{JSON.parse(G$(d,"utf8")).hash!==Sr&&process.stdout.write(Ge.yellow(`! contract.lock was pinned against a different npayload contract \u2014 re-validate after upgrading.
|
|
244
|
-
`))}catch{process.stdout.write(Ge.yellow("! contract.lock is unreadable \u2014 regenerate via `npayload init`.\n"))}let m=hv(i,"..","permissions.generated.ts"),{projectAllPermissions:p}=await import("../chunk-
|
|
246
|
+
`))}catch{process.stdout.write(Ge.yellow("! contract.lock is unreadable \u2014 regenerate via `npayload init`.\n"))}let m=hv(i,"..","permissions.generated.ts"),{projectAllPermissions:p}=await import("../chunk-CNAIHF3M.mjs"),{checkScopesDrift:f}=await import("../chunk-A7HA64P6.mjs"),g=f(await p(),m);!g.ok&&g.reason&&process.stdout.write(Ge.yellow(`! ${g.reason}
|
|
245
247
|
`)),process.exit(0)}process.stderr.write(Ge.red.bold(`\u2717 events.config has ${u.issues.length} problem(s):
|
|
246
248
|
`));for(let d of u.issues){let m=d.allowed?Ge.dim(` allowed: ${JSON.stringify(d.allowed)}`):"";process.stderr.write(` ${Ge.yellow(d.path)} ${d.message}${m}
|
|
247
249
|
`)}process.exit(1)}catch(r){let o=r instanceof Error?r.message:String(r);process.stderr.write(Ge.red(`validate failed: ${o}
|
|
@@ -507,9 +509,9 @@ you declare in connect.config.ts is identity BRIDGES \u2014 declare them and run
|
|
|
507
509
|
access grants, tenant approvals) is managed through the np.connect.* SDK calls above \u2014 use
|
|
508
510
|
connect_usage for copy-ready snippets. The cross-org HANDSHAKE stays imperative regardless: a
|
|
509
511
|
bridge/grant you declare is an OFFER (pending) until the other org confirms in ITS own config \u2014
|
|
510
|
-
declarative intent, never auto-consent.`;function en(){return zi()}a(en,"allowInternalUrls");function N(e){return{content:[{type:"text",text:typeof e=="string"?e:JSON.stringify(e,null,2)}]}}a(N,"text");function ce(e,t={}){let r=e?.code;return{...N({ok:!1,...typeof r=="string"?{code:r}:{},type:e instanceof Error?e.name:typeof e,error:e instanceof Error?e.message:String(e),...t}),isError:!0}}a(ce,"toolFailure");function Xw(e){let t=e,r=t?.details?.errors;if(!(!t||!Array.isArray(r))&&!(t.code!=="PIPE_DEFINITION_INVALID"&&t.status!==400))return{ok:!1,code:typeof t.code=="string"?t.code:"PIPE_DEFINITION_INVALID",message:typeof t.message=="string"?t.message:"The pipe definition is not valid.",errors:r,schemaVersion:No,retry:!0,next:"Fix each reason at its path, then call pipes_validate_definition (or pipes_create) again.",...typeof t.requestId=="string"?{requestId:t.requestId}:{}}}a(Xw,"pipeDefinitionRefusal");function ug(){for(let e of["connect.config.ts","connect.config.mjs","connect.config.js","npayload/connect.config.ts","npayload/connect.config.mjs","npayload/connect.config.js"]){let t=Yw(process.cwd(),e);if(ex(t))return t}return Yw(process.cwd(),"connect.config.ts")}a(ug,"findConnectConfig");function fE(){let e=new lE({name:"npayload",version:an()});e.tool("npayload_overview","Call this FIRST, before anything else. Returns the complete deterministic map for working on this npayload project: current project state (config found, credential source, generated artifacts), the exact ordered end-to-end workflow (each step names the MCP tool AND the CLI command), and the hard rules. Follow it step by step \u2014 never guess, never reverse-engineer.",async()=>{let p=null;try{p=We()}catch{p=null}let f=a(v=>ex(cE(process.cwd(),v)),"gen"),g=null;try{let{resolveCredentials:v}=await import("../chunk-5SMWYS7Z.mjs");g=(await v()).source}catch{g=null}return N({version:an(),state:{eventsConfig:p,credentialSource:g,generated:{contractLock:f("npayload/_generated/contract.lock"),typedEventPayloads:f("npayload/_generated/events.d.ts"),permissions:f("npayload/permissions.generated.ts")},note:g===null?"No credential source \u2014 run `npx @npayload/sdk init` in this project (or `npayload doctor` for diagnosis) before any deploy/status call.":"Credentials resolve automatically; never read or edit .env / .npayload.json."},...yy()})}),e.tool("events_contract","Return the npayload Events config schema (JSON Schema) + the capability catalog + decision guide + guidance. Call this BEFORE writing or editing events.config.ts \u2014 the schema returned here is the only valid source of config fields (after npayload_overview).",async()=>N({version:Sr,guidance:pE,capabilities:Iw,schema:Cn})),e.tool("events_usage","Return server-side, copy-ready RUNTIME recipes for using Events from app code (publish variants, queue/outbox consume, streams, KV, webhook verification, catalogue, exchanges, consumer groups, DLQ, snapshots, privacy, NPP). Call this when writing the app code (not just the topology). Optionally pass a feature key to get one recipe.",{feature:S.string().optional().describe('a recipe key (e.g. "queueConsume", "webhookVerify"); omit to get all recipes')},async({feature:p})=>p&&Ro[p]?N(Ro[p]):N(p?{error:`unknown feature "${p}"`,available:Object.keys(Ro)}:{version:Sr,recipes:Ro})),e.tool("events_validate","Validate an Events config against the contract (structure + security). Pass the config object, OR omit it to validate the project's events.config.ts on disk. Returns { ok, issues } with precise, fixable problems.",{config:S.union([S.record(S.string(),S.unknown()),S.string()]).optional().describe("the EventsConfig object (or a JSON string) to validate; omit to validate events.config.ts on disk"),configPath:S.string().optional().describe("path to events.config.ts (used when `config` is omitted)")},async({config:p,configPath:f})=>{let g=p;if(typeof g=="string")try{g=JSON.parse(g)}catch{}g==null&&(g=await le(f??We()));let v=Jr(g,{allowInternalUrls:en()});return{...N(v),isError:!v.ok}}),e.tool("events_deploy","Reconcile the project's events.config.ts to your deployment (idempotent). Validates first; pass check:true for a dry-run plan. Mutating: confirm before applying.",{check:S.boolean().optional().describe("dry run: print the plan, apply nothing"),configPath:S.string().optional().describe("path to events.config.ts (default: ./events.config.ts or ./npayload/events.config.ts)")},async({check:p,configPath:f})=>{let g=f??We(),v=await le(g),h=Jr(v,{allowInternalUrls:en()});if(!h.ok)return{...N({error:"config invalid \u2014 fix before deploy",issues:h.issues}),isError:!0};try{let x=await xe({config:g,check:p??!1,sink:a(()=>{},"sink")});return N(x.output)}catch(x){return ce(x)}}),e.tool("events_status","Show the current sync state between events.config.ts and your deployment (a dry-run plan: what exists, what would change).",{configPath:S.string().optional()},async({configPath:p})=>{let f=p??We();try{let g=await xe({config:f,check:!0,sink:a(()=>{},"sink")});return N(g.output)}catch(g){return ce(g)}}),e.tool("connect_contract","Return what npayload Connect can do (cross-org event sharing): the connect.config.ts schema (JSON Schema) + the capability catalog + decision guide + guidance. Call FIRST to learn how to write connect.config.ts and drive the np.connect.* SDK.",async()=>N({version:ru,guidance:mE,capabilities:Cw,schema:Ui})),e.tool("pipes_contract","Return the npayload Pipes config schema (JSON Schema) + the capability catalog + decision guide + guidance. Call this BEFORE writing or editing pipes.config.ts \u2014 the schema returned here is the only valid source of config fields.",async()=>N({version:pv,guidance:Pw,capabilities:Ew,schema:Li})),e.tool("connect_usage","Return server-side, copy-ready RUNTIME recipes for driving Connect from app code (set profile, explore, request/approve access grants, identity bridges, tenant approvals). Call this when writing the cross-org integration. Optionally pass a feature key to get one recipe.",{feature:S.string().optional().describe('a recipe key (e.g. "requestAccess", "createBridge"); omit to get all recipes')},async({feature:p})=>p&&Oo[p]?N(Oo[p]):N(p?{error:`unknown feature "${p}"`,available:Object.keys(Oo)}:{version:ru,recipes:Oo})),e.tool("connect_validate","Validate a connect.config.ts against the contract (structure + security). Pass the config object, OR omit it to validate the project's connect.config.ts on disk. Returns { ok, issues } with precise, fixable problems.",{config:S.union([S.record(S.string(),S.unknown()),S.string()]).optional().describe("the ConnectConfig object (or a JSON string) to validate; omit to validate connect.config.ts on disk"),configPath:S.string().optional().describe("path to connect.config.ts (used when `config` is omitted)")},async({config:p,configPath:f})=>{let g=p;if(typeof g=="string")try{g=JSON.parse(g)}catch{}g==null&&(g=await le(f??ug()));let v=ou(g,{allowInternalUrls:en()});return{...N(v),isError:!v.ok}}),e.tool("pipes_validate","Validate a Pipes config against the contract (structure + security). Pass the config object, OR omit it to validate the project's pipes.config.ts on disk. Returns { ok, issues } with precise, fixable problems.",{config:S.union([S.record(S.string(),S.unknown()),S.string()]).optional().describe("the PipesConfig object (or a JSON string) to validate; omit to validate pipes.config.ts on disk"),configPath:S.string().optional().describe("path to pipes.config.ts (used when `config` is omitted)")},async({config:p,configPath:f})=>{let g=p;if(typeof g=="string")try{g=JSON.parse(g)}catch{}if(g==null){let h=f??Ke("pipes");if(!h)return{...N({ok:!1,error:"no pipes.config.ts found \u2014 write npayload/pipes.config.ts first (see pipes_contract)"}),isError:!0};g=await le(h)}let v=Kr(g,{allowInternalUrls:en()});return{...N(v),isError:!v.ok}}),e.tool("pipes_deploy","Reconcile the project's pipes.config.ts to your deployment (idempotent, keyed by name). Validates first; pass check:true for a dry-run plan. Mutating: confirm before applying. Governance is admin-gated \u2014 a machine credential gets a clear 'needs admin' note, not a failure.",{check:S.boolean().optional().describe("dry run: print the plan, apply nothing"),configPath:S.string().optional().describe("path to pipes.config.ts (default: ./npayload/pipes.config.ts)")},async({check:p,configPath:f})=>{let g=f??Ke("pipes");if(!g)return{...N({ok:!1,error:"no pipes.config.ts found \u2014 write npayload/pipes.config.ts first (see pipes_contract)"}),isError:!0};let v=await le(g),h=Kr(v,{allowInternalUrls:en()});if(!h.ok)return{...N({error:"config invalid \u2014 fix before deploy",issues:h.issues}),isError:!0};try{let x=await xe({config:g,check:p??!1,sink:a(()=>{},"sink")});return N(x.output)}catch(x){return ce(x)}}),e.tool("pipes_status","Show the current sync state between pipes.config.ts and your deployment (a dry-run plan: what exists, what would change).",{configPath:S.string().optional()},async({configPath:p})=>{let f=p??Ke("pipes");if(!f)return{...N({ok:!1,error:"no pipes.config.ts found"}),isError:!0};try{let g=await xe({config:f,check:!0,sink:a(()=>{},"sink")});return N(g.output)}catch(g){return ce(g)}});let t=a(async p=>{let{buildKernel:f}=await import("../chunk-2PCG57PX.mjs"),g=await f(),v=await Qw(g,p);if(!v)throw new Error("could not resolve appId from token; pass appId (app_\u2026)");return{kernel:g,appId:v}},"kernelAndApp"),r=a(p=>{let f=p;return f?.gid??f?.workflowGid??f?.data?.gid},"wfId"),o=6e4,n=new Map,i=a(async(p,f)=>{let g=n.get(f);if(g&&Date.now()-g.at<o)return g;let v=await p.send(_t("pipes.workflows.listConnectors")),h=v?.data??v??[],x={at:Date.now(),rows:h,index:Vw(h)};return n.set(f,x),x},"fetchConnectorCatalog"),s=a((p,f)=>{try{let v=new uE({allErrors:!0,strict:!1}).compile(p);return v(f)?[]:(v.errors??[]).map(h=>`${h.instancePath||"(root)"} ${h.message??"invalid"}${h.params?` ${JSON.stringify(h.params)}`:""}`)}catch{return[]}},"ajvValidator"),c=a(async(p,f)=>{try{let{kernel:g,appId:v}=await t(f),{index:h}=await i(g,v);return{...sg(p,h,s),catalogReachable:!0}}catch(g){F(g);let v=sg(p,void 0);return{...v,warnings:[...v.warnings,"deployment unreachable \u2014 connector ids, actionIds, and params were NOT verified against the live catalog; pipes_create will verify them"],catalogReachable:!1}}},"validateAgainstLive");e.tool("pipes_catalog","Return the Pipes authoring guide + the LIVE connector catalog from your deployment: every connector, every action, and each action's FULL JSON-Schema (all params, types, enums, required) \u2014 plus the branch-handle map and the valid trigger types. Call FIRST so you author with the real, current params (no guessing).",{appId:S.string().optional().describe("app GID (app_\u2026); defaults to the token's app claim")},async({appId:p})=>{try{let{kernel:f,appId:g}=await t(p),{rows:v}=await i(f,g);return N({guidance:Zw,definitionSchema:{id:Rw,version:No,resource:rg},triggerTypes:Uo,triggers:Do,branchHandles:Yt,builtinNodeTypes:Object.entries(Xt).map(([h,x])=>({nodeType:h,backendType:x,isBrancher:h===Qt||h in Yt})),connectors:v.map(h=>({connectorId:h.id??h.connectorId??h._id,category:h.category,description:h.description,tier:h.tier,needsCredential:h.auth?.type&&h.auth.type!=="none",branchHandles:Yt[h.id??h.connectorId]??((h.id??h.connectorId)===Qt?["<case name>",mr]:void 0),actions:(h.actions??[]).map(x=>({actionId:x.id,name:x.name,description:x.description,inputSchema:x.inputSchema,outputSchema:x.outputSchema}))}))})}catch(f){return ce(f)}});let u=Do.map(p=>p.type).join("|"),l=[...Object.entries(Yt).map(([p,f])=>`${p} ${f.join("/")}`),`${Qt} <case>/${mr}`].join(", "),d=S.object({id:S.string().describe("unique node id"),nodeType:S.string().describe(`the type the engine runs (data.nodeType): a trigger (${u}), a built-in (${Object.keys(Xt).filter(p=>Xt[p]!=="trigger").join("|")}), or "${kt}" for a catalogue connector (then set connectorId from pipes_catalog; it is checked against the live catalogue). Built-ins: ${Lw}`),connectorId:S.string().optional().describe(`REQUIRED when nodeType is "${kt}": the connector id from pipes_catalog`),config:S.record(S.string(),S.unknown()).optional().describe(`data.config. A trigger: its trigger config keys (${Do.map(p=>`${p.type}: ${p.summary}`).join(" ")}). A built-in: its settings, flat. A connector step: ${Ia} \u2014 the action id from pipes_catalog and its params, typed by that action's inputSchema, under params (data.config.params, the only place the engine reads them).`),credentials:S.record(S.string(),S.string()).optional().describe("a connector step's credentials: { <connectorId>: <credential gid> } (data.credentials)"),label:S.string().optional()}),m=S.object({from:S.string(),to:S.string(),branch:S.string().optional().describe(`the branch a brancher is left by (${l}); omit for a step without branches`)});return e.tool("pipes_build","Compile a HIGH-LEVEL pipe spec into a CORRECT workflow definition (connector-schema nodes + explicit edge handles + branch resolution + auto-layout) AND validate it against the LIVE deployment catalog: every connectorId must exist, every actionId must be one of that connector's actions, and connector params are checked against the action's real inputSchema \u2014 so a guessed name fails HERE with a did-you-mean, not at run time. NEVER hand-write node/edge JSON \u2014 use this. Returns { definition, warnings }.",{nodes:S.array(d).describe("the steps"),edges:S.array(m).optional().describe("how steps connect"),appId:S.string().optional().describe("app GID (app_\u2026); defaults to the token's app claim \u2014 used to fetch the live connector catalog for validation")},async({appId:p,...f})=>{try{let g=og(f),v=await c(f,p);if(!v.ok)return{...N({ok:!1,stage:"catalog-validation",issues:v.issues,warnings:v.warnings}),isError:!0};let h=ig(f);return N({ok:!0,definition:g,triggerConfig:h,...v.warnings.length?{warnings:v.warnings}:{}})}catch(g){return ce(g)}}),e.tool("pipes_create",`Create a pipe in your deployment from a high-level spec (the same spec as pipes_build) and optionally activate it. Mutating; confirm first. Include exactly ONE trigger node (nodeType ${u}) as the ENTRY node (no incoming edge) wired to the first step; the trigger config is derived from it (or omit the trigger node and pass triggerType + triggerConfig). The door validates the whole definition before it writes anything; a refusal returns PIPE_DEFINITION_INVALID with every reason (path, expected, got) and retry: true.`,{name:S.string(),description:S.string().optional(),nodes:S.array(d),edges:S.array(m).optional(),triggerType:S.enum(Uo).optional().describe("the single workflow trigger (default manual)"),triggerConfig:S.record(S.string(),S.unknown()).optional().describe(`the trigger's config when the spec has no trigger node (${Do.map(p=>`${p.type}: ${p.summary}`).join(" ")})`),activate:S.boolean().optional(),appId:S.string().optional()},async p=>{try{let f;try{f=og({nodes:p.nodes,edges:p.edges})}catch(k){return ce(k,{stage:"build"})}let g=await c({nodes:p.nodes,edges:p.edges},p.appId);if(!g.catalogReachable)return{...N({ok:!1,stage:"catalog-validation",error:"could not fetch the connector catalog from your deployment \u2014 pipes_create refuses to create unverified workflows",warnings:g.warnings}),isError:!0};if(!g.ok)return{...N({ok:!1,stage:"catalog-validation",issues:g.issues,warnings:g.warnings}),isError:!0};let v=ig({nodes:p.nodes,edges:p.edges},{type:p.triggerType,config:p.triggerConfig}),{kernel:h}=await t(p.appId),x;try{x=await h.send({..._t("pipes.workflows.createWorkflow"),body:{name:p.name,description:p.description??"",definition:f,triggerConfig:v}})}catch(k){let O=Xw(k);if(O)return{...N({...O,stage:"door"}),isError:!0};throw k}let E=r(x);return p.activate&&E&&await h.send({..._t("pipes.workflows.activateWorkflow"),pathParams:{workflowId:E},body:{}}),N({ok:!0,workflowId:E,activated:!!(p.activate&&E),nodes:f.nodes.length,edges:f.edges.length,...g.warnings.length?{warnings:g.warnings}:{}})}catch(f){return ce(f)}}),e.tool("pipes_validate_definition","Validate a pipe definition and trigger config against your deployment WITHOUT saving anything: the door applies every check it applies on create (the one pipe definition schema, your live connector catalogue, params against each action's inputSchema, credentials, branches, one reachable trigger). Pass the { definition, triggerConfig } pipes_build returned. Answers { valid: true } or PIPE_DEFINITION_INVALID with every reason (path, expected, got, didYouMean) and retry: true.",{definition:S.record(S.string(),S.unknown()).describe("the pipe definition { nodes, edges } (pipes_build's definition)"),triggerConfig:S.record(S.string(),S.unknown()).optional().describe("the trigger config { type, config } (pipes_build's triggerConfig)"),appId:S.string().optional()},async({definition:p,triggerConfig:f,appId:g})=>{try{let{kernel:v}=await t(g),h;try{h=await v.send({..._t("pipes.workflows.validateWorkflowDefinition"),body:{definition:p,...f?{triggerConfig:f}:{}}})}catch(E){let k=Xw(E);if(k)return{...N({...k,stage:"door",valid:!1}),isError:!0};throw E}let x=h?.data??h;return N({ok:!0,valid:x?.valid??!0,errors:x?.errors??[],schemaVersion:No})}catch(v){return ce(v)}}),e.resource("pipes-authoring-flow",Mw,{description:"How to author a pipe, step by step: discover the connectors, read their input schemas, draft, validate, create, run, inspect, iterate.",mimeType:"text/plain"},async p=>({contents:[{uri:p.href,mimeType:"text/plain",text:jo}]})),e.resource("pipes-definition-schema",rg,{description:`The pipe definition JSON Schema ${No} every pipes tool is generated from and the door validates against.`,mimeType:"application/schema+json"},async p=>({contents:[{uri:p.href,mimeType:"application/schema+json",text:JSON.stringify(qw,null,2)}]})),e.prompt(Fw,"Author an npayload pipe with the pipes tools, following the pipe-authoring flow.",{goal:S.string().optional().describe("what the pipe should do, in your words")},({goal:p})=>({messages:[{role:"user",content:{type:"text",text:`${p?`Build an npayload pipe that does this: ${p}
|
|
512
|
+
declarative intent, never auto-consent.`;function en(){return zi()}a(en,"allowInternalUrls");function N(e){return{content:[{type:"text",text:typeof e=="string"?e:JSON.stringify(e,null,2)}]}}a(N,"text");function ce(e,t={}){let r=e?.code;return{...N({ok:!1,...typeof r=="string"?{code:r}:{},type:e instanceof Error?e.name:typeof e,error:e instanceof Error?e.message:String(e),...t}),isError:!0}}a(ce,"toolFailure");function Xw(e){let t=e,r=t?.details?.errors;if(!(!t||!Array.isArray(r))&&!(t.code!=="PIPE_DEFINITION_INVALID"&&t.status!==400))return{ok:!1,code:typeof t.code=="string"?t.code:"PIPE_DEFINITION_INVALID",message:typeof t.message=="string"?t.message:"The pipe definition is not valid.",errors:r,schemaVersion:No,retry:!0,next:"Fix each reason at its path, then call pipes_validate_definition (or pipes_create) again.",...typeof t.requestId=="string"?{requestId:t.requestId}:{}}}a(Xw,"pipeDefinitionRefusal");function ug(){for(let e of["connect.config.ts","connect.config.mjs","connect.config.js","npayload/connect.config.ts","npayload/connect.config.mjs","npayload/connect.config.js"]){let t=Yw(process.cwd(),e);if(ex(t))return t}return Yw(process.cwd(),"connect.config.ts")}a(ug,"findConnectConfig");function fE(){let e=new lE({name:"npayload",version:an()});e.tool("npayload_overview","Call this FIRST, before anything else. Returns the complete deterministic map for working on this npayload project: current project state (config found, credential source, generated artifacts), the exact ordered end-to-end workflow (each step names the MCP tool AND the CLI command), and the hard rules. Follow it step by step \u2014 never guess, never reverse-engineer.",async()=>{let p=null;try{p=We()}catch{p=null}let f=a(v=>ex(cE(process.cwd(),v)),"gen"),g=null;try{let{resolveCredentials:v}=await import("../chunk-5SMWYS7Z.mjs");g=(await v()).source}catch{g=null}return N({version:an(),state:{eventsConfig:p,credentialSource:g,generated:{contractLock:f("npayload/_generated/contract.lock"),typedEventPayloads:f("npayload/_generated/events.d.ts"),permissions:f("npayload/permissions.generated.ts")},note:g===null?"No credential source \u2014 run `npx @npayload/sdk init` in this project (or `npayload doctor` for diagnosis) before any deploy/status call.":"Credentials resolve automatically; never read or edit .env / .npayload.json."},...yy()})}),e.tool("events_contract","Return the npayload Events config schema (JSON Schema) + the capability catalog + decision guide + guidance. Call this BEFORE writing or editing events.config.ts \u2014 the schema returned here is the only valid source of config fields (after npayload_overview).",async()=>N({version:Sr,guidance:pE,capabilities:Iw,schema:Cn})),e.tool("events_usage","Return server-side, copy-ready RUNTIME recipes for using Events from app code (publish variants, queue/outbox consume, streams, KV, webhook verification, catalogue, exchanges, consumer groups, DLQ, snapshots, privacy, NPP). Call this when writing the app code (not just the topology). Optionally pass a feature key to get one recipe.",{feature:S.string().optional().describe('a recipe key (e.g. "queueConsume", "webhookVerify"); omit to get all recipes')},async({feature:p})=>p&&Ro[p]?N(Ro[p]):N(p?{error:`unknown feature "${p}"`,available:Object.keys(Ro)}:{version:Sr,recipes:Ro})),e.tool("events_validate","Validate an Events config against the contract (structure + security). Pass the config object, OR omit it to validate the project's events.config.ts on disk. Returns { ok, issues } with precise, fixable problems.",{config:S.union([S.record(S.string(),S.unknown()),S.string()]).optional().describe("the EventsConfig object (or a JSON string) to validate; omit to validate events.config.ts on disk"),configPath:S.string().optional().describe("path to events.config.ts (used when `config` is omitted)")},async({config:p,configPath:f})=>{let g=p;if(typeof g=="string")try{g=JSON.parse(g)}catch{}g==null&&(g=await le(f??We()));let v=Jr(g,{allowInternalUrls:en()});return{...N(v),isError:!v.ok}}),e.tool("events_deploy","Reconcile the project's events.config.ts to your deployment (idempotent). Validates first; pass check:true for a dry-run plan. Mutating: confirm before applying.",{check:S.boolean().optional().describe("dry run: print the plan, apply nothing"),configPath:S.string().optional().describe("path to events.config.ts (default: ./events.config.ts or ./npayload/events.config.ts)")},async({check:p,configPath:f})=>{let g=f??We(),v=await le(g),h=Jr(v,{allowInternalUrls:en()});if(!h.ok)return{...N({error:"config invalid \u2014 fix before deploy",issues:h.issues}),isError:!0};try{let x=await xe({config:g,check:p??!1,sink:a(()=>{},"sink")});return N(x.output)}catch(x){return ce(x)}}),e.tool("events_status","Show the current sync state between events.config.ts and your deployment (a dry-run plan: what exists, what would change).",{configPath:S.string().optional()},async({configPath:p})=>{let f=p??We();try{let g=await xe({config:f,check:!0,sink:a(()=>{},"sink")});return N(g.output)}catch(g){return ce(g)}}),e.tool("connect_contract","Return what npayload Connect can do (cross-org event sharing): the connect.config.ts schema (JSON Schema) + the capability catalog + decision guide + guidance. Call FIRST to learn how to write connect.config.ts and drive the np.connect.* SDK.",async()=>N({version:ru,guidance:mE,capabilities:Cw,schema:Ui})),e.tool("pipes_contract","Return the npayload Pipes config schema (JSON Schema) + the capability catalog + decision guide + guidance. Call this BEFORE writing or editing pipes.config.ts \u2014 the schema returned here is the only valid source of config fields.",async()=>N({version:pv,guidance:Pw,capabilities:Ew,schema:Li})),e.tool("connect_usage","Return server-side, copy-ready RUNTIME recipes for driving Connect from app code (set profile, explore, request/approve access grants, identity bridges, tenant approvals). Call this when writing the cross-org integration. Optionally pass a feature key to get one recipe.",{feature:S.string().optional().describe('a recipe key (e.g. "requestAccess", "createBridge"); omit to get all recipes')},async({feature:p})=>p&&Oo[p]?N(Oo[p]):N(p?{error:`unknown feature "${p}"`,available:Object.keys(Oo)}:{version:ru,recipes:Oo})),e.tool("connect_validate","Validate a connect.config.ts against the contract (structure + security). Pass the config object, OR omit it to validate the project's connect.config.ts on disk. Returns { ok, issues } with precise, fixable problems.",{config:S.union([S.record(S.string(),S.unknown()),S.string()]).optional().describe("the ConnectConfig object (or a JSON string) to validate; omit to validate connect.config.ts on disk"),configPath:S.string().optional().describe("path to connect.config.ts (used when `config` is omitted)")},async({config:p,configPath:f})=>{let g=p;if(typeof g=="string")try{g=JSON.parse(g)}catch{}g==null&&(g=await le(f??ug()));let v=ou(g,{allowInternalUrls:en()});return{...N(v),isError:!v.ok}}),e.tool("pipes_validate","Validate a Pipes config against the contract (structure + security). Pass the config object, OR omit it to validate the project's pipes.config.ts on disk. Returns { ok, issues } with precise, fixable problems.",{config:S.union([S.record(S.string(),S.unknown()),S.string()]).optional().describe("the PipesConfig object (or a JSON string) to validate; omit to validate pipes.config.ts on disk"),configPath:S.string().optional().describe("path to pipes.config.ts (used when `config` is omitted)")},async({config:p,configPath:f})=>{let g=p;if(typeof g=="string")try{g=JSON.parse(g)}catch{}if(g==null){let h=f??Ke("pipes");if(!h)return{...N({ok:!1,error:"no pipes.config.ts found \u2014 write npayload/pipes.config.ts first (see pipes_contract)"}),isError:!0};g=await le(h)}let v=Kr(g,{allowInternalUrls:en()});return{...N(v),isError:!v.ok}}),e.tool("pipes_deploy","Reconcile the project's pipes.config.ts to your deployment (idempotent, keyed by name). Validates first; pass check:true for a dry-run plan. Mutating: confirm before applying. Governance is admin-gated \u2014 a machine credential gets a clear 'needs admin' note, not a failure.",{check:S.boolean().optional().describe("dry run: print the plan, apply nothing"),configPath:S.string().optional().describe("path to pipes.config.ts (default: ./npayload/pipes.config.ts)")},async({check:p,configPath:f})=>{let g=f??Ke("pipes");if(!g)return{...N({ok:!1,error:"no pipes.config.ts found \u2014 write npayload/pipes.config.ts first (see pipes_contract)"}),isError:!0};let v=await le(g),h=Kr(v,{allowInternalUrls:en()});if(!h.ok)return{...N({error:"config invalid \u2014 fix before deploy",issues:h.issues}),isError:!0};try{let x=await xe({config:g,check:p??!1,sink:a(()=>{},"sink")});return N(x.output)}catch(x){return ce(x)}}),e.tool("pipes_status","Show the current sync state between pipes.config.ts and your deployment (a dry-run plan: what exists, what would change).",{configPath:S.string().optional()},async({configPath:p})=>{let f=p??Ke("pipes");if(!f)return{...N({ok:!1,error:"no pipes.config.ts found"}),isError:!0};try{let g=await xe({config:f,check:!0,sink:a(()=>{},"sink")});return N(g.output)}catch(g){return ce(g)}});let t=a(async p=>{let{buildKernel:f}=await import("../chunk-6BBB7BRP.mjs"),g=await f(),v=await Qw(g,p);if(!v)throw new Error("could not resolve appId from token; pass appId (app_\u2026)");return{kernel:g,appId:v}},"kernelAndApp"),r=a(p=>{let f=p;return f?.gid??f?.workflowGid??f?.data?.gid},"wfId"),o=6e4,n=new Map,i=a(async(p,f)=>{let g=n.get(f);if(g&&Date.now()-g.at<o)return g;let v=await p.send(_t("pipes.workflows.listConnectors")),h=v?.data??v??[],x={at:Date.now(),rows:h,index:Vw(h)};return n.set(f,x),x},"fetchConnectorCatalog"),s=a((p,f)=>{try{let v=new uE({allErrors:!0,strict:!1}).compile(p);return v(f)?[]:(v.errors??[]).map(h=>`${h.instancePath||"(root)"} ${h.message??"invalid"}${h.params?` ${JSON.stringify(h.params)}`:""}`)}catch{return[]}},"ajvValidator"),c=a(async(p,f)=>{try{let{kernel:g,appId:v}=await t(f),{index:h}=await i(g,v);return{...sg(p,h,s),catalogReachable:!0}}catch(g){F(g);let v=sg(p,void 0);return{...v,warnings:[...v.warnings,"deployment unreachable \u2014 connector ids, actionIds, and params were NOT verified against the live catalog; pipes_create will verify them"],catalogReachable:!1}}},"validateAgainstLive");e.tool("pipes_catalog","Return the Pipes authoring guide + the LIVE connector catalog from your deployment: every connector, every action, and each action's FULL JSON-Schema (all params, types, enums, required) \u2014 plus the branch-handle map and the valid trigger types. Call FIRST so you author with the real, current params (no guessing).",{appId:S.string().optional().describe("app GID (app_\u2026); defaults to the token's app claim")},async({appId:p})=>{try{let{kernel:f,appId:g}=await t(p),{rows:v}=await i(f,g);return N({guidance:Zw,definitionSchema:{id:Rw,version:No,resource:rg},triggerTypes:Uo,triggers:Do,branchHandles:Yt,builtinNodeTypes:Object.entries(Xt).map(([h,x])=>({nodeType:h,backendType:x,isBrancher:h===Qt||h in Yt})),connectors:v.map(h=>({connectorId:h.id??h.connectorId??h._id,category:h.category,description:h.description,tier:h.tier,needsCredential:h.auth?.type&&h.auth.type!=="none",branchHandles:Yt[h.id??h.connectorId]??((h.id??h.connectorId)===Qt?["<case name>",mr]:void 0),actions:(h.actions??[]).map(x=>({actionId:x.id,name:x.name,description:x.description,inputSchema:x.inputSchema,outputSchema:x.outputSchema}))}))})}catch(f){return ce(f)}});let u=Do.map(p=>p.type).join("|"),l=[...Object.entries(Yt).map(([p,f])=>`${p} ${f.join("/")}`),`${Qt} <case>/${mr}`].join(", "),d=S.object({id:S.string().describe("unique node id"),nodeType:S.string().describe(`the type the engine runs (data.nodeType): a trigger (${u}), a built-in (${Object.keys(Xt).filter(p=>Xt[p]!=="trigger").join("|")}), or "${kt}" for a catalogue connector (then set connectorId from pipes_catalog; it is checked against the live catalogue). Built-ins: ${Lw}`),connectorId:S.string().optional().describe(`REQUIRED when nodeType is "${kt}": the connector id from pipes_catalog`),config:S.record(S.string(),S.unknown()).optional().describe(`data.config. A trigger: its trigger config keys (${Do.map(p=>`${p.type}: ${p.summary}`).join(" ")}). A built-in: its settings, flat. A connector step: ${Ia} \u2014 the action id from pipes_catalog and its params, typed by that action's inputSchema, under params (data.config.params, the only place the engine reads them).`),credentials:S.record(S.string(),S.string()).optional().describe("a connector step's credentials: { <connectorId>: <credential gid> } (data.credentials)"),label:S.string().optional()}),m=S.object({from:S.string(),to:S.string(),branch:S.string().optional().describe(`the branch a brancher is left by (${l}); omit for a step without branches`)});return e.tool("pipes_build","Compile a HIGH-LEVEL pipe spec into a CORRECT workflow definition (connector-schema nodes + explicit edge handles + branch resolution + auto-layout) AND validate it against the LIVE deployment catalog: every connectorId must exist, every actionId must be one of that connector's actions, and connector params are checked against the action's real inputSchema \u2014 so a guessed name fails HERE with a did-you-mean, not at run time. NEVER hand-write node/edge JSON \u2014 use this. Returns { definition, warnings }.",{nodes:S.array(d).describe("the steps"),edges:S.array(m).optional().describe("how steps connect"),appId:S.string().optional().describe("app GID (app_\u2026); defaults to the token's app claim \u2014 used to fetch the live connector catalog for validation")},async({appId:p,...f})=>{try{let g=og(f),v=await c(f,p);if(!v.ok)return{...N({ok:!1,stage:"catalog-validation",issues:v.issues,warnings:v.warnings}),isError:!0};let h=ig(f);return N({ok:!0,definition:g,triggerConfig:h,...v.warnings.length?{warnings:v.warnings}:{}})}catch(g){return ce(g)}}),e.tool("pipes_create",`Create a pipe in your deployment from a high-level spec (the same spec as pipes_build) and optionally activate it. Mutating; confirm first. Include exactly ONE trigger node (nodeType ${u}) as the ENTRY node (no incoming edge) wired to the first step; the trigger config is derived from it (or omit the trigger node and pass triggerType + triggerConfig). The door validates the whole definition before it writes anything; a refusal returns PIPE_DEFINITION_INVALID with every reason (path, expected, got) and retry: true.`,{name:S.string(),description:S.string().optional(),nodes:S.array(d),edges:S.array(m).optional(),triggerType:S.enum(Uo).optional().describe("the single workflow trigger (default manual)"),triggerConfig:S.record(S.string(),S.unknown()).optional().describe(`the trigger's config when the spec has no trigger node (${Do.map(p=>`${p.type}: ${p.summary}`).join(" ")})`),activate:S.boolean().optional(),appId:S.string().optional()},async p=>{try{let f;try{f=og({nodes:p.nodes,edges:p.edges})}catch(k){return ce(k,{stage:"build"})}let g=await c({nodes:p.nodes,edges:p.edges},p.appId);if(!g.catalogReachable)return{...N({ok:!1,stage:"catalog-validation",error:"could not fetch the connector catalog from your deployment \u2014 pipes_create refuses to create unverified workflows",warnings:g.warnings}),isError:!0};if(!g.ok)return{...N({ok:!1,stage:"catalog-validation",issues:g.issues,warnings:g.warnings}),isError:!0};let v=ig({nodes:p.nodes,edges:p.edges},{type:p.triggerType,config:p.triggerConfig}),{kernel:h}=await t(p.appId),x;try{x=await h.send({..._t("pipes.workflows.createWorkflow"),body:{name:p.name,description:p.description??"",definition:f,triggerConfig:v}})}catch(k){let O=Xw(k);if(O)return{...N({...O,stage:"door"}),isError:!0};throw k}let E=r(x);return p.activate&&E&&await h.send({..._t("pipes.workflows.activateWorkflow"),pathParams:{workflowId:E},body:{}}),N({ok:!0,workflowId:E,activated:!!(p.activate&&E),nodes:f.nodes.length,edges:f.edges.length,...g.warnings.length?{warnings:g.warnings}:{}})}catch(f){return ce(f)}}),e.tool("pipes_validate_definition","Validate a pipe definition and trigger config against your deployment WITHOUT saving anything: the door applies every check it applies on create (the one pipe definition schema, your live connector catalogue, params against each action's inputSchema, credentials, branches, one reachable trigger). Pass the { definition, triggerConfig } pipes_build returned. Answers { valid: true } or PIPE_DEFINITION_INVALID with every reason (path, expected, got, didYouMean) and retry: true.",{definition:S.record(S.string(),S.unknown()).describe("the pipe definition { nodes, edges } (pipes_build's definition)"),triggerConfig:S.record(S.string(),S.unknown()).optional().describe("the trigger config { type, config } (pipes_build's triggerConfig)"),appId:S.string().optional()},async({definition:p,triggerConfig:f,appId:g})=>{try{let{kernel:v}=await t(g),h;try{h=await v.send({..._t("pipes.workflows.validateWorkflowDefinition"),body:{definition:p,...f?{triggerConfig:f}:{}}})}catch(E){let k=Xw(E);if(k)return{...N({...k,stage:"door",valid:!1}),isError:!0};throw E}let x=h?.data??h;return N({ok:!0,valid:x?.valid??!0,errors:x?.errors??[],schemaVersion:No})}catch(v){return ce(v)}}),e.resource("pipes-authoring-flow",Mw,{description:"How to author a pipe, step by step: discover the connectors, read their input schemas, draft, validate, create, run, inspect, iterate.",mimeType:"text/plain"},async p=>({contents:[{uri:p.href,mimeType:"text/plain",text:jo}]})),e.resource("pipes-definition-schema",rg,{description:`The pipe definition JSON Schema ${No} every pipes tool is generated from and the door validates against.`,mimeType:"application/schema+json"},async p=>({contents:[{uri:p.href,mimeType:"application/schema+json",text:JSON.stringify(qw,null,2)}]})),e.prompt(Fw,"Author an npayload pipe with the pipes tools, following the pipe-authoring flow.",{goal:S.string().optional().describe("what the pipe should do, in your words")},({goal:p})=>({messages:[{role:"user",content:{type:"text",text:`${p?`Build an npayload pipe that does this: ${p}
|
|
511
513
|
|
|
512
|
-
`:""}${jo}`}}]})),e.tool("pipes_list","List the workflows in your deployment (gid, name, status).",{appId:S.string().optional()},async({appId:p})=>{try{let{kernel:f}=await t(p),g=await f.send(_t("pipes.workflows.listWorkflows")),v=g?.data??g??[];return N(v.map(h=>({workflowId:h.gid??h.workflowGid??h._id,name:h.name,status:h.status})))}catch(f){return ce(f)}}),e.tool("pipes_get","Get one workflow incl. its full definition (nodes + edges) \u2014 useful to inspect or modify an existing pipe.",{workflowId:S.string(),appId:S.string().optional()},async({workflowId:p,appId:f})=>{try{let{kernel:g}=await t(f),v=await g.send({..._t("pipes.workflows.getWorkflow"),pathParams:{workflowId:p}});return N(v)}catch(g){return ce(g)}}),e.tool("pipes_run","Trigger one execution of a workflow (must be active). Returns the execution id + status; poll pipes_get_execution.",{workflowId:S.string(),triggerData:S.record(S.string(),S.unknown()).optional(),appId:S.string().optional()},async({workflowId:p,triggerData:f,appId:g})=>{try{let{kernel:v}=await t(g),h=await v.send({..._t("pipes.executions.triggerExecution"),pathParams:{workflowId:p},body:{triggerData:f??{}}});return N({executionId:h?.gid??h?.executionGid??h?.executionId,status:h?.status})}catch(v){return ce(v)}}),e.tool("pipes_get_execution","Get one execution's live state: overall status (running|completed|failed|cancelled) plus per-node runs with each node's status, output and error. Poll this after pipes_run until the status is terminal. The definition was already checked at create (PIPE_DEFINITION_INVALID); what fails here is the run itself (a remote call, a resolved template, a credential).",{executionId:S.string().describe("the execution id returned by pipes_run"),appId:S.string().optional()},async({executionId:p,appId:f})=>{try{let{kernel:g}=await t(f),v=await g.send({..._t("pipes.executions.getExecution"),pathParams:{executionId:p}});return N(v?.data??v)}catch(g){return ce(g)}}),e.tool("pipes_delete","Delete a workflow (works from ANY state \u2014 draft, paused, archived, active). Mutating \u2014 confirm first.",{workflowId:S.string(),appId:S.string().optional()},async({workflowId:p,appId:f})=>{try{let{kernel:g}=await t(f);return await g.send({..._t("pipes.workflows.deleteWorkflow"),pathParams:{workflowId:p}}),N({ok:!0,deleted:p})}catch(g){return ce(g)}}),e.tool("primus_contract","Return the npayload Primus (AI agents) config schema (JSON Schema) + the capability catalog + decision guide + guidance. Call this BEFORE writing or editing primus.config.ts \u2014 the schema returned here is the only valid source of config fields. Naming rule: skill/tool names are lowercase + underscores (hyphens are rejected).",async()=>N({version:mv,guidance:Tw,capabilities:Aw,schema:Tt})),e.tool("primus_validate","Validate a Primus config against the contract PLUS the platform preflight the schema can't express: skill/tool naming rule (lowercase + underscores, NO hyphens \u2014 the platform hard-rejects them) and trigger\u2192agent parent references. Pass the config object, OR omit it to validate the project's primus.config.ts on disk. Returns { ok, issues }.",{config:S.union([S.record(S.string(),S.unknown()),S.string()]).optional().describe("the PrimusConfig object (or a JSON string) to validate; omit to validate primus.config.ts on disk"),configPath:S.string().optional().describe("path to primus.config.ts (used when `config` is omitted)")},async({config:p,configPath:f})=>{let g=p;if(typeof g=="string")try{g=JSON.parse(g)}catch{}if(g==null){let h=f??Ke("primus");if(!h)return{...N({ok:!1,error:"no primus.config.ts found \u2014 write npayload/primus.config.ts first (see primus_contract)"}),isError:!0};g=await le(h)}let v=Wr(g,{allowInternalUrls:en()});return{...N(v),isError:!v.ok}}),e.tool("primus_deploy","Reconcile the project's primus.config.ts (agents / skills / tools / triggers) to your AI deployment \u2014 idempotent, keyed by name; triggers attach to their agent by NAME (resolved at deploy). Validates first; pass check:true for a dry-run plan. Mutating: confirm before applying.",{check:S.boolean().optional().describe("dry run: print the plan, apply nothing"),configPath:S.string().optional().describe("path to primus.config.ts (default: ./npayload/primus.config.ts)")},async({check:p,configPath:f})=>{let g=f??Ke("primus");if(!g)return{...N({ok:!1,error:"no primus.config.ts found \u2014 write npayload/primus.config.ts first (see primus_contract)"}),isError:!0};let v=await le(g),h=Wr(v,{allowInternalUrls:en()});if(!h.ok)return{...N({error:"config invalid \u2014 fix before deploy",issues:h.issues}),isError:!0};try{let x=await xe({config:g,check:p??!1,sink:a(()=>{},"sink")});return N(x.output)}catch(x){return ce(x)}}),e.tool("primus_status","Show the current sync state between primus.config.ts and your AI deployment (a dry-run plan: what exists, what would change).",{configPath:S.string().optional()},async({configPath:p})=>{let f=p??Ke("primus");if(!f)return{...N({ok:!1,error:"no primus.config.ts found"}),isError:!0};try{let g=await xe({config:f,check:!0,sink:a(()=>{},"sink")});return N(g.output)}catch(g){return ce(g)}}),e.tool("npayload_status","Diagnose the npayload environment: API + auth endpoint reachability, which credential source is available, and whether this project's pinned contract and generated permissions are in sync \u2014 each failure with a one-line remediation. Call this FIRST whenever another tool returns a connection or authorization error.",async()=>{try{let{buildReport:p}=await import("../chunk-52ZB3ZAG.mjs"),f=await p(),g={code:"TRANSPORT_UNAVAILABLE",type:"TransportUnavailableError"};return N({ok:f.authReady&&f.stack.apiReachable,endpoints:{api:{url:f.stack.apiUrl,reachable:f.stack.apiReachable,probe:f.stack.apiProbe,...f.stack.apiProbe==="refused"?g:{}},auth:f.stack.authUrl?{url:f.stack.authUrl,reachable:f.stack.authReachable,probe:f.stack.authProbe,...f.stack.authProbe==="refused"?g:{}}:void 0},credentials:f.credentials,project:{contractPin:f.stack.contractLock,generatedPermissions:f.stack.permissions},remediation:f.remediation})}catch(p){return ce(p)}}),e.tool("npayload_catalog",`Discover the FULL npayload op surface across ALL products (events, pipes, connect, feed, primus, account, \u2026). Returns every op grouped by product, each with { key, method, path, summary, isQuery, idempotent, scopes, pathParams, args }. The "key" is what you pass to npayload_invoke. Call this FIRST to learn what you can do, then npayload_invoke to do it. Pass a "product" to filter (products: ${Aa().join(", ")}).`,{product:S.string().optional().describe(`filter to one product, e.g. ${Aa().slice(0,4).join(", ")}; omit for the full catalog`)},async({product:p})=>{try{let f=Jw(p);return p&&f.products.length===0?{...N({ok:!1,error:`no product "${p}"`,products:Aa()}),isError:!0}:N(f)}catch(f){return ce(f)}}),e.tool("connect_deploy","Reconcile the project's connect.config.ts to the ADMIN control plane (idempotent; admin is the source of truth and syncs to cells). Validates first; pass check:true for a dry-run plan. Mutating: confirm before applying. Declaring a bridge/grant is an OFFER (pending) \u2014 the other org confirms in its own config.",{check:S.boolean().optional().describe("dry run: print the plan, apply nothing"),configPath:S.string().optional().describe("path to connect.config.ts (default: ./connect.config.ts or ./npayload/connect.config.ts)")},async({check:p,configPath:f})=>{let g=f??ug(),v=await le(g),h=ou(v,{allowInternalUrls:en()});if(!h.ok)return{...N({error:"config invalid \u2014 fix before deploy",issues:h.issues}),isError:!0};try{let x=await xe({config:g,check:p??!1,sink:a(()=>{},"sink")});return N(x.output)}catch(x){return ce(x)}}),e.tool("connect_status","Show the current sync state between connect.config.ts and the admin control plane (a dry-run plan: what exists, what would change).",{configPath:S.string().optional()},async({configPath:p})=>{let f=p??ug();try{let g=await xe({config:f,check:!0,sink:a(()=>{},"sink")});return N(g.output)}catch(g){return ce(g)}}),e.tool("npayload_invoke",`Invoke ANY npayload op by its catalog "key" (from npayload_catalog), e.g. "events.channels.list", "connect.connectAccess.listMyGrants", "feed.listings.create", "primus.agents.create", "account.environments.create". Pass "args" keyed by the op's arg names \u2014 path params and body/query fields together; this tool splits them per the op's contract. Path params named "appId" are auto-resolved from your token when omitted. Dispatches as your authenticated client (bounded by your own token scopes \u2014 no escalation). WARNING: ops where isQuery is false MUTATE state; ALWAYS confirm with the user before invoking a mutating op (create/update/delete/publish/trigger/\u2026).`,{key:S.string().describe('the op key from npayload_catalog, e.g. "events.channels.create"'),args:S.record(S.string(),S.unknown()).optional().describe("op args keyed by arg name (path params + body/query); see the op's pathParams/args in npayload_catalog")},async({key:p,args:f})=>{try{let{buildKernel:g}=await import("../chunk-2PCG57PX.mjs"),v=Ea({key:p})==="primus"?ne(process.env.NPAYLOAD_PRIMUS_API_URL,"primusApiUrl"):void 0,h=await g(v||void 0),{row:x,request:E}=await Hw(p,f,{resolveAppId:a(()=>Qw(h),"resolveAppId"),newIdempotencyKey:a(()=>globalThis.crypto.randomUUID(),"newIdempotencyKey")}),k=await h.send(E);return N({ok:!0,key:p,method:x.method,path:E.path,mutating:!x.isQuery,result:k})}catch(g){return g instanceof Sn?ce(g,{suggestions:g.suggestions}):ce(g)}}),e}a(fE,"buildServer");function tx(e){e.command("mcp").description("npayload MCP server for your coding agent (local stdio)").command("serve",{isDefault:!0}).description("Run the MCP server on stdio (Claude / Cursor / Codex connect to this)").action(async()=>{Bw(await Oh());let r=fE(),o=new dE;await r.connect(o)})}a(tx,"registerMcp");import{existsSync as hg,readFileSync as UE,watch as LE}from"fs";import{resolve as zE,join as Ga}from"path";import tn from"chalk";import ue from"chalk";import{createHash as DE}from"crypto";import{readFileSync as jE}from"fs";import{existsSync as Mo,readFileSync as fg,writeFileSync as La,mkdirSync as ax}from"fs";import{resolve as cx,join as Ot,dirname as ux}from"path";import _e from"chalk";function Ca(e,t){return Ra(e)===Ra(t)}a(Ca,"deepEqual");function Ra(e){if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(Ra).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(o=>`${JSON.stringify(o)}:${Ra(t[o])}`).join(",")}}`}a(Ra,"stableStringify");var gE=a(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj");function rx(e,t,r){let o={},n=[],i=[],s=[],c=nx(t,r);for(let u of c){let l=t[u]??{},d=r[u]??{},m=e[u]??{},p={};for(let f of nx(l,d)){let g=l[f],v=d[f],h=m[f];if(g&&!v){p[f]=ot(g),s.push({resource:u,key:f});continue}if(!g&&v){p[f]=ot(v),n.push({resource:u,key:f,kind:"add-entry",value:ot(v)});continue}if(!g||!v)continue;let x={};for(let E of hE(h,g,v)){let k=h?E in h:!1,O=E in g,A=E in v,j=h?.[E],U=g[E],K=v[E];if(O&&A)Ca(U,K)?x[E]=ot(U):k&&Ca(U,j)?(x[E]=ot(K),n.push({resource:u,key:f,field:E,kind:"update-field",value:ot(K)})):k&&Ca(K,j)?x[E]=ot(U):(x[E]=ot(U),i.push({resource:u,key:f,field:E,base:j,local:U,remote:K}));else if(O&&!A)x[E]=ot(U);else if(!O&&A){if(k&&Ca(K,j))continue;x[E]=ot(K),n.push({resource:u,key:f,field:E,kind:"add-field",value:ot(K)})}}p[f]=x}Object.keys(p).length&&(o[u]=p)}return{merged:o,changes:n,conflicts:i,localOnly:s}}a(rx,"threeWayMergeConfig");function nx(e,t){return Array.from(new Set([...Object.keys(e),...Object.keys(t)]))}a(nx,"unionKeys");function hE(...e){let t=new Set;for(let r of e)if(gE(r))for(let o of Object.keys(r))t.add(o);return Array.from(t)}a(hE,"unionFieldKeys");function ot(e){return e===void 0?e:JSON.parse(JSON.stringify(e))}a(ot,"clone");var Lo;async function yE(){if(Lo!==void 0)return Lo;try{Lo=(await import("typescript")).default??await import("typescript")}catch{Lo=null}return Lo}a(yE,"loadTs");function fr(e,t=0){let r=" ".repeat(t),o=" ".repeat(t+1);if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.length===0?"[]":`[
|
|
514
|
+
`:""}${jo}`}}]})),e.tool("pipes_list","List the workflows in your deployment (gid, name, status).",{appId:S.string().optional()},async({appId:p})=>{try{let{kernel:f}=await t(p),g=await f.send(_t("pipes.workflows.listWorkflows")),v=g?.data??g??[];return N(v.map(h=>({workflowId:h.gid??h.workflowGid??h._id,name:h.name,status:h.status})))}catch(f){return ce(f)}}),e.tool("pipes_get","Get one workflow incl. its full definition (nodes + edges) \u2014 useful to inspect or modify an existing pipe.",{workflowId:S.string(),appId:S.string().optional()},async({workflowId:p,appId:f})=>{try{let{kernel:g}=await t(f),v=await g.send({..._t("pipes.workflows.getWorkflow"),pathParams:{workflowId:p}});return N(v)}catch(g){return ce(g)}}),e.tool("pipes_run","Trigger one execution of a workflow (must be active). Returns the execution id + status; poll pipes_get_execution.",{workflowId:S.string(),triggerData:S.record(S.string(),S.unknown()).optional(),appId:S.string().optional()},async({workflowId:p,triggerData:f,appId:g})=>{try{let{kernel:v}=await t(g),h=await v.send({..._t("pipes.executions.triggerExecution"),pathParams:{workflowId:p},body:{triggerData:f??{}}});return N({executionId:h?.gid??h?.executionGid??h?.executionId,status:h?.status})}catch(v){return ce(v)}}),e.tool("pipes_get_execution","Get one execution's live state: overall status (running|completed|failed|cancelled) plus per-node runs with each node's status, output and error. Poll this after pipes_run until the status is terminal. The definition was already checked at create (PIPE_DEFINITION_INVALID); what fails here is the run itself (a remote call, a resolved template, a credential).",{executionId:S.string().describe("the execution id returned by pipes_run"),appId:S.string().optional()},async({executionId:p,appId:f})=>{try{let{kernel:g}=await t(f),v=await g.send({..._t("pipes.executions.getExecution"),pathParams:{executionId:p}});return N(v?.data??v)}catch(g){return ce(g)}}),e.tool("pipes_delete","Delete a workflow (works from ANY state \u2014 draft, paused, archived, active). Mutating \u2014 confirm first.",{workflowId:S.string(),appId:S.string().optional()},async({workflowId:p,appId:f})=>{try{let{kernel:g}=await t(f);return await g.send({..._t("pipes.workflows.deleteWorkflow"),pathParams:{workflowId:p}}),N({ok:!0,deleted:p})}catch(g){return ce(g)}}),e.tool("primus_contract","Return the npayload Primus (AI agents) config schema (JSON Schema) + the capability catalog + decision guide + guidance. Call this BEFORE writing or editing primus.config.ts \u2014 the schema returned here is the only valid source of config fields. Naming rule: skill/tool names are lowercase + underscores (hyphens are rejected).",async()=>N({version:mv,guidance:Tw,capabilities:Aw,schema:Tt})),e.tool("primus_validate","Validate a Primus config against the contract PLUS the platform preflight the schema can't express: skill/tool naming rule (lowercase + underscores, NO hyphens \u2014 the platform hard-rejects them) and trigger\u2192agent parent references. Pass the config object, OR omit it to validate the project's primus.config.ts on disk. Returns { ok, issues }.",{config:S.union([S.record(S.string(),S.unknown()),S.string()]).optional().describe("the PrimusConfig object (or a JSON string) to validate; omit to validate primus.config.ts on disk"),configPath:S.string().optional().describe("path to primus.config.ts (used when `config` is omitted)")},async({config:p,configPath:f})=>{let g=p;if(typeof g=="string")try{g=JSON.parse(g)}catch{}if(g==null){let h=f??Ke("primus");if(!h)return{...N({ok:!1,error:"no primus.config.ts found \u2014 write npayload/primus.config.ts first (see primus_contract)"}),isError:!0};g=await le(h)}let v=Wr(g,{allowInternalUrls:en()});return{...N(v),isError:!v.ok}}),e.tool("primus_deploy","Reconcile the project's primus.config.ts (agents / skills / tools / triggers) to your AI deployment \u2014 idempotent, keyed by name; triggers attach to their agent by NAME (resolved at deploy). Validates first; pass check:true for a dry-run plan. Mutating: confirm before applying.",{check:S.boolean().optional().describe("dry run: print the plan, apply nothing"),configPath:S.string().optional().describe("path to primus.config.ts (default: ./npayload/primus.config.ts)")},async({check:p,configPath:f})=>{let g=f??Ke("primus");if(!g)return{...N({ok:!1,error:"no primus.config.ts found \u2014 write npayload/primus.config.ts first (see primus_contract)"}),isError:!0};let v=await le(g),h=Wr(v,{allowInternalUrls:en()});if(!h.ok)return{...N({error:"config invalid \u2014 fix before deploy",issues:h.issues}),isError:!0};try{let x=await xe({config:g,check:p??!1,sink:a(()=>{},"sink")});return N(x.output)}catch(x){return ce(x)}}),e.tool("primus_status","Show the current sync state between primus.config.ts and your AI deployment (a dry-run plan: what exists, what would change).",{configPath:S.string().optional()},async({configPath:p})=>{let f=p??Ke("primus");if(!f)return{...N({ok:!1,error:"no primus.config.ts found"}),isError:!0};try{let g=await xe({config:f,check:!0,sink:a(()=>{},"sink")});return N(g.output)}catch(g){return ce(g)}}),e.tool("npayload_status","Diagnose the npayload environment: API + auth endpoint reachability, which credential source is available, and whether this project's pinned contract and generated permissions are in sync \u2014 each failure with a one-line remediation. Call this FIRST whenever another tool returns a connection or authorization error.",async()=>{try{let{buildReport:p}=await import("../chunk-5KFQTEH3.mjs"),f=await p(),g={code:"TRANSPORT_UNAVAILABLE",type:"TransportUnavailableError"};return N({ok:f.authReady&&f.stack.apiReachable,endpoints:{api:{url:f.stack.apiUrl,reachable:f.stack.apiReachable,probe:f.stack.apiProbe,...f.stack.apiProbe==="refused"?g:{}},auth:f.stack.authUrl?{url:f.stack.authUrl,reachable:f.stack.authReachable,probe:f.stack.authProbe,...f.stack.authProbe==="refused"?g:{}}:void 0},credentials:f.credentials,project:{contractPin:f.stack.contractLock,generatedPermissions:f.stack.permissions},remediation:f.remediation})}catch(p){return ce(p)}}),e.tool("npayload_catalog",`Discover the FULL npayload op surface across ALL products (events, pipes, connect, feed, primus, account, \u2026). Returns every op grouped by product, each with { key, method, path, summary, isQuery, idempotent, scopes, pathParams, args }. The "key" is what you pass to npayload_invoke. Call this FIRST to learn what you can do, then npayload_invoke to do it. Pass a "product" to filter (products: ${Aa().join(", ")}).`,{product:S.string().optional().describe(`filter to one product, e.g. ${Aa().slice(0,4).join(", ")}; omit for the full catalog`)},async({product:p})=>{try{let f=Jw(p);return p&&f.products.length===0?{...N({ok:!1,error:`no product "${p}"`,products:Aa()}),isError:!0}:N(f)}catch(f){return ce(f)}}),e.tool("connect_deploy","Reconcile the project's connect.config.ts to the ADMIN control plane (idempotent; admin is the source of truth and syncs to cells). Validates first; pass check:true for a dry-run plan. Mutating: confirm before applying. Declaring a bridge/grant is an OFFER (pending) \u2014 the other org confirms in its own config.",{check:S.boolean().optional().describe("dry run: print the plan, apply nothing"),configPath:S.string().optional().describe("path to connect.config.ts (default: ./connect.config.ts or ./npayload/connect.config.ts)")},async({check:p,configPath:f})=>{let g=f??ug(),v=await le(g),h=ou(v,{allowInternalUrls:en()});if(!h.ok)return{...N({error:"config invalid \u2014 fix before deploy",issues:h.issues}),isError:!0};try{let x=await xe({config:g,check:p??!1,sink:a(()=>{},"sink")});return N(x.output)}catch(x){return ce(x)}}),e.tool("connect_status","Show the current sync state between connect.config.ts and the admin control plane (a dry-run plan: what exists, what would change).",{configPath:S.string().optional()},async({configPath:p})=>{let f=p??ug();try{let g=await xe({config:f,check:!0,sink:a(()=>{},"sink")});return N(g.output)}catch(g){return ce(g)}}),e.tool("npayload_invoke",`Invoke ANY npayload op by its catalog "key" (from npayload_catalog), e.g. "events.channels.list", "connect.connectAccess.listMyGrants", "feed.listings.create", "primus.agents.create", "account.environments.create". Pass "args" keyed by the op's arg names \u2014 path params and body/query fields together; this tool splits them per the op's contract. Path params named "appId" are auto-resolved from your token when omitted. Dispatches as your authenticated client (bounded by your own token scopes \u2014 no escalation). WARNING: ops where isQuery is false MUTATE state; ALWAYS confirm with the user before invoking a mutating op (create/update/delete/publish/trigger/\u2026).`,{key:S.string().describe('the op key from npayload_catalog, e.g. "events.channels.create"'),args:S.record(S.string(),S.unknown()).optional().describe("op args keyed by arg name (path params + body/query); see the op's pathParams/args in npayload_catalog")},async({key:p,args:f})=>{try{let{buildKernel:g}=await import("../chunk-6BBB7BRP.mjs"),v=Ea({key:p})==="primus"?ne(process.env.NPAYLOAD_PRIMUS_API_URL,"primusApiUrl"):void 0,h=await g(v||void 0),{row:x,request:E}=await Hw(p,f,{resolveAppId:a(()=>Qw(h),"resolveAppId"),newIdempotencyKey:a(()=>globalThis.crypto.randomUUID(),"newIdempotencyKey")}),k=await h.send(E);return N({ok:!0,key:p,method:x.method,path:E.path,mutating:!x.isQuery,result:k})}catch(g){return g instanceof Sn?ce(g,{suggestions:g.suggestions}):ce(g)}}),e}a(fE,"buildServer");function tx(e){e.command("mcp").description("npayload MCP server for your coding agent (local stdio)").command("serve",{isDefault:!0}).description("Run the MCP server on stdio (Claude / Cursor / Codex connect to this)").action(async()=>{Bw(await Oh());let r=fE(),o=new dE;await r.connect(o)})}a(tx,"registerMcp");import{existsSync as hg,readFileSync as UE,watch as LE}from"fs";import{resolve as zE,join as Ga}from"path";import tn from"chalk";import ue from"chalk";import{createHash as DE}from"crypto";import{readFileSync as jE}from"fs";import{existsSync as Mo,readFileSync as fg,writeFileSync as La,mkdirSync as ax}from"fs";import{resolve as cx,join as Ot,dirname as ux}from"path";import _e from"chalk";function Ca(e,t){return Ra(e)===Ra(t)}a(Ca,"deepEqual");function Ra(e){if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(Ra).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(o=>`${JSON.stringify(o)}:${Ra(t[o])}`).join(",")}}`}a(Ra,"stableStringify");var gE=a(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj");function rx(e,t,r){let o={},n=[],i=[],s=[],c=nx(t,r);for(let u of c){let l=t[u]??{},d=r[u]??{},m=e[u]??{},p={};for(let f of nx(l,d)){let g=l[f],v=d[f],h=m[f];if(g&&!v){p[f]=ot(g),s.push({resource:u,key:f});continue}if(!g&&v){p[f]=ot(v),n.push({resource:u,key:f,kind:"add-entry",value:ot(v)});continue}if(!g||!v)continue;let x={};for(let E of hE(h,g,v)){let k=h?E in h:!1,O=E in g,A=E in v,j=h?.[E],U=g[E],K=v[E];if(O&&A)Ca(U,K)?x[E]=ot(U):k&&Ca(U,j)?(x[E]=ot(K),n.push({resource:u,key:f,field:E,kind:"update-field",value:ot(K)})):k&&Ca(K,j)?x[E]=ot(U):(x[E]=ot(U),i.push({resource:u,key:f,field:E,base:j,local:U,remote:K}));else if(O&&!A)x[E]=ot(U);else if(!O&&A){if(k&&Ca(K,j))continue;x[E]=ot(K),n.push({resource:u,key:f,field:E,kind:"add-field",value:ot(K)})}}p[f]=x}Object.keys(p).length&&(o[u]=p)}return{merged:o,changes:n,conflicts:i,localOnly:s}}a(rx,"threeWayMergeConfig");function nx(e,t){return Array.from(new Set([...Object.keys(e),...Object.keys(t)]))}a(nx,"unionKeys");function hE(...e){let t=new Set;for(let r of e)if(gE(r))for(let o of Object.keys(r))t.add(o);return Array.from(t)}a(hE,"unionFieldKeys");function ot(e){return e===void 0?e:JSON.parse(JSON.stringify(e))}a(ot,"clone");var Lo;async function yE(){if(Lo!==void 0)return Lo;try{Lo=(await import("typescript")).default??await import("typescript")}catch{Lo=null}return Lo}a(yE,"loadTs");function fr(e,t=0){let r=" ".repeat(t),o=" ".repeat(t+1);if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.length===0?"[]":`[
|
|
513
515
|
${e.map(i=>`${o}${fr(i,t+1)}`).join(`,
|
|
514
516
|
`)},
|
|
515
517
|
${r}]`;if(typeof e=="object"){let n=e,i=Object.keys(n);return i.length===0?"{}":`{
|
|
@@ -542,7 +544,7 @@ export default ${e}(${JSON.stringify(r,null,2)});
|
|
|
542
544
|
* This is the MERGED result \u2014 diff it against ${f}, then keep.`;La(A,sx(m.define,r,k.merged,j),"utf8"),Ua(zo(m,r),g),t(_e.yellow(`! ${m.name}: in-place merge unavailable (${O.reason??"n/a"}) \u2014 wrote sidecar ${A}
|
|
543
545
|
`)),d++}}return d===0&&l.count===0&&t(_e.dim(`Nothing to pull.
|
|
544
546
|
`)),l.count>0&&process.stderr.write(_e.yellow(`\u26A0 ${l.count} resource type(s) unreadable \u2014 this preview/sync is PARTIAL.
|
|
545
|
-
`)),{touched:d,listFailures:l.count}}a(gg,"runPullOnce");function lx(e){e.command("pull").description("Pull your live Events and Primus setup into *.config.ts (three-way backward sync)").option("--app <appGid>","app GID (default: NPAYLOAD_APP_ID or the project .env)").option("--out <path>","force-write the resolved config to this path (skips merge)").option("--force","overwrite the resolved config in place (skips merge)").option("--env <slug>","environment to pull from (default: the active environment, `np env use`)").option("--check","preview the merge (adopted fields, additions, conflicts) \u2014 write NOTHING").action(async(t,r)=>{try{let o=dt(t,r),n=An(o!==void 0?{explicitSlug:o}:{}),i=await gg({...t,env:n});try{let{pullScopesIntoManifest:s}=await import("../chunk-
|
|
547
|
+
`)),{touched:d,listFailures:l.count}}a(gg,"runPullOnce");function lx(e){e.command("pull").description("Pull your live Events and Primus setup into *.config.ts (three-way backward sync)").option("--app <appGid>","app GID (default: NPAYLOAD_APP_ID or the project .env)").option("--out <path>","force-write the resolved config to this path (skips merge)").option("--force","overwrite the resolved config in place (skips merge)").option("--env <slug>","environment to pull from (default: the active environment, `np env use`)").option("--check","preview the merge (adopted fields, additions, conflicts) \u2014 write NOTHING").action(async(t,r)=>{try{let o=dt(t,r),n=An(o!==void 0?{explicitSlug:o}:{}),i=await gg({...t,env:n});try{let{pullScopesIntoManifest:s}=await import("../chunk-X3VVI7V3.mjs");await s({...t.app?{appId:t.app}:{},readRemoteGrant:a(async c=>{let{restoreSession:u}=await import("../chunk-I3UZ2FRE.mjs"),l=await u();return l?l.getOacGrant(c):null},"readRemoteGrant"),log:a(c=>process.stdout.write(c),"log")})}catch(s){F(s)}process.exit(i.listFailures>0?1:0)}catch(o){process.stderr.write(_e.red(`${se(o instanceof Error?o.message:String(o),o)}
|
|
546
548
|
`)),process.exit(1)}})}a(lx,"registerPull");var qa=class extends Error{static{a(this,"PushTargetsProductionError")}constructor(t,r="active"){super((r==="--env"?`Refusing: \`--env ${t}\` names the PRODUCTION environment. `:`Refusing: the active environment "${t}" is the PRODUCTION environment. `)+"`np push`/`diff`/`watch`/`sync` target development environments only \u2014 production changes ship through `np deploy`. "+(r==="--env"?"Pass a development environment's slug.":"Switch with `np env use <dev-slug>` first.")),this.name="PushTargetsProductionError"}};function gr(e,t){let r=t?.trim()?t.trim():void 0,o=r!==void 0?"--env":"active",n=r??pc(e)??"sandbox";if(n==="production"||n==="prod")throw new qa(n,o);if(En(e)?.environments.find(c=>c.slug===n)?.kind==="production")throw new qa(n,o);return n}a(gr,"resolveActivePushEnv");function za(e,t){let r=Ir(e.app);return{...e.config?{config:e.config}:{},...r?{app:r}:{},env:gr(void 0,e.env),check:t,...e.prune?{prune:!0}:{},...e.yes?{yes:!0}:{},...e.acceptRemote?{acceptRemote:!0}:{},...e.overwriteRemote?{overwriteRemote:!0}:{}}}a(za,"sandboxOpts");function Ma(e){return dt({},e)}a(Ma,"typedEnv");function Fa(e){process.stderr.write(ue.red(`${se(`failed: ${e instanceof Error?e.message:String(e)}`,e)}
|
|
547
549
|
`)),process.exit(1)}a(Fa,"fail");function dx(e){try{return DE("sha256").update(jE(e)).digest("hex")}catch{return}}a(dx,"fileDigest");var Za=class{static{a(this,"AdoptedWrites")}digests=new Map;record(t){for(let r of t){let o=dx(r);o!==void 0&&this.digests.set(r,o)}}isOnlyTheAdoption(t){return t.length===0||this.digests.size===0?!1:t.every(r=>this.digests.get(r)!==void 0&&this.digests.get(r)===dx(r))}clear(){this.digests.clear()}};function px(e,t,r,o){let n=Math.max(5,e.pollSeconds)*1e3,i=!1,s=a(async()=>{if(!(i||t.flag)){t.flag=!0;try{try{let m=await le(We()),p=Zh(fc(m)),f=await It(void 0,void 0,{readOnly:!0}),{token:g}=await f.auth.getAccessToken([]),h=(JSON.parse(Buffer.from(g.split(".")[1]??"","base64url").toString("utf8")).scope??"").split(" ").filter(Boolean).sort();h.length>0&&JSON.stringify(h)!==JSON.stringify(p)&&!i&&(process.stdout.write(ue.cyan(`\u2193 scope drift: credential carries ${h.length} scope(s), config projects ${p.length} \u2014 resyncing to the config\u2026
|
|
548
550
|
`)),await Gh(fc(m),Ir(e.app),x=>process.stdout.write(x)))}catch(m){F(m)}if(i)return;let u=gr(void 0,e.env),d=(await xe({...e.config?{config:e.config}:{},...Ir(e.app)?{app:Ir(e.app)}:{},env:u,check:!0,sink:a(()=>{},"sink")})).plan.filter(m=>m.action!=="noop");d.length>0&&!i&&(process.stdout.write(ue.cyan(`
|
|
@@ -609,7 +611,7 @@ ${t}`}a(lT,"contentSuffix");function Ka(e,t,r=e.startedAt){let o={...e,openTools
|
|
|
609
611
|
`),this.contentOpen=!1),this.sinks.err(`${at.dim(t)}
|
|
610
612
|
`)}},Wa=class{constructor(t=Ex){this.sinks=t}static{a(this,"NdjsonRenderer")}onEvent(t){this.sinks.out(`${JSON.stringify({event:t.event,data:t.data})}
|
|
611
613
|
`)}};function dT(e){return e?/nonce="([^"]+)"/.exec(e)?.[1]:void 0}a(dT,"parseDpopNonce");var pT="executions:execute";async function*Fo(e,t,r,o,n){let i=Nt(In(e)??ze(),n?.fetchImpl),s=`${t.replace(/\/+$/,"")}/v1/primus/chat/stream-pipeline`,c=JSON.stringify({agentGid:r.agentGid,input:r.input,...r.conversationGid?{conversationGid:r.conversationGid}:{}}),u=a(async()=>{In(e)?.check(s);let d=await e.auth.getAccessToken([pT]),m=await e.auth.signDpopProof({method:"POST",url:s,accessToken:d.token});return i(s,{method:"POST",headers:{Authorization:`DPoP ${d.token}`,DPoP:m,Accept:"text/event-stream","content-type":"application/json"},body:c,signal:o})},"doFetch"),l=await u();if(l.status===401){let d=dT(l.headers.get("www-authenticate"));d&&(e.auth.cacheNonce(new URL(s).origin,d),l=await u())}if(!l.ok){let d="";try{d=(await l.text()).slice(0,300)}catch{}throw new C(`chat stream request failed (${l.status})${d?`: ${d}`:""}`,{code:l.status===401||l.status===403?"CHAT_AUTH":l.status===404?"PRIMUS_UNREACHABLE":"CHAT_STREAM_FAILED",hint:l.status===403?"your credential is missing the executions:execute scope \u2014 re-run `npayload push` (permissions sync) or grant it in the dashboard":l.status===404?"the chat route was not found at this endpoint \u2014 check NPAYLOAD_PRIMUS_API_URL (or --api-url) names your AI endpoint":void 0})}if(!l.body)throw new C("chat stream returned no body",{code:"CHAT_STREAM_FAILED"});for await(let d of Zg(l.body))yield{event:d.event??"message",data:d.data}}a(Fo,"streamChatTurn");function Ha(e){let t=e;return(Array.isArray(t)?t:Array.isArray(t?.data)?t.data:[]).filter(o=>typeof o=="object"&&o!==null)}a(Ha,"rowsOf");var ct=a(e=>typeof e=="string"&&e?e:void 0,"str");async function qo(e){let t=await e.send({method:"GET",path:"/v1/primus/agents",query:{activeOnly:!0},scope:"agents:read"});return Ha(t).map(r=>({gid:ct(r.gid)??"",name:ct(r.name)??"(unnamed)",description:ct(r.description),status:ct(r.status)})).filter(r=>r.gid&&(r.status===void 0||r.status==="active"))}a(qo,"listActiveAgents");function Ya(e,t){let r=e.find(i=>i.gid===t);if(r)return r;let o=t.toLowerCase(),n=e.filter(i=>i.name.toLowerCase()===o);if(n.length===1)return n[0];throw n.length>1?new C(`agent name "${t}" is ambiguous (${n.length} matches)`,{code:"AGENT_AMBIGUOUS",hint:`use the gid: ${n.map(i=>i.gid).join(" | ")}`}):new C(`no active agent matches "${t}"`,{code:"AGENT_NOT_FOUND",hint:e.length?`available: ${e.slice(0,8).map(i=>i.name).join(", ")}`:"no active agents in this app \u2014 create one first (np primus agents create / dashboard)"})}a(Ya,"resolveAgent");async function Tx(e,t){let r=await e.send({method:"GET",path:"/v1/primus/conversations/by-agent",query:{agentGid:t},scope:"conversations:read"});return Ha(r).map(o=>({id:ct(o.gid)??"",title:ct(o.title),updatedAt:typeof o.updatedAt=="number"?o.updatedAt:typeof o.lastMessageAt=="number"?o.lastMessageAt:void 0})).filter(o=>o.id)}a(Tx,"listConversationsByAgent");async function Ax(e,t,r=10){let o=await e.send({method:"GET",path:"/v1/primus/conversations/{conversationId}/messages",pathParams:{conversationId:t},query:{messageLimit:r},scope:"conversations:read"}),n=o??{};return(Array.isArray(n.messages)?n.messages:Ha(o)).filter(s=>typeof s=="object"&&s!==null).map(s=>({role:ct(s.role)??"message",content:ct(s.content)??JSON.stringify(s.content??"").slice(0,200)})).slice(-r)}a(Ax,"getConversationMessages");async function Cx(e,t){try{let r=await e.send({method:"GET",path:"/v1/primus/executions/by-conversation",query:{conversationGid:t,limit:5},scope:"executions:read"}),o=Ha(r).find(i=>ct(i.status)==="running"||ct(i.status)==="pending"),n=o?ct(o.gid):void 0;return n?(await e.send({method:"POST",path:"/v1/primus/executions/{executionId}/cancel",pathParams:{executionId:n},body:{reason:"interrupted from np primus chat"},scope:"executions:execute"}),!0):!1}catch(r){return F(r),!1}}a(Cx,"cancelRunningExecution");import{createInterface as mT}from"readline/promises";import pe from"chalk";function Rx(e){let t=e.trim();if(!t.startsWith("/"))return null;let[r,...o]=t.slice(1).split(/\s+/),n=o.join(" ").trim()||void 0;switch((r??"").toLowerCase()){case"help":case"h":case"?":return{kind:"help"};case"exit":case"quit":case"q":return{kind:"exit"};case"new":return{kind:"new"};case"resume":return{kind:"resume"};case"info":return{kind:"info"};case"agent":return{kind:"agent",ref:n};default:return{kind:"unknown",raw:t}}}a(Rx,"parseSlashCommand");var Ox=["commands:"," /agent [name|gid] switch agent (picker when no argument; resets the conversation)"," /new start a fresh conversation with the current agent"," /resume pick one of this agent's conversations to continue"," /info show current agent, conversation, and endpoint"," /help this help"," /exit leave the chat","","Ctrl-C during a reply interrupts the run (best-effort server cancel);","at the prompt it exits. Messages are single-line in this version."].join(`
|
|
612
|
-
`);var Je=a(e=>{process.stderr.write(e)},"err");async function Tg(e,t,r={}){let o=await qo(e);if(o.length===0){let{CliError:n}=await import("../chunk-
|
|
614
|
+
`);var Je=a(e=>{process.stderr.write(e)},"err");async function Tg(e,t,r={}){let o=await qo(e);if(o.length===0){let{CliError:n}=await import("../chunk-QHGF2GC6.mjs");throw new n("no active agents in this app",{code:"NO_AGENTS",hint:"create one first: np primus agents create --name \u2026 (or use the dashboard), then re-run np primus chat"})}return o.length===1?o[0]:(r.select??He)("Pick an agent",o.map(n=>({name:n.gid===t?.gid?`${n.name} (current)`:n.name,value:n,description:n.description})))}a(Tg,"pickAgent");async function Nx(e,t,r={}){let o=r.err??Je,n=await Tx(e,t.gid);if(n.length===0){o(pe.dim(`no previous conversations with ${t.name} \u2014 starting fresh
|
|
613
615
|
`));return}let i=await(r.select??He)(`Resume a conversation with ${t.name}`,n.slice(0,20).map(s=>({name:s.title??s.id,value:s.id,description:s.updatedAt?new Date(s.updatedAt).toLocaleString():void 0})));try{let s=await Ax(e,i,10);if(s.length){o(pe.dim("\u2500".repeat(40)+`
|
|
614
616
|
`));for(let c of s){let u=c.role==="user"?"you":c.role;o(pe.dim(`${u}: ${c.content.split(`
|
|
615
617
|
`)[0].slice(0,120)}
|
|
@@ -635,7 +637,7 @@ ${t}`}a(lT,"contentSuffix");function Ka(e,t,r=e.startedAt){let o={...e,openTools
|
|
|
635
637
|
`)+(v?pe.dim(` ${v}
|
|
636
638
|
`):"")+`
|
|
637
639
|
`)}finally{s=!1,c=null}}n.close(),Je(pe.dim(`bye
|
|
638
|
-
`))}a(Dx,"runChatRepl");function yT(e,t){if(e.json&&!e.message)throw new C("--json requires --message (NDJSON output is one-shot only)",{code:"JSON_REQUIRES_MESSAGE",hint:'np primus chat --agent <ref> --message "\u2026" --json'});if(e.message){if(!e.agent&&!t)throw new C("--message without a TTY also needs --agent",{code:"AGENT_REQUIRED",hint:'np primus chat --agent <gid|name> --message "\u2026"'});return"oneshot"}if(!t)throw new C("interactive chat needs a TTY",{code:"NO_TTY",hint:'for scripts/CI use one-shot mode: np primus chat --agent <ref> --message "\u2026" [--json]'});return"repl"}a(yT,"assertChatInvocation");async function vT(e){let{buildKernel:t}=await import("../chunk-
|
|
640
|
+
`))}a(Dx,"runChatRepl");function yT(e,t){if(e.json&&!e.message)throw new C("--json requires --message (NDJSON output is one-shot only)",{code:"JSON_REQUIRES_MESSAGE",hint:'np primus chat --agent <ref> --message "\u2026" --json'});if(e.message){if(!e.agent&&!t)throw new C("--message without a TTY also needs --agent",{code:"AGENT_REQUIRED",hint:'np primus chat --agent <gid|name> --message "\u2026"'});return"oneshot"}if(!t)throw new C("interactive chat needs a TTY",{code:"NO_TTY",hint:'for scripts/CI use one-shot mode: np primus chat --agent <ref> --message "\u2026" [--json]'});return"repl"}a(yT,"assertChatInvocation");async function vT(e){let{buildKernel:t}=await import("../chunk-6BBB7BRP.mjs"),r=e??ne(process.env.NPAYLOAD_PRIMUS_API_URL,"primusApiUrl"),o=await t(r),n=r??ne(process.env.NPAYLOAD_API_URL,"apiUrl","https://api.npayload.com");return{kernel:o,baseUrl:n}}a(vT,"resolveChatKernel");async function bT(e,t,r,o,n,i={}){let s=i.fetchImpl?{fetchImpl:i.fetchImpl}:void 0,c=new AbortController,u=a(()=>c.abort(),"onSignal");process.on("SIGINT",u);try{let l;if(n){let m=new Wa(i.sinks);for await(let p of Fo(e,t,{agentGid:r.gid,input:o},c.signal,s)){if(m.onEvent(p),p.event==="done"){l=(p.data??{}).status;break}if(p.event==="error"){l="failed";break}}}else{let m=new yr(i.sinks?{sinks:i.sinks}:void 0);m.beginTurn();let p=Ja(Date.now()),f=Fo(e,t,{agentGid:r.gid,input:o},c.signal,s);for await(let g of f){let v=Ka(p,g,Date.now());p=v.state;for(let h of v.actions)m.apply(h);if(p.done)break}l=p.status}let d=l==="completed"?0:1;return process.exitCode=d,d}finally{process.off("SIGINT",u)}}a(bT,"runOneShot");function jx(e){e.command("chat").description("chat with an agent \u2014 streams the run's steps (phases, tool calls) and the reply live").option("--agent <ref>","agent gid or name (picker on a TTY when omitted)").option("--resume","pick one of the agent's conversations to continue").option("--message <text>","one-shot: send one message, print the reply, exit").option("--json","one-shot only: emit the raw stream as NDJSON").option("--api-url <url>","override the AI endpoint (defaults to npayload's own)").action(async t=>{try{let r=yT(t,je()),{kernel:o,baseUrl:n}=await vT(t.apiUrl),i;try{i=await qo(o)}catch(u){let l=u?.status;throw l===404?new C("the AI endpoint is not reachable at this base URL",{code:"PRIMUS_UNREACHABLE",hint:"check NPAYLOAD_PRIMUS_API_URL (or --api-url) names your AI endpoint",cause:u}):l===403?new C("your credential is missing the agents:read scope",{code:"CHAT_AUTH",hint:"re-run `npayload push` (permissions sync) or grant the ai scopes in the dashboard",cause:u}):u}let s=t.agent?Ya(i,t.agent):r==="oneshot"?(()=>{if(i.length===1)return i[0];throw new C("--message needs --agent when more than one agent exists",{code:"AGENT_REQUIRED",hint:`available: ${i.slice(0,8).map(u=>u.name).join(", ")}`})})():await Tg(o);if(r==="oneshot"){await bT(o,n,s,t.message,t.json===!0);return}await Dx(o,n,{agent:s},{resume:t.resume===!0})}catch(r){(r instanceof C||r instanceof be)&&de(r),process.stderr.write(hT.red(`\u2717 ${r instanceof Error?r.message:String(r)}
|
|
639
641
|
`)),process.exitCode=1}})}a(jx,"registerChat");import me from"chalk";import{readFileSync as wT,writeFileSync as Ux}from"fs";import{resolve as xT}from"path";function Lx(e,t){let r=[];for(let o of _r()){let n=e[o];if(n)for(let[i,s]of Object.entries(n))for(let c of un(o)){let u=ni(Tn(s,c.path))??[],l=new Map;for(let f of Object.keys(e[c.parent]??{}))l.set(f,{name:f,source:"config"});for(let f of t[c.parent]??[]){let g=l.get(f.name);l.set(f.name,{name:f.name,source:g?.source??"live",gid:f.gid??g?.gid})}let d=[...l.values()].sort((f,g)=>f.name.localeCompare(g.name)),m=new Set(d.map(f=>f.name)),p=u.filter(f=>!m.has(f));r.push({resource:o,key:i,spec:c,current:u,candidates:d,dangling:p})}}return r}a(Lx,"computeWiringSlots");function kT(e,t,r){if(Lh(e.current,t))return null;let o=e.spec.array?t:t[0]??null,n=t.map(s=>e.candidates.find(c=>c.name===s)?.gid).filter(s=>!!s),i=n.length?`// ${r}: ${n.join(", ")}`:void 0;return{resource:e.resource,key:e.key,field:e.spec.path,kind:"update-field",value:o,...i?{trailingComment:i}:{}}}a(kT,"slotToChange");function _T(e){let t=e.current.length?e.current.join(", "):me.dim("(none)"),r=e.dangling.length?me.red(` \u26A0 not found: ${e.dangling.join(", ")}`):"";return`${e.resource} "${e.key}" \u2192 ${e.spec.label}: ${t}${r}`}a(_T,"describeSlot");var $T={agents:"/v1/primus/agents",skills:"/v1/primus/skills",tools:"/v1/primus/tools"};async function ST(e,t){let r={},o=ne(process.env.NPAYLOAD_PRIMUS_API_URL,"primusApiUrl"),n;try{n=await It(o,t)}catch(s){return e(me.yellow(` \u2022 live topology unavailable (${s instanceof Error?s.message:String(s)}) \u2014 using config-declared candidates only
|
|
640
642
|
`)),r}let i=new Set;for(let s of _r())for(let c of un(s))i.add(c.parent);for(let s of i){let c=$T[s];if(c)try{let u=await n.send({method:"GET",path:c}),l=IT(u);r[s]=l.map(d=>({name:typeof d.name=="string"?d.name:"",gid:typeof d.gid=="string"?d.gid:void 0})).filter(d=>d.name)}catch(u){F(u),e(me.yellow(` \u2022 could not list ${s} (${u instanceof Error?u.message:String(u)})
|
|
641
643
|
`))}}return r}a(ST,"fetchLive");function IT(e){let t=e;return(Array.isArray(t)?t:Array.isArray(t.data)?t.data:[]).filter(o=>typeof o=="object"&&o!==null)}a(IT,"extractRows");async function PT(e){let t=e.sink??(u=>void process.stdout.write(u)),r={checkbox:dy,select:He,confirm:ly,...e.prompts},o=Lx(e.config,e.live);t(me.bold(`
|
|
@@ -682,7 +684,7 @@ Refusing a destructive op without a TTY; pass --yes to proceed.
|
|
|
682
684
|
`)),printError:e.printError??(b=>void process.stderr.write(`${b}
|
|
683
685
|
`))}),xv(t,{print:e.print??(b=>{process.stdout.write(`${JSON.stringify(b,null,2)}
|
|
684
686
|
`)}),printError:e.printError??(b=>{process.stderr.write(`${b}
|
|
685
|
-
`)}),...e.readSecret?{readSecret:e.readSecret}:{},confirm:e.confirm??Ng}),tx(t),fx(t),mx(t),lx(t),Wh(t),Kh(t),yx(t),zx(t),Px(t,{fetchAccountStatus:a(async()=>{try{let b={method:"GET",path:"/v1/billing/account-status",scope:"billing:read"},M=await(await c(b)).send(b);return M&&typeof M.tier=="string"?M:null}catch(b){return F(b),null}},"fetchAccountStatus")});let n=a(b=>{if(b.path.startsWith("/v1/primus/")){let T=ne(process.env.NPAYLOAD_PRIMUS_API_URL,"primusApiUrl");if(T)return{lane:"primus",url:T}}if(b.path.startsWith("/v1/account/")){let T=ne(process.env.NPAYLOAD_ACCOUNT_API_URL,"accountApiUrl");if(T)return{lane:"account",url:T}}if(b.path.startsWith("/v1/analytics/")){let T=ne(process.env.NPAYLOAD_ADMIN_API_URL,"adminApiUrl");if(T)return{lane:"analytics",url:T}}return{lane:"cell"}},"laneOf"),i=a(()=>{let b=t.opts().env;return An(typeof b=="string"&&b.trim()!==""?{explicitSlug:b}:{})},"resolveDispatchEnvSlug"),s=Jx({laneOf:n,resolveEnvSlug:i,build:a(async(b,T)=>{if(b){let{buildKernel:M}=await import("../chunk-
|
|
687
|
+
`)}),...e.readSecret?{readSecret:e.readSecret}:{},confirm:e.confirm??Ng}),tx(t),fx(t),mx(t),lx(t),Wh(t),Kh(t),yx(t),zx(t),Px(t,{fetchAccountStatus:a(async()=>{try{let b={method:"GET",path:"/v1/billing/account-status",scope:"billing:read"},M=await(await c(b)).send(b);return M&&typeof M.tier=="string"?M:null}catch(b){return F(b),null}},"fetchAccountStatus")});let n=a(b=>{if(b.path.startsWith("/v1/primus/")){let T=ne(process.env.NPAYLOAD_PRIMUS_API_URL,"primusApiUrl");if(T)return{lane:"primus",url:T}}if(b.path.startsWith("/v1/account/")){let T=ne(process.env.NPAYLOAD_ACCOUNT_API_URL,"accountApiUrl");if(T)return{lane:"account",url:T}}if(b.path.startsWith("/v1/analytics/")){let T=ne(process.env.NPAYLOAD_ADMIN_API_URL,"adminApiUrl");if(T)return{lane:"analytics",url:T}}return{lane:"cell"}},"laneOf"),i=a(()=>{let b=t.opts().env;return An(typeof b=="string"&&b.trim()!==""?{explicitSlug:b}:{})},"resolveDispatchEnvSlug"),s=Jx({laneOf:n,resolveEnvSlug:i,build:a(async(b,T)=>{if(b){let{buildKernel:M}=await import("../chunk-6BBB7BRP.mjs");return M(b,T)}return nc(T)},"build")}),c=a(b=>s.getKernelFor(b),"getKernelFor");kv(t,{print:e.print??(b=>{process.stdout.write(`${JSON.stringify(b,null,2)}
|
|
686
688
|
`)}),printError:e.printError??(b=>{process.stderr.write(`${b}
|
|
687
689
|
`)}),credential:a(async()=>{let b=process.env.NPAYLOAD_CLIENT_ID;if(b)return{clientId:b,source:"env"};let T=await kr();return{clientId:T.clientId,source:T.source}},"credential"),token:a(async()=>(await nc(i())).auth.getAccessToken([]),"token")}),kx(t,{resolveKernel:a(async()=>nc(i()),"resolveKernel"),mintedEnvSlug:a(()=>i(),"mintedEnvSlug"),yes:a(()=>t.opts().yes===!0,"yes"),tail:a(async(b,T)=>yg(b,T),"tail"),confirm:a(async b=>e.confirm?e.confirm(b):Ng(b),"confirm")}),_x(t,{resolveKernel:a(async()=>nc(i()),"resolveKernel"),mintedEnvSlug:a(()=>i(),"mintedEnvSlug")});let u=a(()=>{let b=t.opts().transport;if(b==="http"||b==="npp")return b;if(b!==void 0)throw new Y(`--transport must be "npp" or "http", got "${b}"`);return process.env.NPAYLOAD_TRANSPORT==="http"?"http":"npp"},"resolveCliTransport"),l=/^\/v1\/channels\/\{channelId\}\/messages$/,d=/^\/v1\/channels\/\{channelId\}\/subscribe$/,m=new Set(["payload","qosLevel"]),p=new WeakMap,f=a(b=>{let T=rn(b);return $h(process.env.NPAYLOAD_EDGE_URL,In(b),[Hg(b),`${T.replace(/\/+$/,"")}/v1/apps/dpop-keys`])},"nppEdgeOf"),g=a(b=>new be("NPP transport selected but not configured"+(b?`: ${b}`:". Set NPAYLOAD_EDGE_URL.")+" Or opt into HTTP/JSON explicitly with --transport http or NPAYLOAD_TRANSPORT=http."),"nppNotConfigured"),v=a(b=>{let{edgeUrl:T,refusal:M}=f(b);if(!T)throw g(M);let J=rn(b),H=p.get(b);return H||(H=Yg(b,{baseUrl:J,edgeUrl:T,clientId:process.env.NPAYLOAD_CLIENT_ID??"",appId:process.env.NPAYLOAD_APP_ID,sequenceStore:new tc}),p.set(b,H)),H},"getNppPublisher"),h=new Map,x=a((b,T)=>b.send({method:"GET",path:"/v1/channels/{channelId}",pathParams:{channelId:T}}),"readChannelAnswer"),E=new Map,k=new WeakMap,O=a(()=>ne(process.env.NPAYLOAD_API_URL,"apiUrl","https://api.npayload.com"),"cliApiUrl"),A=a((b,T)=>{let M=k.get(b);if(!M){let J=O(),H=ak(J,T);M=Qg(b,{baseUrl:J,frameDoorUrl:H.url,clientId:process.env.NPAYLOAD_CLIENT_ID??"",appId:process.env.NPAYLOAD_APP_ID,readChannel:a(async re=>{if(E.has(re)){let Zo=E.get(re);return E.delete(re),Zo}return x(b,re)},"readChannel"),producerEpoch:a(re=>ik(re),"producerEpoch"),...H.fetchImpl?{fetchImpl:H.fetchImpl}:{}}),k.set(b,M)}return M},"getKernelDoorPublisher"),j=a(async(b,T,M)=>{let J=h.get(T);if(!J){J=x(b,T).catch(()=>{}),h.set(T,J);let H=await J;ic(H)&&E.set(T,H)}if(ic(await J))return A(b,M)},"kernelDoorPublisherFor"),U=a(async b=>{let T=await c(b);if(u()==="npp"){let J=b.body??{};if(b.method==="POST"&&l.test(b.path)){if("payload"in J&&b.idempotencyKeySupplied!==!0&&Object.keys(J).every(re=>m.has(re)||J[re]===void 0)){let re=f(T);if(!re.edgeUrl&&!sk(O()))throw g(re.refusal);let nn=await(await j(T,b.pathParams.channelId,re)??await v(T)).publish(b.pathParams.channelId,J.payload,{...J.qosLevel!==void 0?{qosLevel:J.qosLevel}:{}});if(!nn.accepted)throw pA(nn);return ac({gid:nn.gid,status:"accepted",statusCode:nn.statusCode,statusName:nn.statusName,sequence:nn.sequence,httpStatus:nn.httpStatus,transport:"npp"})}}else if(b.method==="POST"&&d.test(b.path)){let H=await v(T),re=typeof J.consumerId=="string"&&J.consumerId||`consumer-${b.pathParams.channelId}`;return H.subscribe(b.pathParams.channelId,{consumerId:re,...typeof J.mode=="number"?{mode:J.mode}:{},...typeof J.deliveryPreference=="number"?{deliveryPreference:J.deliveryPreference}:{}})}}let M=await T.send(b);return b.method==="POST"&&l.test(b.path)?ac(M):M},"sendViaTransport");Bx(t,{send:U,newIdempotencyKey:a(()=>globalThis.crypto.randomUUID(),"newIdempotencyKey"),print:e.print??(b=>{process.stdout.write(`${JSON.stringify(b,null,2)}
|
|
688
690
|
`)}),printError:e.printError??(b=>{process.stderr.write(`${b}
|