@fugood/bricks-cli 2.26.0-beta.40 → 2.26.0-beta.41

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/lib/index.js CHANGED
@@ -54,7 +54,7 @@ Blueprint: ${e.name}`)),console.log("─".repeat(60)),console.log(`ID: ${
54
54
  ${s.default.bold("Overview")}`),console.log(e.description?.trim()||s.default.gray("(no overview)")),o.length>0&&(console.log(`
55
55
  ${s.default.bold("Referenced but not on the map")} (${o.length})`),o.forEach(e=>{var t=r.get(e.fromNodeId)||e.fromNodeId;console.log(` - ${h[e.kind]||e.kind} ${e.name||e.ref} ${s.default.gray(`(${e.ref}, from ${t})`)}`)})),console.log("─".repeat(60))})),b.command("graph <id>").description("Show blueprint nodes with authored and derived edges").option("-j, --json","Output as JSON").action(w((e,t)=>{var a=e.nodes||[],r=e.edges||[],o=e.derivedEdges||[];if(t.json)return void(0,d.GF)({_id:e._id,name:e.name,revision:e.revision,nodes:a.map(y),edges:r,derivedEdges:o});var i=new Map(a.map(e=>[e.id,e.name]));console.log(s.default.bold(`
56
56
  Blueprint Graph: ${e.name}`)),console.log(s.default.gray(`${e._id} \xb7 revision ${e.revision}`)),console.log("─".repeat(80)),console.log(`${s.default.bold("Nodes")} (${a.length})`),a.forEach(e=>{var t=h[e.kind]||e.kind;console.log(` ${s.default.gray(e.id)} ${t.padEnd(8)} ${e.name}${v(e)}`)}),D("Authored edges",r,i),D("Derived edges",o,i),console.log("─".repeat(80))})),b.command("members <id>").description("List blueprint nodes grouped by kind, with missing (tombstone) flags").option("-j, --json","Output as JSON").action(w((e,t)=>{var a=g(e.nodes);if(t.json)return void(0,d.GF)({_id:e._id,name:e.name,revision:e.revision,members:Object.fromEntries(Object.entries(a).map(([e,t])=>[e,t.map(({id:e,ref:t,name:a,missing:r,missing_reason:o})=>({id:e,ref:t,name:a,missing:r,missing_reason:o}))]))});console.log(s.default.bold(`
57
- Blueprint Members: ${e.name}`)),console.log("─".repeat(80));var r=Object.entries(a).filter(([,e])=>e.length>0);0===r.length&&console.log(s.default.yellow("No nodes")),r.forEach(([e,t])=>{console.log(`${s.default.bold(m[e])} (${t.length})`),t.forEach(e=>{var t=e.ref?s.default.gray(` (${e.ref})`):"";console.log(` - ${e.name}${t}${v(e)}`)}),console.log()})})),b.command("projection <id>").description("Print the projection text that the blueprint Orchestrator gets as its context").action((o=i(function*(e){var t=(0,l.requireAuth)(),a=(0,p.default)("Fetching blueprint projection...").start();try{var r=yield t.blueprintProjection({id:e});a.stop(),console.log(r)}catch(e){a.fail(`Failed to get blueprint projection: ${e.message}`),process.exit(1)}}),function(e){return o.apply(this,arguments)})),(0,u.H)(b,{resource:"blueprint",fetchById:(e,t)=>e.blueprint({id:t}),search:(e,t,a)=>e.blueprints({keyword:t,paginate:{limit:a}})})},50427(e,t,a){a.d(t,{Q:()=>eu});var r,o,i,n,s,p,d,l,u,c,m,h,f,v,g,y,D,w,b,_=a(99436),k=a(35679),E=a(73284),S=a(76760),C=a(67996),x=a(77598),$=a(48161),N=a(51455),A=a(27549),F=a(19557),T=8089,O=(r=_(function*(e,t,a=3e3){return(0,F.uE)(`http://${e}:${t}/buttress/info`,a)}),function(e,t){return r.apply(this,arguments)}),I=a(94370),j="bricks buttress node-credential",B=(0,I.default)`
57
+ Blueprint Members: ${e.name}`)),console.log("─".repeat(80));var r=Object.entries(a).filter(([,e])=>e.length>0);0===r.length&&console.log(s.default.yellow("No nodes")),r.forEach(([e,t])=>{console.log(`${s.default.bold(m[e])} (${t.length})`),t.forEach(e=>{var t=e.ref?s.default.gray(` (${e.ref})`):"";console.log(` - ${e.name}${t}${v(e)}`)}),console.log()})})),b.command("projection <id>").description("Print the projection text that the blueprint Orchestrator gets as its context").action((o=i(function*(e){var t=(0,l.requireAuth)(),a=(0,p.default)("Fetching blueprint projection...").start();try{var r=yield t.blueprintProjection({id:e});a.stop(),console.log(r)}catch(e){a.fail(`Failed to get blueprint projection: ${e.message}`),process.exit(1)}}),function(e){return o.apply(this,arguments)})),(0,u.H)(b,{resource:"blueprint",fetchById:(e,t)=>e.blueprint({id:t}),search:(e,t,a)=>e.blueprints({keyword:t,paginate:{limit:a}})})},50427(e,t,a){a.d(t,{Q:()=>em});var r,o,i,n,s,p,d,l,u,c,m,h,f,v,g,y,D,w,b,_,k=a(99436),E=a(35679),S=a(73284),C=a(76760),x=a(67996),$=a(77598),N=a(48161),A=a(51455),F=a(27549),T=a(19557),O=8089,I=(r=k(function*(e,t,a=3e3){return(0,T.uE)(`http://${e}:${t}/buttress/info`,a)}),function(e,t){return r.apply(this,arguments)}),j=a(94370),B="bricks buttress node-credential",P=(0,j.default)`
58
58
  query CLI_buttressRegistryCapabilities {
59
59
  bindResult: __type(name: "ButtressBindResult") {
60
60
  fields {
@@ -70,14 +70,17 @@ Blueprint Members: ${e.name}`)),console.log("─".repeat(80));var r=Object.entri
70
70
  mutationType {
71
71
  fields {
72
72
  name
73
+ args {
74
+ name
75
+ }
73
76
  }
74
77
  }
75
78
  }
76
79
  }
77
- `,P=e=>new Set((e?.fields||[]).map(({name:e})=>e)),R=(o=_(function*(e){var t=yield e.query(B),a=P(t?.bindResult);return{bindNodeCredential:a.has("nodeCredential")&&a.has("registry"),issueNodeCredential:P(t?.__schema?.mutationType).has("issueButtressNodeCredential"),registryTrust:P(t?.__schema?.queryType).has("registryTrust")}}),function(e){return o.apply(this,arguments)}),V=e=>"string"==typeof e&&Number.isFinite(Date.parse(e)),M=e=>{if(!e||"object"!=typeof e)return null;var t=e.token,a=e.jti,r=e.kid,o=e.issuedAt,i=e.expiresAt,n=e.renewAfter;return"string"==typeof t&&t&&"string"==typeof a&&"string"==typeof r&&[o,i,n].every(V)?{token:t,jti:a,kid:r,issuedAt:o,expiresAt:i,renewAfter:n}:null},L=(e,t=new Date().toISOString())=>{if(!e||"object"!=typeof e)return null;var a=e.issuer,r=e.audience,o=e.baseUrl,i=e.jwks;return"string"==typeof a&&"string"==typeof r&&"string"==typeof o&&Array.isArray(i?.keys)?{issuer:a,audience:r,baseUrl:o,jwks:i,fetchedAt:t}:null},U=e=>{try{var t=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf8"));return t&&"object"==typeof t?t:null}catch{return null}},q=(e,t)=>{var a,r,o,i,n,s=U(e?.token);if(!s||"kc"!==s.k||"node"!==s.st)return"it is not a node credential";if(String(s.w_id)!==String(t?.workspace?.id)||s.sid!==t?.workspace?.serverId)return"it belongs to another workspace or server";var p=null;try{a=t.serverKeyPair.publicKeySpki,o=(r=x.createPublicKey({key:Buffer.from(a,"base64"),format:"der",type:"spki"}).export({format:"jwk"})).crv,i=r.kty,n=r.x,p=x.createHash("sha256").update(JSON.stringify({crv:o,kty:i,x:n})).digest("base64url")}catch{return"the local state has no usable announce key"}return s.cnf?.jkt!==p?"it is bound to another announce key":null},J=(e,t=Date.now())=>{var a=U(e?.token);return{jti:e.jti,issuer:"string"==typeof a?.iss?a.iss:null,issuedAt:e.issuedAt,expiresAt:e.expiresAt,renewAfter:e.renewAfter,expired:!(Date.parse(e.expiresAt)>t),renewDue:!(Date.parse(e.renewAfter)>t)}},Y="A node credential needs Workspace management permission: a workspace token with the manage_devtools scope, or OAuth login with update-workspace. A CTOR MCP token cannot get one.",G=["privateKeyPkcs8"],K=["spacekey"],W=["token"],H=["token"],z=S.join($.homedir(),".bricks-cli","buttress"),Q=e=>S.join(e||z,"state.json"),X="buttress-functions",Z=(i=_(function*(e,t,a){var r,o,i,n=null,s=!0;try{n=JSON.parse((yield N.readFile(e,"utf8"))),s=!1}catch(t){if(t instanceof SyntaxError)throw Error(`${e} is not valid JSON; refusing to overwrite it.`);if("ENOENT"!==t.code)throw t}var p=(i=(o=(r=n)&&"object"==typeof r&&!Array.isArray(r)?r:{}).mcpServers&&"object"==typeof o.mcpServers&&!Array.isArray(o.mcpServers)?o.mcpServers:{},{...o,mcpServers:{...i,[t]:a}});return yield N.writeFile(e,`${JSON.stringify(p,null,2)}
78
- `,s?{mode:384}:{}),{file:e,created:s}}),function(e,t,a){return i.apply(this,arguments)}),ee=(e,t,a)=>{if(e?.workspace?.serverId!==t)return!1;var r=e.workspace.id;if(!r||!a||String(r)!==String(a))throw Error(`Local Buttress state belongs to workspace ${r||"unknown"}, but the current profile targets ${a||"unknown"}. Switch profiles first.`);return!0},et=()=>{try{return`buttress-${A.machineIdSync()}`}catch{return null}},ea=(n=_(function*({client:e,workspaceId:t,serverId:a,name:r,withRegistry:o=!1,onNodeCredentialDropped:i}){if(!t)throw Error("A workspace-authenticated client is required to bind Buttress.");var n,s,p,d,l,u,c=yield e.issueDevtoolsAccessToken({});if("string"!=typeof c?.token||!c.token||String(c.workspaceId)!==String(t)||!(Date.parse(c.expiresAt)>Date.now()))throw Error("DevTools token response is incomplete, expired, or belongs to another workspace.");var m=(s=(n=x.generateKeyPairSync("ed25519")).publicKey,p=n.privateKey,d=s.export({type:"spki",format:"der"}),l=p.export({type:"pkcs8",format:"der"}),u=x.createHash("sha256").update(d).digest("hex").slice(0,16),{publicKeySpki:d.toString("base64"),privateKeyPkcs8:l.toString("base64"),kid:u}),h={serverId:a,name:r,serverPublicKey:{spkiBase64:m.publicKeySpki,kid:m.kid}},f=o?yield e.bindButtressServerWithRegistry(h):yield e.bindButtressServer(h);if(String(f.workspaceId)!==String(t))throw Error("Buttress binding response belongs to another workspace.");var v={workspace:{id:f.workspaceId,name:f.workspaceName,serverId:f.serverId,issuerPublicKey:f.issuerPublicKey.pem,kid:f.issuerPublicKey.kid,boundAt:new Date().toISOString()},serverKeyPair:m,devtools:{token:c.token,workspaceId:c.workspaceId,expiresAt:c.expiresAt,...c.jti?{jti:c.jti}:{}}};if(o){var g=L(f.registry);g&&(v.registry=g);var y=M(f.nodeCredential),D=y&&q(y,v);D?i?.(D):y&&(v.nodeCredential=y)}return v}),function(e){return n.apply(this,arguments)}),er=(s=_(function*(e){var t=Q(e);try{var a=yield N.readFile(t,"utf8");return JSON.parse(a)}catch(e){if(e instanceof SyntaxError)throw Error("Buttress state.json contains invalid JSON.");if("ENOENT"===e.code)return null;throw e}}),function(e){return s.apply(this,arguments)}),eo=(p=_(function*(e,t){var a=t||z,r=Q(t);yield N.mkdir(a,{recursive:!0,mode:448}),yield N.chmod(a,448);var o=`${r}.tmp-${process.pid}-${x.randomUUID()}`;try{yield N.writeFile(o,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),yield N.chmod(o,384),yield N.rename(o,r),yield N.chmod(r,384)}catch(e){throw yield N.unlink(o).catch(()=>{}),e}return r}),function(e,t){return p.apply(this,arguments)}),ei=(d=_(function*(e,t,a,r){var o=yield er(r);if(o?.workspace?.serverId!==a?.serverId||o?.workspace?.id!==a?.id)throw Error("state.json now holds another binding; nothing was written.");var i={...o};return void 0===t?delete i[e]:i[e]=t,eo(i,r)}),function(e,t,a,r){return d.apply(this,arguments)}),en=(l=_(function*(e){var t=Q(e);try{return yield N.unlink(t),!0}catch(e){if("ENOENT"===e.code)return!1;throw e}}),function(e){return l.apply(this,arguments)}),es=(u=_(function*({client:e,serverId:t,workspaceId:a,stateDir:r,keepLocal:o=!1}){var i=o?null:yield er(r),n=!o&&ee(i,t,a);return{removed:yield e.unbindButtressServer({serverId:t}),localRemoved:!!n&&(yield en(r))}}),function(e){return u.apply(this,arguments)}),ep=(c=_(function*({timeout:e=3e3,verify:t=!0,port:a=T,onStatus:r}={}){r?.(`Scanning UDP ${a} for ${e}ms...`);var o,i=yield(({timeout:e=3e3,idleTimeout:t=0,port:a=T}={})=>(0,F.YH)({port:a,timeout:e,idleTimeout:t,buildQuery:()=>Buffer.from(JSON.stringify({t:"QUERY",v:"2.0",d:{id:`cli-${(0,F.BW)()}`}})),parseMessage:(e,t)=>{var a=(0,F.nl)(e,e=>e?.v==="2.0");if(!a)return null;var r={...a,address:t.address};return{key:r.id||`${t.address}:${r.port}`,value:r}}}))({timeout:e,port:a});return 0===i.length?[]:t?(r?.(`Verifying ${i.length} server(s)...`),yield Promise.all(i.map((o=_(function*(e){var t=yield O(e.address,e.port,2e3);return t?{...e,...t,address:e.address,verified:!0}:{...e,verified:!1}}),function(e){return o.apply(this,arguments)})))):i}),function(){return c.apply(this,arguments)}),ed=(m=_(function*(){var e=(yield Promise.resolve().then(a.bind(a,47988))).getCurrentProfile,t=(0,(yield Promise.resolve().then(a.bind(a,31802))).getConnectionContext)(e()),r=t.auth,o=t.baseUrl;return r||(console.error(E.default.red("Not logged in. Use `bricks auth login` first.")),process.exit(1)),{client:(0,(yield Promise.all([a.e(2499),a.e(8295),a.e(907)]).then(a.bind(a,85382))).createClient)(o,r),workspaceId:r.workspaceId,baseUrl:o}}),function(){return m.apply(this,arguments)}),el=({state:e,capabilities:t,droppedReason:a},r)=>{var o=`Run \`${j}\` to get one.`;if(!t){r(E.default.yellow("! The node credential was not requested: the BRICKS server schema check failed.")),r(E.default.gray(` ${o}`));return}if(t.bindNodeCredential){if(e.nodeCredential){var i=J(e.nodeCredential),n=i.expiresAt,s=i.issuer;r(` Node credential expires: ${n} ${E.default.gray(`(issuer ${s||"unknown"})`)}`);return}if(a){r(E.default.yellow(`! The issued node credential does not fit the new state (${a}) and was not stored.`)),r(E.default.gray(` ${o}`));return}if(r(E.default.yellow("! No BRICKS Registry node credential was issued with this bind.")),!e.registry){r(E.default.gray(" BRICKS Registry is off or not reachable on this BRICKS server.")),r(E.default.gray(` When it is on, run \`${j}\` to get one.`));return}r(E.default.gray(` ${o} ${Y}`))}},eu=new k.uB("buttress").description("Pair and inspect buttress-server bindings for the current workspace").alias("butr");eu.command("bind").description("Pair a local buttress-server and provision workspace DevTools access").option("-s, --server-id <id>","Buttress server id (auto-detected from machine id by default)").option("-n, --name <name>","Friendly name for this buttress server").option("--state-dir <dir>","Override the buttress state directory (defaults to ~/.bricks-cli/buttress)").option("--print","Print state.json to stdout instead of writing to disk (useful for remote setups)").action((h=_(function*(e){var t=(yield Promise.resolve().then(a.bind(a,14636))).default,r=e.serverId||et();r||(console.error(E.default.red("Could not detect a local server id. Pass --server-id <id> explicitly.")),process.exit(1));var o=yield ed(),i=o.client,n=o.workspaceId,s=t(`Binding buttress server ${E.default.cyan(r)}...`).start();try{var p=e.print?null:yield er(e.stateDir),d=yield R(i).catch(()=>null),l=null,u=yield ea({client:i,workspaceId:n,serverId:r,name:e.name,withRegistry:!!d?.bindNodeCredential,onNodeCredentialDropped:e=>{l=e}}),c={state:u,capabilities:d,droppedReason:l};if(s.stop(),e.print){console.warn(E.default.yellow("⚠ Output contains the announce private key, DevTools token and node credential. Treat as a secret.")),el(c,console.warn),process.stdout.write(`${JSON.stringify(u,null,2)}
79
- `);return}p?.bank&&p?.workspace?.id===u.workspace.id&&(u.bank=p.bank);var m=yield eo(u,e.stateDir);console.log(E.default.green("✓"),"Buttress server bound to workspace."),console.log(` Workspace: ${E.default.bold(u.workspace.name)} (${u.workspace.id})`),console.log(` Server id: ${E.default.cyan(u.workspace.serverId)}`),console.log(` Issuer kid: ${E.default.gray(u.workspace.kid)}`),console.log(` Announce kid: ${E.default.gray(u.serverKeyPair.kid)}`),console.log(` DevTools token expires: ${u.devtools.expiresAt}`),el(c,console.log),console.log(` State file: ${E.default.gray(m)}`),console.log(),console.log(E.default.yellow("Restart buttress-server for the binding to take effect."))}catch(e){s.fail(`Bind failed: ${e.message}`),process.exit(1)}}),function(e){return h.apply(this,arguments)})),eu.command("unbind").description("Unbind a buttress server from this workspace").option("-s, --server-id <id>","Buttress server id (auto-detected by default)").option("--state-dir <dir>","Override the buttress state directory").option("--keep-local","Do not remove the local state.json file").action((f=_(function*(e){var t=e.serverId||et();t||(console.error(E.default.red("Could not detect a local server id. Pass --server-id explicitly.")),process.exit(1));var a=yield ed(),r=a.client,o=a.workspaceId;try{var i=yield es({client:r,serverId:t,workspaceId:o,stateDir:e.stateDir,keepLocal:e.keepLocal}),n=i.removed,s=i.localRemoved;if(n?console.log(E.default.green("✓"),`Unbound ${E.default.cyan(t)} from workspace.`):console.log(E.default.yellow("!"),`${E.default.cyan(t)} was not bound to this workspace.`),s){var p=Q(e.stateDir);console.log(E.default.gray(`Removed local state file: ${p}`))}}catch(e){console.error(E.default.red(`Unbind failed: ${e.message}`)),process.exit(1)}}),function(e){return f.apply(this,arguments)})),eu.command("status").description("Show local buttress binding state and the workspace-side bound list").option("--state-dir <dir>","Override the buttress state directory").option("-j, --json","Output as JSON").action((v=_(function*(e){var t=yield er(e.stateDir),a=null;try{var r=(yield ed()).client;a=yield r.buttressServers()}catch(e){a={error:e.message}}if(e.json)return void console.log(JSON.stringify(((e,t)=>{var a=e;if(e?.serverKeyPair&&"object"==typeof e.serverKeyPair){var r=e.serverKeyPair,o=(r.privateKeyPkcs8,C(r,G));a={...a,serverKeyPair:o}}if(e?.bank&&"object"==typeof e.bank){var i=e.bank,n=(i.spacekey,C(i,K));a={...a,bank:n}}if(e?.devtools&&"object"==typeof e.devtools){var s=e.devtools,p=(s.token,C(s,W));a={...a,devtools:p}}if(e?.nodeCredential&&"object"==typeof e.nodeCredential){var d=e.nodeCredential,l=(d.token,C(d,H));a={...a,nodeCredential:l}}return{local:a,remote:t}})(t,a),null,2));if(console.log(E.default.bold("\nLocal buttress state")),console.log("─".repeat(60)),t?.workspace){console.log(` Workspace: ${E.default.bold(t.workspace.name)} (${t.workspace.id})`),console.log(` Server id: ${E.default.cyan(t.workspace.serverId)}`),console.log(` Issuer kid: ${E.default.gray(t.workspace.kid)}`),console.log(` Bound at: ${E.default.gray(t.workspace.boundAt)}`),console.log(` File: ${E.default.gray(Q(e.stateDir))}`),t.devtools&&console.log(` DevTools token expires: ${t.devtools.expiresAt}`);var o=M(t.nodeCredential);if(o){var i=J(o),n=i.expiresAt,s=i.issuer,p=i.expired,d=i.renewDue,l=q(o,t),u="";l?u=E.default.red(` (does not fit this state: ${l})`):p?u=E.default.red(" (expired)"):d&&(u=E.default.yellow(` (renewal due: run \`${j}\`)`)),console.log(` Node credential expires: ${n}${u}`),console.log(` Node credential issuer: ${E.default.gray(s||"unknown")}`)}else t.registry&&console.log(` Node credential: ${E.default.yellow("none")} `+E.default.gray(`(run \`${j}\`)`));t.bank&&console.log(` Data Bank: ${E.default.bold(t.bank.spacename)} ${E.default.gray(`(${t.bank.keyName||"key stored"}) @ ${t.bank.endpoint}`)}`)}else console.log(E.default.gray(" not bound (no state.json found)"));console.log(E.default.bold("\nWorkspace-side bound servers")),console.log("─".repeat(60)),Array.isArray(a)?0===a.length?console.log(E.default.gray(" none")):a.forEach(e=>{console.log(` ${E.default.cyan(e.serverId)} ${E.default.gray(e.name||"")} ${E.default.gray(e.boundAt||"")}`)}):a?.error&&console.log(E.default.red(` failed to fetch: ${a.error}`))}),function(e){return v.apply(this,arguments)})),eu.command("issue-token").description("Issue a long-lived workspace-scoped buttress access token (CLI/CTOR usage)").option("--ttl <seconds>","Time-to-live in seconds (default 30 days, max 90 days)",e=>parseInt(e,10)).option("-j, --json","Output as JSON").action((g=_(function*(e){var t=(yield ed()).client;try{var a=yield t.issueButtressAccessToken({ttlSeconds:e.ttl});if(e.json)return void console.log(JSON.stringify(a,null,2));console.log(E.default.green("✓"),"Buttress access token issued."),console.log(` Workspace: ${a.workspaceId}`),console.log(` Expires: ${a.expiresAt}`),console.log(` jti: ${E.default.gray(a.jti)}`),console.log(),console.log(E.default.cyan(a.token))}catch(e){console.error(E.default.red(`Issue token failed: ${e.message}`)),process.exit(1)}}),function(e){return g.apply(this,arguments)})),eu.command("bank-key").description("Issue a Data Bank space key for this buttress server's local functions (stored in state.json)").option("--state-dir <dir>","Override the buttress state directory").option("--key-name <name>","Key name prefix registered on the workspace","buttress-server").option("--revoke","Revoke the stored key and remove it from state.json").option("-j, --json","Output as JSON").action((y=_(function*(e){var t,r,o,i=yield er(e.stateDir);i?.workspace||(console.error(E.default.red("This host is not bound to a workspace. Run `bricks buttress bind` first.")),process.exit(1));var n=yield ed(),s=n.client,p=n.workspaceId,d=n.baseUrl;try{ee(i,i.workspace.serverId,p)}catch(e){console.error(E.default.red(e.message)),process.exit(1)}if(e.revoke){if(!i.bank?.spacekey)return void console.log(E.default.yellow("!"),"No Data Bank key is stored for this server.");try{yield s.updateWorkspace({revokeBankKey:i.bank.spacekey})}catch(e){console.error(E.default.red(`Revoke failed: ${e.message}`)),process.exit(1)}return(yield ei("bank",void 0,i.workspace,e.stateDir),e.json)?void console.log(JSON.stringify({revoked:!0},null,2)):(console.log(E.default.green("✓"),"Data Bank key revoked and removed from state.json."),void console.log(E.default.yellow("Restart buttress-server for the change to take effect.")))}var l=(yield Promise.resolve().then(a.bind(a,14636))).default,u=yield a.e(1936).then(a.bind(a,76627)),c=u.issueWorkspaceBankKey,m=u.BANK_DISABLED_MESSAGE,h=(yield a.e(9387).then(a.bind(a,30182))).resolveBankEndpoint;try{t=h(d)}catch(e){console.error(E.default.red(e.message)),process.exit(1)}var f=l("Issuing Data Bank space key...").start();try{r=yield c(s,{keyName:e.keyName,assertWorkspace:e=>{if(!e?._id||String(e._id)!==String(p))throw Error("The client targets another workspace. Switch profiles and retry.")}}),f.stop()}catch(e){f.fail(`Issue failed: ${e.message}`),e.message===m&&console.error(E.default.gray("Enable it first with `bricks data enable`.")),process.exit(1)}var v=i.bank,g={endpoint:t,...r};try{o=yield ei("bank",g,i.workspace,e.stateDir)}catch(e){throw yield s.updateWorkspace({revokeBankKey:g.spacekey}).catch(()=>{}),e}(v?.spacekey&&v.spacekey!==g.spacekey&&(yield s.updateWorkspace({revokeBankKey:v.spacekey}).catch(()=>{})),e.json)?console.log(JSON.stringify({endpoint:t,spacename:g.spacename,keyName:g.keyName,issuedAt:g.issuedAt,file:o},null,2)):(console.log(E.default.green("✓"),"Data Bank space key stored for this buttress server."),console.log(` Space: ${E.default.bold(g.spacename)} (${t})`),console.log(` Key name: ${E.default.cyan(g.keyName)}`),console.log(` State file: ${E.default.gray(o)}`),console.log(),console.log(E.default.yellow("Restart buttress-server so local functions pick it up (context.bank).")))}),function(e){return y.apply(this,arguments)})),eu.command("node-credential").description("Get a new BRICKS Registry node credential for the bound buttress server, without a rebind (stored in state.json)").option("--state-dir <dir>","Override the buttress state directory").option("--force","Get a new credential even when the stored one is not due for renewal").option("-j, --json","Output as JSON").action((D=_(function*(e){var t,r,o,i=yield er(e.stateDir);i?.workspace||(console.error(E.default.red("This host is not bound to a workspace. Run `bricks buttress bind` first.")),process.exit(1)),i.serverKeyPair?.publicKeySpki||(console.error(E.default.red("state.json has no announce key. Run `bricks buttress bind` again first.")),process.exit(1));var n=yield ed(),s=n.client,p=n.workspaceId;try{ee(i,i.workspace.serverId,p)}catch(e){console.error(E.default.red(e.message)),process.exit(1)}var d=M(i.nodeCredential);if(d&&!e.force&&!q(d,i)){var l=J(d);if(!l.renewDue)return e.json?void console.log(JSON.stringify({renewed:!1,...l},null,2)):(console.log(E.default.green("✓"),`The stored node credential is valid until ${l.expiresAt} and is not due for renewal until ${l.renewAfter}.`),void console.log(E.default.gray(" Use --force to get a new one now.")))}var u=(yield Promise.resolve().then(a.bind(a,14636))).default,c=i.workspace.serverId,m=u(`Getting a node credential for ${E.default.cyan(c)}...`).start();try{t=yield R(s)}catch(e){m.fail(`Could not read the BRICKS server schema: ${e.message}`),process.exit(1)}t.issueNodeCredential||(m.fail("This BRICKS server does not issue BRICKS Registry node credentials."),process.exit(1));try{if(!(r=M((yield s.issueButtressNodeCredential({serverId:c})))))throw Error("The node credential response is incomplete.")}catch(e){var h,f=(h=(e=>{var t,a=(t=e?.graphQLErrors??e?.cause?.graphQLErrors??[],t.find(e=>e?.extensions?.code)?.extensions??{}),r=(({retryAfterSeconds:e,retryAfterMs:t})=>Number.isFinite(e)&&e>0?e:Number.isFinite(t)&&t>0?Math.ceil(t/1e3):null)(a),o=r?` Try again in ${r} seconds.`:" Try again later.";switch(a.code){case"REGISTRY_DISABLED":return"BRICKS Registry is not enabled on this BRICKS server, so it issues no node credential.";case"REGISTRY_UNAVAILABLE":return`BRICKS Registry is not available right now.${o}`;case"REGISTRY_ISSUE_CONFLICT":return"The Buttress binding changed while the credential was issued (for example a rebind or an unbind). Run the command again.";case"REGISTRY_SUBJECT_NOT_ELIGIBLE":return"This server cannot get a node credential: the workspace has no binding for it, or the binding has no Ed25519 announce key. Run `bricks buttress bind` again.";case"rate_limited":return`BRICKS Registry or the workspace API refused: too many requests (for example, a node gets at most 5 credentials per hour and 10 per day).${o}`;default:return null}})(e))?{message:h,known:!0}:{message:e?.message||String(e),known:!1},v=f.message,g=f.known;m.fail(`Node credential not issued: ${v}`),g||console.error(E.default.gray(Y)),d&&console.error(E.default.gray("The stored node credential is kept.")),process.exit(1)}var y=q(r,i);y&&(m.fail(`The new node credential does not fit this state.json: ${y}. The workspace binding of ${c} changed, and this issue revoked its earlier node credential.`),console.error(E.default.gray(`Do not run this command again on this host. Run \`bricks buttress bind\` on the host that should run ${c}.`)),process.exit(1));var D=i.registry??null,w=null;if(t.registryTrust)try{D=L((yield s.registryTrust()))??D}catch(e){w=`Registry trust data not refreshed: ${e.message}`}try{o=yield eo({...i,nodeCredential:r,...D?{registry:D}:{}},e.stateDir)}catch(e){m.fail(`Could not save the node credential to state.json: ${e.message}`),process.exit(1)}m.stop(),w&&console.warn(E.default.yellow(`! ${w}`));var b=J(r);e.json?console.log(JSON.stringify({renewed:!0,serverId:c,...b,file:o},null,2)):(console.log(E.default.green("✓"),"Node credential stored for this buttress server."),console.log(` Server id: ${E.default.cyan(c)}`),console.log(` Issuer: ${E.default.gray(b.issuer||"unknown")}`),console.log(` Expires: ${b.expiresAt}`),console.log(` Renew after: ${b.renewAfter}`),console.log(` State file: ${E.default.gray(o)}`),console.log(),console.log(E.default.yellow("Restart buttress-server for the change to take effect.")))}),function(e){return D.apply(this,arguments)})),eu.command("mcp-config").description("Print (or write) the .mcp.json entry for a buttress server's local functions (experimental)").option("-u, --url <url>","Buttress server base URL (skips LAN discovery)").option("--ttl <seconds>","Token time-to-live in seconds (default 30 days, max 90 days)",e=>parseInt(e,10)).option("--no-token","Omit the access token (for an unauthenticated server)").option("-n, --name <name>","Server key to write in .mcp.json",X).option("-w, --write [file]","Merge into .mcp.json (defaults to ./.mcp.json)").option("-t, --timeout <ms>","Discovery timeout in milliseconds","3000").option("-j, --json","Output as JSON").action((w=_(function*(e){var t,r,o,i=(yield Promise.resolve().then(a.bind(a,14636))).default,n=yield Promise.resolve().then(a.bind(a,47988)),s=n.getCurrentProfile,p=n.getTokenInfo,d=e.url,l=null;if(!d){var u=i("Scanning for buttress-servers...").start();try{var c,m,h,f=yield ep({timeout:parseInt(e.timeout,10),onStatus:e=>{u.text=e}});u.stop();var v=p(s())?.workspaceId||null;h=(m=(c=(f||[]).filter(e=>!1!==e.verified&&e.address)).filter(e=>e.functions?.enabled)).length>0?m:c,l=0===h.length?null:v&&h.find(e=>e.workspace?.id===v)||h[0]}catch(e){u.fail(`Scan failed: ${e.message}`),process.exit(1)}l||(console.error(E.default.red("No buttress-server found on the LAN. Pass --url <base-url> explicitly.")),process.exit(1));var g=p(s())?.workspaceId||null,y=l.workspace?.id;!1===e.token||y&&y===g||(console.error(E.default.red(`Refusing to issue a token for ${l.name||l.address}: it reports workspace ${y||"(none — unbound)"}, not ${g||"(unknown)"}.`)),console.error(E.default.gray("Pass --url <base-url> to target it explicitly, or --no-token for an unauthenticated server.")),process.exit(1)),d=`http://${l.address}:${l.port}`,l.functions?.enabled||console.warn(E.default.yellow(`! ${l.name||d} does not advertise local functions. Enable [functions] in its config.`))}var D=null;if(!1!==e.token)try{var w=(yield ed()).client;D=(yield w.issueButtressAccessToken({ttlSeconds:e.ttl})).token}catch(e){console.error(E.default.red(`Could not issue an access token: ${e.message}`)),console.error(E.default.gray("Use --no-token for a server running with allow_unauthenticated = true.")),process.exit(1)}var b=(t=d,r=D,o=String(t).replace(/\/+$/,""),{url:`${o}/functions/mcp`,...r?{headers:{Authorization:`Bearer ${r}`}}:{}}),_=e.name||X;if(e.write){var k=S.resolve("string"==typeof e.write?e.write:".mcp.json");try{var C=(yield Z(k,_,b)).created;console.log(E.default.green("✓"),`${C?"Created":"Updated"} ${E.default.gray(k)} (${E.default.cyan(_)})`),console.log(` Endpoint: ${E.default.cyan(b.url)}`)}catch(e){console.error(E.default.red(e.message)),process.exit(1)}}else e.json?console.log(JSON.stringify({mcpServers:{[_]:b}},null,2)):(console.log(E.default.bold("\nAdd this to your .mcp.json:")),console.log(JSON.stringify({mcpServers:{[_]:b}},null,2)),console.log(),console.log(E.default.gray("Or re-run with --write to merge it automatically.")));D&&console.log(E.default.gray("\nThe entry embeds a workspace access token — treat .mcp.json as a secret and keep it out of version control."))}),function(e){return w.apply(this,arguments)})),eu.command("scan").description("Scan LAN for buttress-servers via UDP and verify each via /buttress/info").option("-t, --timeout <ms>","Scan timeout in milliseconds","3000").option("-p, --port <port>","UDP discovery port",String(T)).option("--udp-only","Skip HTTP /buttress/info verification").option("-j, --json","Output as JSON").action((b=_(function*(e){var t=(yield Promise.resolve().then(a.bind(a,14636))).default,r=yield Promise.resolve().then(a.bind(a,47988)),o=r.getCurrentProfile,i=r.getTokenInfo,n=parseInt(e.timeout,10),s=parseInt(e.port,10),p=[],d=t(`Scanning for buttress-servers (${n}ms)...`).start();try{p=yield ep({timeout:n,port:s,verify:!e.udpOnly,onStatus:e=>{d.text=e}}),d.stop()}catch(e){d.fail(`Scan failed: ${e.message}`),process.exit(1)}var l=o(),u=i(l)?.workspaceId||null;if(e.json)return void console.log(JSON.stringify({servers:p,workspaceId:u},null,2));if(0===p.length)return void console.log(E.default.yellow("No buttress-servers found on the LAN."));for(var c of(console.log(E.default.bold(`
80
- Found ${p.length} buttress-server(s)`)),console.log("─".repeat(70)),p)){var m=!1===c.verified?E.default.red("unverified"):E.default.green("online"),h=c.workspace?.id,f=h&&u&&h===u,v=c.authentication?.bound?E.default.yellow("JWT required"):E.default.gray("open");console.log(` ${E.default.bold(c.name||"Unknown")} ${E.default.gray(`(${c.address}:${c.port})`)} [${m}]`),c.id&&console.log(` Server id: ${E.default.cyan(c.id)}`),c.version&&console.log(` Version: ${E.default.green(c.version)}`);var g=c.authentication?.kid?E.default.gray(` (kid: ${c.authentication.kid})`):"";if(console.log(` Auth: ${v}${g}`),h){var y=f?E.default.green(`${h} ${E.default.bold("(current profile)")}`):E.default.gray(h);console.log(` Workspace: ${y}`)}if(Array.isArray(c.generators)&&c.generators.length>0)for(var D of(console.log(" Generators:"),c.generators)){var w=[];"number"==typeof D.score&&w.push(`score ${D.score.toFixed(1)}`),!0===D.hasGpu?w.push("GPU ✓"):!1===D.hasGpu&&w.push("GPU ✗"),"number"==typeof D.usableBytes&&w.push(`${(D.usableBytes/0x40000000).toFixed(1)} GB usable`);var b=w.length>0?` ${E.default.gray(w.join(" "))}`:"";console.log(` - ${E.default.cyan(D.type)}${b}`)}}console.log("─".repeat(70)),p.some(e=>e.authentication?.bound)&&(console.log(),console.log(E.default.gray("To connect to a bound server, run `bricks buttress issue-token` for a workspace access token.")))}),function(e){return b.apply(this,arguments)}))},71335(e,t,a){a.d(t,{oT:()=>l});var r=a(35679),o=a(73284),i=a(47988),n={prod:"https://display.bricks.tools",beta:"https://display-beta.bricks.tools",dev:"http://localhost:3001"},s=e=>{var t=Object.entries(n).find(([,t])=>e===t);return t?t[0]:null},p={prod:"https://activity-log.bricks.tools",beta:"https://activity-log-beta.bricks.tools",dev:"http://localhost:8088"},d=e=>{var t=Object.entries(p).find(([,t])=>e===t);return t?t[0]:null},l=new r.uB("config").description("CLI configuration management");l.command("endpoint").argument("[environment]","Environment to use (prod, beta, dev)").description("Show or set endpoint environment").option("-p, --profile","Set for current profile instead of global").action((e,t)=>{if(!e){var a=(0,i.getBaseUrl)(),r=s(a),l=(0,i.getActivityLogBaseUrl)(),u=d(l);console.log(o.default.bold("\nEndpoint Configuration")),console.log("─".repeat(50)),console.log(o.default.bold("BRICKS")),console.log(` URL: ${o.default.cyan(a)}`),console.log(` Environment: ${r?o.default.green(r):o.default.yellow("custom")}`),console.log(o.default.bold("Activity Log")),console.log(` URL: ${o.default.cyan(l)}`),console.log(` Environment: ${u?o.default.green(u):o.default.yellow("custom")}`),console.log("─".repeat(50)),console.log(o.default.gray("\nUsage: bricks config endpoint <prod|beta|dev>"));return}var c=Object.keys(n);c.includes(e)||(console.error(o.default.red(`Invalid environment: ${e}`)),console.log(o.default.gray(`Valid options: ${c.join(", ")}`)),process.exit(1));var m=n[e],h=p[e],f=t.profile?(0,i.getCurrentProfile)():null;(0,i.setBaseUrl)(m,f),(0,i.setActivityLogBaseUrl)(h,f);var v=t.profile?` (profile: ${(0,i.getCurrentProfile)()})`:"";console.log(o.default.green(`✓ Endpoint changed to ${e}${v}`)),console.log(o.default.gray(` BRICKS: ${m}`)),console.log(o.default.gray(` Activity Log: ${h}`)),console.log(o.default.yellow("\nNote: You may need to re-authenticate if your token is for a different environment.")),console.log(o.default.gray("Use `bricks auth status` to check your connection."))}),l.command("show").description("Show current configuration").option("-j, --json","Output as JSON").action(e=>{var t=(0,i.getBaseUrl)(),a=s(t);if(e.json)return void console.log(JSON.stringify({endpoint:t,environment:a||"custom"},null,2));console.log(o.default.bold("\nBRICKS CLI Configuration")),console.log("─".repeat(50)),console.log(`BRICKS: ${o.default.cyan(t)}`),a?console.log(`Environment: ${o.default.green(a)}`):console.log(`Environment: ${o.default.yellow("custom")}`);var r=(0,i.getActivityLogBaseUrl)(),n=d(r);console.log(`Activity Log: ${o.default.cyan(r)} ${n?o.default.green(`(${n})`):o.default.yellow("(custom)")}`),console.log("─".repeat(50))})},22175(e,t,a){a.d(t,{g:()=>f});var r,o,i,n,s,p,d,l,u=a(99436),c=a(35679),m=a(73284),h=a(90003),f=new c.uB("ctor").description("BRICKS Project (ctor) tooling: scaffold, sync, compile, deploy, and serve the project"),v=e=>{console.error(m.default.red(e?.message||String(e))),process.exit(1)};(0,h.x)(f.command("init <id>").description("Initialize a BRICKS Project from an application or module").option("--type <type>","Project type: app or module","app")).action((r=u(function*(e,t){var r="module"===t.type?"module":"application",o=(yield Promise.all([a.e(5658),a.e(4456)]).then(a.bind(a,58891))).initProject;yield o(r,e,t)}),function(e,t){return r.apply(this,arguments)})),f.command("postinstall").description("Regenerate the ctor/ library, MCP config, and skills (run from a project)").option("--skip-copy-project","Skip copying the ctor/ library into the project").option("--refresh-skills","Also overwrite bundled skill files whose content changed (default keeps existing skills)").option("--check","Compare the bundled ctor/skills assets against the project without writing (always exits 0; read the output)").option("-j, --json","With --check, output the comparison as JSON").action((o=u(function*(e){try{if(e.check){var t=(yield Promise.all([a.e(7111),a.e(1708)]).then(a.bind(a,37495))).checkProjectAssets,r=yield t();if(e.json)return void console.log(JSON.stringify(r,null,2));if(r.upToDate)return void console.log(`Project assets match the bundled snapshot (CLI ${r.cliVersion}).`);var o=(e,{changed:t,missing:a})=>{if(t.length||a.length){for(var r of(console.log(`${e}: ${t.length} changed, ${a.length} missing`),t))console.log(` ~ ${r}`);for(var o of a)console.log(` + ${o}`)}};console.log(`Project assets differ from the bundled snapshot (CLI ${r.cliVersion}):`),o("ctor/",r.lib),o("skills",r.skills),console.log("Run `bricks ctor postinstall --refresh-skills` to update them.");return}var i=(yield Promise.all([a.e(7111),a.e(1708)]).then(a.bind(a,37495))).postinstall;yield i(e)}catch(e){v(e)}}),function(e){return o.apply(this,arguments)})),f.command("pull").description("Pull the latest project files from BRICKS (3-way git merge)").option("-f, --force","Force pull, committing any uncommitted changes first").action((i=u(function*(e){try{var t=(yield a.e(9663).then(a.bind(a,47090))).pull;yield t(e)}catch(e){v(e)}}),function(e){return i.apply(this,arguments)})),f.command("push").description("Compile and push config to BRICKS without creating a release").option("--auto-commit","Auto-commit uncommitted changes before pushing").option("--no-check","Skip the conflict guard (don't pass --last-commit-id)").option("--no-validate","Skip server-side config schema validation").option("-y, --yes","Skip all prompts").action((n=u(function*(e){try{var t=(yield Promise.all([a.e(2151),a.e(8937),a.e(2517)]).then(a.bind(a,69620))).compile,r=(yield a.e(2557).then(a.bind(a,71772))).push;yield t({check:!0}),yield r(e)}catch(e){v(e)}}),function(e){return n.apply(this,arguments)})),f.command("deploy").description("Compile and create a new release only when requested; use push for normal updates").option("--changelogs <text>","Changelogs text for the release").option("--changelogs-file <path>","Read changelogs from a file").option("--auto-commit","Auto-commit uncommitted changes before deploying").option("--auto-version","Bump the local patch version; application version must exceed cloud releases").option("--version <version>","Set release version; application version must exceed cloud releases").option("-y, --yes","Skip all prompts").action((s=u(function*(e){try{var t=(yield Promise.all([a.e(2151),a.e(8937),a.e(2517)]).then(a.bind(a,69620))).compile,r=(yield a.e(1215).then(a.bind(a,42914))).deploy;yield t({check:!0}),yield r(e)}catch(e){v(e)}}),function(e){return s.apply(this,arguments)})),f.command("compile").description("Typecheck and build the project config").option("--no-check","Skip the typecheck preflight").action((p=u(function*(e){try{var t=(yield Promise.all([a.e(2151),a.e(8937),a.e(2517)]).then(a.bind(a,69620))).compile;yield t(e)}catch(e){v(e)}}),function(e){return p.apply(this,arguments)})),f.command("simulator").description("Run the BRICKS web-preview simulator for the project").allowUnknownOption(!0).helpOption(!1).action((d=u(function*(e,t){try{var r=(yield a.e(9320).then(a.bind(a,7931))).simulator;yield r(t.args)}catch(e){v(e)}}),function(e,t){return d.apply(this,arguments)})),f.command("mcp").description("Start the project-local bricks-ctor MCP server (STDIO)").option("--project <dir>","Project root (default: current directory)").action((l=u(function*(e){try{var t=(yield Promise.all([a.e(3781),a.e(39),a.e(6194)]).then(a.bind(a,95417))).startCtorMcpServer;yield t(e.project)}catch(e){v(e)}}),function(e){return l.apply(this,arguments)}))},55609(e,t,a){a.d(t,{E:()=>J});var r,o,i,n,s,p,d,l,u,c,m,h,f,v,g,y,D,w=a(68832),b=a(99436),_=a(79896),k=a(35679),E=a(73284),S=a(7586),C=a(56493),x=a(58021),$=a(47988),N=a(31596),A=a(98593),F=(r=b(function*(){return(yield Promise.resolve().then(a.bind(a,14636))).default}),function(){return r.apply(this,arguments)}),T=(o=b(function*(e,t){return e.json?null:(yield F())(t).start()}),function(e,t){return o.apply(this,arguments)}),O=(i=b(function*(){return a.e(1936).then(a.bind(a,76627))}),function(){return i.apply(this,arguments)}),I=(n=b(function*(){return a.e(9387).then(a.bind(a,30182))}),function(){return n.apply(this,arguments)}),j=({spinner:e,error:t,options:a,action:r,target:o})=>{var i=t.message;i?.includes(N.GE)?i=`${N.GE} Run \`bricks data enable\` first.`:t.isBankAuthError&&(i=`${i}
80
+ `,R=e=>new Set((e?.fields||[]).map(({name:e})=>e)),V=(o=k(function*(e){var t=yield e.query(P),a=R(t?.bindResult);return{accessTokenAudience:!!t?.__schema?.mutationType?.fields?.find(e=>"issueButtressAccessToken"===e.name)?.args?.some(e=>"serverId"===e.name),bindNodeCredential:a.has("nodeCredential")&&a.has("registry"),issueNodeCredential:R(t?.__schema?.mutationType).has("issueButtressNodeCredential"),registryTrust:R(t?.__schema?.queryType).has("registryTrust")}}),function(e){return o.apply(this,arguments)}),M=e=>"string"==typeof e&&Number.isFinite(Date.parse(e)),L=e=>{if(!e||"object"!=typeof e)return null;var t=e.token,a=e.jti,r=e.kid,o=e.issuedAt,i=e.expiresAt,n=e.renewAfter;return"string"==typeof t&&t&&"string"==typeof a&&"string"==typeof r&&[o,i,n].every(M)?{token:t,jti:a,kid:r,issuedAt:o,expiresAt:i,renewAfter:n}:null},U=(e,t=new Date().toISOString())=>{if(!e||"object"!=typeof e)return null;var a=e.issuer,r=e.audience,o=e.baseUrl,i=e.jwks;return"string"==typeof a&&"string"==typeof r&&"string"==typeof o&&Array.isArray(i?.keys)?{issuer:a,audience:r,baseUrl:o,jwks:i,fetchedAt:t}:null},q=e=>{try{var t=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf8"));return t&&"object"==typeof t?t:null}catch{return null}},J=(e,t)=>{var a,r,o,i,n,s=q(e?.token);if(!s||"kc"!==s.k||"node"!==s.st)return"it is not a node credential";if(String(s.w_id)!==String(t?.workspace?.id)||s.sid!==t?.workspace?.serverId)return"it belongs to another workspace or server";var p=null;try{a=t.serverKeyPair.publicKeySpki,o=(r=$.createPublicKey({key:Buffer.from(a,"base64"),format:"der",type:"spki"}).export({format:"jwk"})).crv,i=r.kty,n=r.x,p=$.createHash("sha256").update(JSON.stringify({crv:o,kty:i,x:n})).digest("base64url")}catch{return"the local state has no usable announce key"}return s.cnf?.jkt!==p?"it is bound to another announce key":null},Y=(e,t=Date.now())=>{var a=q(e?.token);return{jti:e.jti,issuer:"string"==typeof a?.iss?a.iss:null,issuedAt:e.issuedAt,expiresAt:e.expiresAt,renewAfter:e.renewAfter,expired:!(Date.parse(e.expiresAt)>t),renewDue:!(Date.parse(e.renewAfter)>t)}},G="A node credential needs Workspace management permission: a workspace token with the manage_devtools scope, or OAuth login with update-workspace. A CTOR MCP token cannot get one.",K=["privateKeyPkcs8"],W=["spacekey"],H=["token"],z=["token"],Q=C.join(N.homedir(),".bricks-cli","buttress"),X=e=>C.join(e||Q,"state.json"),Z="buttress-functions",ee=(i=k(function*(e,t,a){var r,o,i,n=null,s=!0;try{n=JSON.parse((yield A.readFile(e,"utf8"))),s=!1}catch(t){if(t instanceof SyntaxError)throw Error(`${e} is not valid JSON; refusing to overwrite it.`);if("ENOENT"!==t.code)throw t}var p=(i=(o=(r=n)&&"object"==typeof r&&!Array.isArray(r)?r:{}).mcpServers&&"object"==typeof o.mcpServers&&!Array.isArray(o.mcpServers)?o.mcpServers:{},{...o,mcpServers:{...i,[t]:a}});return yield A.writeFile(e,`${JSON.stringify(p,null,2)}
81
+ `,s?{mode:384}:{}),{file:e,created:s}}),function(e,t,a){return i.apply(this,arguments)}),et=(e,t,a)=>{if(e?.workspace?.serverId!==t)return!1;var r=e.workspace.id;if(!r||!a||String(r)!==String(a))throw Error(`Local Buttress state belongs to workspace ${r||"unknown"}, but the current profile targets ${a||"unknown"}. Switch profiles first.`);return!0},ea=()=>{try{return`buttress-${F.machineIdSync()}`}catch{return null}},er=(n=k(function*({client:e,workspaceId:t,serverId:a,name:r,withRegistry:o=!1,onNodeCredentialDropped:i}){if(!t)throw Error("A workspace-authenticated client is required to bind Buttress.");var n,s,p,d,l,u,c=yield e.issueDevtoolsAccessToken({});if("string"!=typeof c?.token||!c.token||String(c.workspaceId)!==String(t)||!(Date.parse(c.expiresAt)>Date.now()))throw Error("DevTools token response is incomplete, expired, or belongs to another workspace.");var m=(s=(n=$.generateKeyPairSync("ed25519")).publicKey,p=n.privateKey,d=s.export({type:"spki",format:"der"}),l=p.export({type:"pkcs8",format:"der"}),u=$.createHash("sha256").update(d).digest("hex").slice(0,16),{publicKeySpki:d.toString("base64"),privateKeyPkcs8:l.toString("base64"),kid:u}),h={serverId:a,name:r,serverPublicKey:{spkiBase64:m.publicKeySpki,kid:m.kid}},f=o?yield e.bindButtressServerWithRegistry(h):yield e.bindButtressServer(h);if(String(f.workspaceId)!==String(t))throw Error("Buttress binding response belongs to another workspace.");var v={workspace:{id:f.workspaceId,name:f.workspaceName,serverId:f.serverId,issuerPublicKey:f.issuerPublicKey.pem,kid:f.issuerPublicKey.kid,boundAt:new Date().toISOString()},serverKeyPair:m,devtools:{token:c.token,workspaceId:c.workspaceId,expiresAt:c.expiresAt,...c.jti?{jti:c.jti}:{}}};if(o){var g=U(f.registry);g&&(v.registry=g);var y=L(f.nodeCredential),D=y&&J(y,v);D?i?.(D):y&&(v.nodeCredential=y)}return v}),function(e){return n.apply(this,arguments)}),eo=(s=k(function*(e){var t=X(e);try{var a=yield A.readFile(t,"utf8");return JSON.parse(a)}catch(e){if(e instanceof SyntaxError)throw Error("Buttress state.json contains invalid JSON.");if("ENOENT"===e.code)return null;throw e}}),function(e){return s.apply(this,arguments)}),ei=(p=k(function*(e,t){var a=t||Q,r=X(t);yield A.mkdir(a,{recursive:!0,mode:448}),yield A.chmod(a,448);var o=`${r}.tmp-${process.pid}-${$.randomUUID()}`;try{yield A.writeFile(o,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),yield A.chmod(o,384),yield A.rename(o,r),yield A.chmod(r,384)}catch(e){throw yield A.unlink(o).catch(()=>{}),e}return r}),function(e,t){return p.apply(this,arguments)}),en=(d=k(function*(e,t,a,r){var o=yield eo(r);if(o?.workspace?.serverId!==a?.serverId||o?.workspace?.id!==a?.id)throw Error("state.json now holds another binding; nothing was written.");var i={...o};return void 0===t?delete i[e]:i[e]=t,ei(i,r)}),function(e,t,a,r){return d.apply(this,arguments)}),es=(l=k(function*(e){var t=X(e);try{return yield A.unlink(t),!0}catch(e){if("ENOENT"===e.code)return!1;throw e}}),function(e){return l.apply(this,arguments)}),ep=(u=k(function*({client:e,serverId:t,workspaceId:a,stateDir:r,keepLocal:o=!1}){var i=o?null:yield eo(r),n=!o&&et(i,t,a);return{removed:yield e.unbindButtressServer({serverId:t}),localRemoved:!!n&&(yield es(r))}}),function(e){return u.apply(this,arguments)}),ed=(c=k(function*({timeout:e=3e3,verify:t=!0,port:a=O,onStatus:r}={}){r?.(`Scanning UDP ${a} for ${e}ms...`);var o,i=yield(({timeout:e=3e3,idleTimeout:t=0,port:a=O}={})=>(0,T.YH)({port:a,timeout:e,idleTimeout:t,buildQuery:()=>Buffer.from(JSON.stringify({t:"QUERY",v:"2.0",d:{id:`cli-${(0,T.BW)()}`}})),parseMessage:(e,t)=>{var a=(0,T.nl)(e,e=>e?.v==="2.0");if(!a)return null;var r={...a,address:t.address};return{key:r.id||`${t.address}:${r.port}`,value:r}}}))({timeout:e,port:a});return 0===i.length?[]:t?(r?.(`Verifying ${i.length} server(s)...`),yield Promise.all(i.map((o=k(function*(e){var t=yield I(e.address,e.port,2e3);return t?{...e,...t,address:e.address,verified:!0}:{...e,verified:!1}}),function(e){return o.apply(this,arguments)})))):i}),function(){return c.apply(this,arguments)}),el=(m=k(function*(){var e=(yield Promise.resolve().then(a.bind(a,47988))).getCurrentProfile,t=(0,(yield Promise.resolve().then(a.bind(a,31802))).getConnectionContext)(e()),r=t.auth,o=t.baseUrl;return r||(console.error(S.default.red("Not logged in. Use `bricks auth login` first.")),process.exit(1)),{client:(0,(yield Promise.all([a.e(2499),a.e(8295),a.e(907)]).then(a.bind(a,85382))).createClient)(o,r),workspaceId:r.workspaceId,baseUrl:o}}),function(){return m.apply(this,arguments)}),eu=(h=k(function*(e,t,{serverId:a,discovered:r}={}){var o=a??r?.id;if(null!=o){var i=yield V(e).catch(()=>null);if(i?.accessTokenAudience){var n=o,s=r?.envelope?.kid;if(s){var p=yield e.buttressServerKeys().catch(()=>[]);n=p?.find(e=>e.serverPublicKey?.kid===s)?.serverId??o}return e.issueButtressServerAccessToken({serverId:n,ttlSeconds:t})}if(null!=a)throw Error("The workspace API did not advertise support for a server-limited token.")}return e.issueButtressAccessToken({ttlSeconds:t})}),function(e,t){return h.apply(this,arguments)}),ec=({state:e,capabilities:t,droppedReason:a},r)=>{var o=`Run \`${B}\` to get one.`;if(!t){r(S.default.yellow("! The node credential was not requested: the BRICKS server schema check failed.")),r(S.default.gray(` ${o}`));return}if(t.bindNodeCredential){if(e.nodeCredential){var i=Y(e.nodeCredential),n=i.expiresAt,s=i.issuer;r(` Node credential expires: ${n} ${S.default.gray(`(issuer ${s||"unknown"})`)}`);return}if(a){r(S.default.yellow(`! The issued node credential does not fit the new state (${a}) and was not stored.`)),r(S.default.gray(` ${o}`));return}if(r(S.default.yellow("! No BRICKS Registry node credential was issued with this bind.")),!e.registry){r(S.default.gray(" BRICKS Registry is off or not reachable on this BRICKS server.")),r(S.default.gray(` When it is on, run \`${B}\` to get one.`));return}r(S.default.gray(` ${o} ${G}`))}},em=new E.uB("buttress").description("Pair and inspect buttress-server bindings for the current workspace").alias("butr");em.command("bind").description("Pair a local buttress-server and provision workspace DevTools access").option("-s, --server-id <id>","Buttress server id (auto-detected from machine id by default)").option("-n, --name <name>","Friendly name for this buttress server").option("--state-dir <dir>","Override the buttress state directory (defaults to ~/.bricks-cli/buttress)").option("--print","Print state.json to stdout instead of writing to disk (useful for remote setups)").action((f=k(function*(e){var t=(yield Promise.resolve().then(a.bind(a,14636))).default,r=e.serverId||ea();r||(console.error(S.default.red("Could not detect a local server id. Pass --server-id <id> explicitly.")),process.exit(1));var o=yield el(),i=o.client,n=o.workspaceId,s=t(`Binding buttress server ${S.default.cyan(r)}...`).start();try{var p=e.print?null:yield eo(e.stateDir),d=yield V(i).catch(()=>null),l=null,u=yield er({client:i,workspaceId:n,serverId:r,name:e.name,withRegistry:!!d?.bindNodeCredential,onNodeCredentialDropped:e=>{l=e}}),c={state:u,capabilities:d,droppedReason:l};if(s.stop(),e.print){console.warn(S.default.yellow("⚠ Output contains the announce private key, DevTools token and node credential. Treat as a secret.")),ec(c,console.warn),process.stdout.write(`${JSON.stringify(u,null,2)}
82
+ `);return}p?.bank&&p?.workspace?.id===u.workspace.id&&(u.bank=p.bank);var m=yield ei(u,e.stateDir);console.log(S.default.green("✓"),"Buttress server bound to workspace."),console.log(` Workspace: ${S.default.bold(u.workspace.name)} (${u.workspace.id})`),console.log(` Server id: ${S.default.cyan(u.workspace.serverId)}`),console.log(` Issuer kid: ${S.default.gray(u.workspace.kid)}`),console.log(` Announce kid: ${S.default.gray(u.serverKeyPair.kid)}`),console.log(` DevTools token expires: ${u.devtools.expiresAt}`),ec(c,console.log),console.log(` State file: ${S.default.gray(m)}`),console.log(),console.log(S.default.yellow("Restart buttress-server for the binding to take effect."))}catch(e){s.fail(`Bind failed: ${e.message}`),process.exit(1)}}),function(e){return f.apply(this,arguments)})),em.command("unbind").description("Unbind a buttress server from this workspace").option("-s, --server-id <id>","Buttress server id (auto-detected by default)").option("--state-dir <dir>","Override the buttress state directory").option("--keep-local","Do not remove the local state.json file").action((v=k(function*(e){var t=e.serverId||ea();t||(console.error(S.default.red("Could not detect a local server id. Pass --server-id explicitly.")),process.exit(1));var a=yield el(),r=a.client,o=a.workspaceId;try{var i=yield ep({client:r,serverId:t,workspaceId:o,stateDir:e.stateDir,keepLocal:e.keepLocal}),n=i.removed,s=i.localRemoved;if(n?console.log(S.default.green("✓"),`Unbound ${S.default.cyan(t)} from workspace.`):console.log(S.default.yellow("!"),`${S.default.cyan(t)} was not bound to this workspace.`),s){var p=X(e.stateDir);console.log(S.default.gray(`Removed local state file: ${p}`))}}catch(e){console.error(S.default.red(`Unbind failed: ${e.message}`)),process.exit(1)}}),function(e){return v.apply(this,arguments)})),em.command("status").description("Show local buttress binding state and the workspace-side bound list").option("--state-dir <dir>","Override the buttress state directory").option("-j, --json","Output as JSON").action((g=k(function*(e){var t=yield eo(e.stateDir),a=null;try{var r=(yield el()).client;a=yield r.buttressServers()}catch(e){a={error:e.message}}if(e.json)return void console.log(JSON.stringify(((e,t)=>{var a=e;if(e?.serverKeyPair&&"object"==typeof e.serverKeyPair){var r=e.serverKeyPair,o=(r.privateKeyPkcs8,x(r,K));a={...a,serverKeyPair:o}}if(e?.bank&&"object"==typeof e.bank){var i=e.bank,n=(i.spacekey,x(i,W));a={...a,bank:n}}if(e?.devtools&&"object"==typeof e.devtools){var s=e.devtools,p=(s.token,x(s,H));a={...a,devtools:p}}if(e?.nodeCredential&&"object"==typeof e.nodeCredential){var d=e.nodeCredential,l=(d.token,x(d,z));a={...a,nodeCredential:l}}return{local:a,remote:t}})(t,a),null,2));if(console.log(S.default.bold("\nLocal buttress state")),console.log("─".repeat(60)),t?.workspace){console.log(` Workspace: ${S.default.bold(t.workspace.name)} (${t.workspace.id})`),console.log(` Server id: ${S.default.cyan(t.workspace.serverId)}`),console.log(` Issuer kid: ${S.default.gray(t.workspace.kid)}`),console.log(` Bound at: ${S.default.gray(t.workspace.boundAt)}`),console.log(` File: ${S.default.gray(X(e.stateDir))}`),t.devtools&&console.log(` DevTools token expires: ${t.devtools.expiresAt}`);var o=L(t.nodeCredential);if(o){var i=Y(o),n=i.expiresAt,s=i.issuer,p=i.expired,d=i.renewDue,l=J(o,t),u="";l?u=S.default.red(` (does not fit this state: ${l})`):p?u=S.default.red(" (expired)"):d&&(u=S.default.yellow(` (renewal due: run \`${B}\`)`)),console.log(` Node credential expires: ${n}${u}`),console.log(` Node credential issuer: ${S.default.gray(s||"unknown")}`)}else t.registry&&console.log(` Node credential: ${S.default.yellow("none")} `+S.default.gray(`(run \`${B}\`)`));t.bank&&console.log(` Data Bank: ${S.default.bold(t.bank.spacename)} ${S.default.gray(`(${t.bank.keyName||"key stored"}) @ ${t.bank.endpoint}`)}`)}else console.log(S.default.gray(" not bound (no state.json found)"));console.log(S.default.bold("\nWorkspace-side bound servers")),console.log("─".repeat(60)),Array.isArray(a)?0===a.length?console.log(S.default.gray(" none")):a.forEach(e=>{console.log(` ${S.default.cyan(e.serverId)} ${S.default.gray(e.name||"")} ${S.default.gray(e.boundAt||"")}`)}):a?.error&&console.log(S.default.red(` failed to fetch: ${a.error}`))}),function(e){return g.apply(this,arguments)})),em.command("issue-token").option("-s, --server-id <id>","Limit the token to this bound server").description("Issue a long-lived workspace-scoped buttress access token (CLI/CTOR usage)").option("--ttl <seconds>","Time-to-live in seconds (default 30 days, max 90 days)",e=>parseInt(e,10)).option("-j, --json","Output as JSON").action((y=k(function*(e){var t=(yield el()).client;try{var a=yield eu(t,e.ttl,{serverId:e.serverId});if(e.json)return void console.log(JSON.stringify(a,null,2));console.log(S.default.green("✓"),"Buttress access token issued."),console.log(` Workspace: ${a.workspaceId}`),console.log(` Expires: ${a.expiresAt}`),console.log(` jti: ${S.default.gray(a.jti)}`),console.log(),console.log(S.default.cyan(a.token))}catch(e){console.error(S.default.red(`Issue token failed: ${e.message}`)),process.exit(1)}}),function(e){return y.apply(this,arguments)})),em.command("bank-key").description("Issue a Data Bank space key for this buttress server's local functions (stored in state.json)").option("--state-dir <dir>","Override the buttress state directory").option("--key-name <name>","Key name prefix registered on the workspace","buttress-server").option("--revoke","Revoke the stored key and remove it from state.json").option("-j, --json","Output as JSON").action((D=k(function*(e){var t,r,o,i=yield eo(e.stateDir);i?.workspace||(console.error(S.default.red("This host is not bound to a workspace. Run `bricks buttress bind` first.")),process.exit(1));var n=yield el(),s=n.client,p=n.workspaceId,d=n.baseUrl;try{et(i,i.workspace.serverId,p)}catch(e){console.error(S.default.red(e.message)),process.exit(1)}if(e.revoke){if(!i.bank?.spacekey)return void console.log(S.default.yellow("!"),"No Data Bank key is stored for this server.");try{yield s.updateWorkspace({revokeBankKey:i.bank.spacekey})}catch(e){console.error(S.default.red(`Revoke failed: ${e.message}`)),process.exit(1)}return(yield en("bank",void 0,i.workspace,e.stateDir),e.json)?void console.log(JSON.stringify({revoked:!0},null,2)):(console.log(S.default.green("✓"),"Data Bank key revoked and removed from state.json."),void console.log(S.default.yellow("Restart buttress-server for the change to take effect.")))}var l=(yield Promise.resolve().then(a.bind(a,14636))).default,u=yield a.e(1936).then(a.bind(a,76627)),c=u.issueWorkspaceBankKey,m=u.BANK_DISABLED_MESSAGE,h=(yield a.e(9387).then(a.bind(a,30182))).resolveBankEndpoint;try{t=h(d)}catch(e){console.error(S.default.red(e.message)),process.exit(1)}var f=l("Issuing Data Bank space key...").start();try{r=yield c(s,{keyName:e.keyName,assertWorkspace:e=>{if(!e?._id||String(e._id)!==String(p))throw Error("The client targets another workspace. Switch profiles and retry.")}}),f.stop()}catch(e){f.fail(`Issue failed: ${e.message}`),e.message===m&&console.error(S.default.gray("Enable it first with `bricks data enable`.")),process.exit(1)}var v=i.bank,g={endpoint:t,...r};try{o=yield en("bank",g,i.workspace,e.stateDir)}catch(e){throw yield s.updateWorkspace({revokeBankKey:g.spacekey}).catch(()=>{}),e}(v?.spacekey&&v.spacekey!==g.spacekey&&(yield s.updateWorkspace({revokeBankKey:v.spacekey}).catch(()=>{})),e.json)?console.log(JSON.stringify({endpoint:t,spacename:g.spacename,keyName:g.keyName,issuedAt:g.issuedAt,file:o},null,2)):(console.log(S.default.green("✓"),"Data Bank space key stored for this buttress server."),console.log(` Space: ${S.default.bold(g.spacename)} (${t})`),console.log(` Key name: ${S.default.cyan(g.keyName)}`),console.log(` State file: ${S.default.gray(o)}`),console.log(),console.log(S.default.yellow("Restart buttress-server so local functions pick it up (context.bank).")))}),function(e){return D.apply(this,arguments)})),em.command("node-credential").description("Get a new BRICKS Registry node credential for the bound buttress server, without a rebind (stored in state.json)").option("--state-dir <dir>","Override the buttress state directory").option("--force","Get a new credential even when the stored one is not due for renewal").option("-j, --json","Output as JSON").action((w=k(function*(e){var t,r,o,i=yield eo(e.stateDir);i?.workspace||(console.error(S.default.red("This host is not bound to a workspace. Run `bricks buttress bind` first.")),process.exit(1)),i.serverKeyPair?.publicKeySpki||(console.error(S.default.red("state.json has no announce key. Run `bricks buttress bind` again first.")),process.exit(1));var n=yield el(),s=n.client,p=n.workspaceId;try{et(i,i.workspace.serverId,p)}catch(e){console.error(S.default.red(e.message)),process.exit(1)}var d=L(i.nodeCredential);if(d&&!e.force&&!J(d,i)){var l=Y(d);if(!l.renewDue)return e.json?void console.log(JSON.stringify({renewed:!1,...l},null,2)):(console.log(S.default.green("✓"),`The stored node credential is valid until ${l.expiresAt} and is not due for renewal until ${l.renewAfter}.`),void console.log(S.default.gray(" Use --force to get a new one now.")))}var u=(yield Promise.resolve().then(a.bind(a,14636))).default,c=i.workspace.serverId,m=u(`Getting a node credential for ${S.default.cyan(c)}...`).start();try{t=yield V(s)}catch(e){m.fail(`Could not read the BRICKS server schema: ${e.message}`),process.exit(1)}t.issueNodeCredential||(m.fail("This BRICKS server does not issue BRICKS Registry node credentials."),process.exit(1));try{if(!(r=L((yield s.issueButtressNodeCredential({serverId:c})))))throw Error("The node credential response is incomplete.")}catch(e){var h,f=(h=(e=>{var t,a=(t=e?.graphQLErrors??e?.cause?.graphQLErrors??[],t.find(e=>e?.extensions?.code)?.extensions??{}),r=(({retryAfterSeconds:e,retryAfterMs:t})=>Number.isFinite(e)&&e>0?e:Number.isFinite(t)&&t>0?Math.ceil(t/1e3):null)(a),o=r?` Try again in ${r} seconds.`:" Try again later.";switch(a.code){case"REGISTRY_DISABLED":return"BRICKS Registry is not enabled on this BRICKS server, so it issues no node credential.";case"REGISTRY_UNAVAILABLE":return`BRICKS Registry is not available right now.${o}`;case"REGISTRY_ISSUE_CONFLICT":return"The Buttress binding changed while the credential was issued (for example a rebind or an unbind). Run the command again.";case"REGISTRY_SUBJECT_NOT_ELIGIBLE":return"This server cannot get a node credential: the workspace has no binding for it, or the binding has no Ed25519 announce key. Run `bricks buttress bind` again.";case"rate_limited":return`BRICKS Registry or the workspace API refused: too many requests (for example, a node gets at most 5 credentials per hour and 10 per day).${o}`;default:return null}})(e))?{message:h,known:!0}:{message:e?.message||String(e),known:!1},v=f.message,g=f.known;m.fail(`Node credential not issued: ${v}`),g||console.error(S.default.gray(G)),d&&console.error(S.default.gray("The stored node credential is kept.")),process.exit(1)}var y=J(r,i);y&&(m.fail(`The new node credential does not fit this state.json: ${y}. The workspace binding of ${c} changed, and this issue revoked its earlier node credential.`),console.error(S.default.gray(`Do not run this command again on this host. Run \`bricks buttress bind\` on the host that should run ${c}.`)),process.exit(1));var D=i.registry??null,w=null;if(t.registryTrust)try{D=U((yield s.registryTrust()))??D}catch(e){w=`Registry trust data not refreshed: ${e.message}`}try{o=yield ei({...i,nodeCredential:r,...D?{registry:D}:{}},e.stateDir)}catch(e){m.fail(`Could not save the node credential to state.json: ${e.message}`),process.exit(1)}m.stop(),w&&console.warn(S.default.yellow(`! ${w}`));var b=Y(r);e.json?console.log(JSON.stringify({renewed:!0,serverId:c,...b,file:o},null,2)):(console.log(S.default.green("✓"),"Node credential stored for this buttress server."),console.log(` Server id: ${S.default.cyan(c)}`),console.log(` Issuer: ${S.default.gray(b.issuer||"unknown")}`),console.log(` Expires: ${b.expiresAt}`),console.log(` Renew after: ${b.renewAfter}`),console.log(` State file: ${S.default.gray(o)}`),console.log(),U(i.registry)?(console.log(S.default.yellow("Buttress 2.26 or later takes the new credential within 60 seconds.")),console.log(S.default.yellow("Restart an older buttress-server for the change to take effect."))):console.log(S.default.yellow("Restart buttress-server for the change to take effect.")))}),function(e){return w.apply(this,arguments)})),em.command("mcp-config").description("Print (or write) the .mcp.json entry for a buttress server's local functions (experimental)").option("-u, --url <url>","Buttress server base URL (skips LAN discovery)").option("--ttl <seconds>","Token time-to-live in seconds (default 30 days, max 90 days)",e=>parseInt(e,10)).option("--no-token","Omit the access token (for an unauthenticated server)").option("-n, --name <name>","Server key to write in .mcp.json",Z).option("-w, --write [file]","Merge into .mcp.json (defaults to ./.mcp.json)").option("-t, --timeout <ms>","Discovery timeout in milliseconds","3000").option("-j, --json","Output as JSON").action((b=k(function*(e){var t,r,o,i=(yield Promise.resolve().then(a.bind(a,14636))).default,n=yield Promise.resolve().then(a.bind(a,47988)),s=n.getCurrentProfile,p=n.getTokenInfo,d=e.url,l=null;if(!d){var u=i("Scanning for buttress-servers...").start();try{var c,m,h,f=yield ed({timeout:parseInt(e.timeout,10),onStatus:e=>{u.text=e}});u.stop();var v=p(s())?.workspaceId||null;h=(m=(c=(f||[]).filter(e=>!1!==e.verified&&e.address)).filter(e=>e.functions?.enabled)).length>0?m:c,l=0===h.length?null:v&&h.find(e=>e.workspace?.id===v)||h[0]}catch(e){u.fail(`Scan failed: ${e.message}`),process.exit(1)}l||(console.error(S.default.red("No buttress-server found on the LAN. Pass --url <base-url> explicitly.")),process.exit(1));var g=p(s())?.workspaceId||null,y=l.workspace?.id;!1===e.token||y&&y===g||(console.error(S.default.red(`Refusing to issue a token for ${l.name||l.address}: it reports workspace ${y||"(none — unbound)"}, not ${g||"(unknown)"}.`)),console.error(S.default.gray("Pass --url <base-url> to target it explicitly, or --no-token for an unauthenticated server.")),process.exit(1)),d=`http://${l.address}:${l.port}`,l.functions?.enabled||console.warn(S.default.yellow(`! ${l.name||d} does not advertise local functions. Enable [functions] in its config.`))}var D=null;if(!1!==e.token)try{var w=(yield el()).client;D=(yield eu(w,e.ttl,{discovered:l})).token}catch(e){console.error(S.default.red(`Could not issue an access token: ${e.message}`)),console.error(S.default.gray("Use --no-token for a server running with allow_unauthenticated = true.")),process.exit(1)}var b=(t=d,r=D,o=String(t).replace(/\/+$/,""),{url:`${o}/functions/mcp`,...r?{headers:{Authorization:`Bearer ${r}`}}:{}}),_=e.name||Z;if(e.write){var k=C.resolve("string"==typeof e.write?e.write:".mcp.json");try{var E=(yield ee(k,_,b)).created;console.log(S.default.green("✓"),`${E?"Created":"Updated"} ${S.default.gray(k)} (${S.default.cyan(_)})`),console.log(` Endpoint: ${S.default.cyan(b.url)}`)}catch(e){console.error(S.default.red(e.message)),process.exit(1)}}else e.json?console.log(JSON.stringify({mcpServers:{[_]:b}},null,2)):(console.log(S.default.bold("\nAdd this to your .mcp.json:")),console.log(JSON.stringify({mcpServers:{[_]:b}},null,2)),console.log(),console.log(S.default.gray("Or re-run with --write to merge it automatically.")));D&&console.log(S.default.gray("\nThe entry embeds a workspace access token — treat .mcp.json as a secret and keep it out of version control."))}),function(e){return b.apply(this,arguments)})),em.command("scan").description("Scan LAN for buttress-servers via UDP and verify each via /buttress/info").option("-t, --timeout <ms>","Scan timeout in milliseconds","3000").option("-p, --port <port>","UDP discovery port",String(O)).option("--udp-only","Skip HTTP /buttress/info verification").option("-j, --json","Output as JSON").action((_=k(function*(e){var t=(yield Promise.resolve().then(a.bind(a,14636))).default,r=yield Promise.resolve().then(a.bind(a,47988)),o=r.getCurrentProfile,i=r.getTokenInfo,n=parseInt(e.timeout,10),s=parseInt(e.port,10),p=[],d=t(`Scanning for buttress-servers (${n}ms)...`).start();try{p=yield ed({timeout:n,port:s,verify:!e.udpOnly,onStatus:e=>{d.text=e}}),d.stop()}catch(e){d.fail(`Scan failed: ${e.message}`),process.exit(1)}var l=o(),u=i(l)?.workspaceId||null;if(e.json)return void console.log(JSON.stringify({servers:p,workspaceId:u},null,2));if(0===p.length)return void console.log(S.default.yellow("No buttress-servers found on the LAN."));for(var c of(console.log(S.default.bold(`
83
+ Found ${p.length} buttress-server(s)`)),console.log("─".repeat(70)),p)){var m=!1===c.verified?S.default.red("unverified"):S.default.green("online"),h=c.workspace?.id,f=h&&u&&h===u,v=c.authentication?.bound?S.default.yellow("JWT required"):S.default.gray("open");console.log(` ${S.default.bold(c.name||"Unknown")} ${S.default.gray(`(${c.address}:${c.port})`)} [${m}]`),c.id&&console.log(` Server id: ${S.default.cyan(c.id)}`),c.version&&console.log(` Version: ${S.default.green(c.version)}`);var g=c.authentication?.kid?S.default.gray(` (kid: ${c.authentication.kid})`):"";if(console.log(` Auth: ${v}${g}`),h){var y=f?S.default.green(`${h} ${S.default.bold("(current profile)")}`):S.default.gray(h);console.log(` Workspace: ${y}`)}if(Array.isArray(c.generators)&&c.generators.length>0)for(var D of(console.log(" Generators:"),c.generators)){var w=[];"number"==typeof D.score&&w.push(`score ${D.score.toFixed(1)}`),!0===D.hasGpu?w.push("GPU ✓"):!1===D.hasGpu&&w.push("GPU ✗"),"number"==typeof D.usableBytes&&w.push(`${(D.usableBytes/0x40000000).toFixed(1)} GB usable`);var b=w.length>0?` ${S.default.gray(w.join(" "))}`:"";console.log(` - ${S.default.cyan(D.type)}${b}`)}}console.log("─".repeat(70)),p.some(e=>e.authentication?.bound)&&(console.log(),console.log(S.default.gray("To connect to a bound server, run `bricks buttress issue-token` for a workspace access token.")))}),function(e){return _.apply(this,arguments)}))},71335(e,t,a){a.d(t,{oT:()=>l});var r=a(35679),o=a(73284),i=a(47988),n={prod:"https://display.bricks.tools",beta:"https://display-beta.bricks.tools",dev:"http://localhost:3001"},s=e=>{var t=Object.entries(n).find(([,t])=>e===t);return t?t[0]:null},p={prod:"https://activity-log.bricks.tools",beta:"https://activity-log-beta.bricks.tools",dev:"http://localhost:8088"},d=e=>{var t=Object.entries(p).find(([,t])=>e===t);return t?t[0]:null},l=new r.uB("config").description("CLI configuration management");l.command("endpoint").argument("[environment]","Environment to use (prod, beta, dev)").description("Show or set endpoint environment").option("-p, --profile","Set for current profile instead of global").action((e,t)=>{if(!e){var a=(0,i.getBaseUrl)(),r=s(a),l=(0,i.getActivityLogBaseUrl)(),u=d(l);console.log(o.default.bold("\nEndpoint Configuration")),console.log("─".repeat(50)),console.log(o.default.bold("BRICKS")),console.log(` URL: ${o.default.cyan(a)}`),console.log(` Environment: ${r?o.default.green(r):o.default.yellow("custom")}`),console.log(o.default.bold("Activity Log")),console.log(` URL: ${o.default.cyan(l)}`),console.log(` Environment: ${u?o.default.green(u):o.default.yellow("custom")}`),console.log("─".repeat(50)),console.log(o.default.gray("\nUsage: bricks config endpoint <prod|beta|dev>"));return}var c=Object.keys(n);c.includes(e)||(console.error(o.default.red(`Invalid environment: ${e}`)),console.log(o.default.gray(`Valid options: ${c.join(", ")}`)),process.exit(1));var m=n[e],h=p[e],f=t.profile?(0,i.getCurrentProfile)():null;(0,i.setBaseUrl)(m,f),(0,i.setActivityLogBaseUrl)(h,f);var v=t.profile?` (profile: ${(0,i.getCurrentProfile)()})`:"";console.log(o.default.green(`✓ Endpoint changed to ${e}${v}`)),console.log(o.default.gray(` BRICKS: ${m}`)),console.log(o.default.gray(` Activity Log: ${h}`)),console.log(o.default.yellow("\nNote: You may need to re-authenticate if your token is for a different environment.")),console.log(o.default.gray("Use `bricks auth status` to check your connection."))}),l.command("show").description("Show current configuration").option("-j, --json","Output as JSON").action(e=>{var t=(0,i.getBaseUrl)(),a=s(t);if(e.json)return void console.log(JSON.stringify({endpoint:t,environment:a||"custom"},null,2));console.log(o.default.bold("\nBRICKS CLI Configuration")),console.log("─".repeat(50)),console.log(`BRICKS: ${o.default.cyan(t)}`),a?console.log(`Environment: ${o.default.green(a)}`):console.log(`Environment: ${o.default.yellow("custom")}`);var r=(0,i.getActivityLogBaseUrl)(),n=d(r);console.log(`Activity Log: ${o.default.cyan(r)} ${n?o.default.green(`(${n})`):o.default.yellow("(custom)")}`),console.log("─".repeat(50))})},22175(e,t,a){a.d(t,{g:()=>f});var r,o,i,n,s,p,d,l,u=a(99436),c=a(35679),m=a(73284),h=a(90003),f=new c.uB("ctor").description("BRICKS Project (ctor) tooling: scaffold, sync, compile, deploy, and serve the project"),v=e=>{console.error(m.default.red(e?.message||String(e))),process.exit(1)};(0,h.x)(f.command("init <id>").description("Initialize a BRICKS Project from an application or module").option("--type <type>","Project type: app or module","app")).action((r=u(function*(e,t){var r="module"===t.type?"module":"application",o=(yield Promise.all([a.e(5658),a.e(4456)]).then(a.bind(a,58891))).initProject;yield o(r,e,t)}),function(e,t){return r.apply(this,arguments)})),f.command("postinstall").description("Regenerate the ctor/ library, MCP config, and skills (run from a project)").option("--skip-copy-project","Skip copying the ctor/ library into the project").option("--refresh-skills","Also overwrite bundled skill files whose content changed (default keeps existing skills)").option("--check","Compare the bundled ctor/skills assets against the project without writing (always exits 0; read the output)").option("-j, --json","With --check, output the comparison as JSON").action((o=u(function*(e){try{if(e.check){var t=(yield Promise.all([a.e(7111),a.e(1708)]).then(a.bind(a,37495))).checkProjectAssets,r=yield t();if(e.json)return void console.log(JSON.stringify(r,null,2));if(r.upToDate)return void console.log(`Project assets match the bundled snapshot (CLI ${r.cliVersion}).`);var o=(e,{changed:t,missing:a})=>{if(t.length||a.length){for(var r of(console.log(`${e}: ${t.length} changed, ${a.length} missing`),t))console.log(` ~ ${r}`);for(var o of a)console.log(` + ${o}`)}};console.log(`Project assets differ from the bundled snapshot (CLI ${r.cliVersion}):`),o("ctor/",r.lib),o("skills",r.skills),console.log("Run `bricks ctor postinstall --refresh-skills` to update them.");return}var i=(yield Promise.all([a.e(7111),a.e(1708)]).then(a.bind(a,37495))).postinstall;yield i(e)}catch(e){v(e)}}),function(e){return o.apply(this,arguments)})),f.command("pull").description("Pull the latest project files from BRICKS (3-way git merge)").option("-f, --force","Force pull, committing any uncommitted changes first").action((i=u(function*(e){try{var t=(yield a.e(9663).then(a.bind(a,47090))).pull;yield t(e)}catch(e){v(e)}}),function(e){return i.apply(this,arguments)})),f.command("push").description("Compile and push config to BRICKS without creating a release").option("--auto-commit","Auto-commit uncommitted changes before pushing").option("--no-check","Skip the conflict guard (don't pass --last-commit-id)").option("--no-validate","Skip server-side config schema validation").option("-y, --yes","Skip all prompts").action((n=u(function*(e){try{var t=(yield Promise.all([a.e(2151),a.e(8937),a.e(2517)]).then(a.bind(a,69620))).compile,r=(yield a.e(2557).then(a.bind(a,71772))).push;yield t({check:!0}),yield r(e)}catch(e){v(e)}}),function(e){return n.apply(this,arguments)})),f.command("deploy").description("Compile and create a new release only when requested; use push for normal updates").option("--changelogs <text>","Changelogs text for the release").option("--changelogs-file <path>","Read changelogs from a file").option("--auto-commit","Auto-commit uncommitted changes before deploying").option("--auto-version","Bump the local patch version; application version must exceed cloud releases").option("--version <version>","Set release version; application version must exceed cloud releases").option("-y, --yes","Skip all prompts").action((s=u(function*(e){try{var t=(yield Promise.all([a.e(2151),a.e(8937),a.e(2517)]).then(a.bind(a,69620))).compile,r=(yield a.e(1215).then(a.bind(a,42914))).deploy;yield t({check:!0}),yield r(e)}catch(e){v(e)}}),function(e){return s.apply(this,arguments)})),f.command("compile").description("Typecheck and build the project config").option("--no-check","Skip the typecheck preflight").action((p=u(function*(e){try{var t=(yield Promise.all([a.e(2151),a.e(8937),a.e(2517)]).then(a.bind(a,69620))).compile;yield t(e)}catch(e){v(e)}}),function(e){return p.apply(this,arguments)})),f.command("simulator").description("Run the BRICKS web-preview simulator for the project").allowUnknownOption(!0).helpOption(!1).action((d=u(function*(e,t){try{var r=(yield a.e(9320).then(a.bind(a,7931))).simulator;yield r(t.args)}catch(e){v(e)}}),function(e,t){return d.apply(this,arguments)})),f.command("mcp").description("Start the project-local bricks-ctor MCP server (STDIO)").option("--project <dir>","Project root (default: current directory)").action((l=u(function*(e){try{var t=(yield Promise.all([a.e(3781),a.e(39),a.e(6194)]).then(a.bind(a,95417))).startCtorMcpServer;yield t(e.project)}catch(e){v(e)}}),function(e){return l.apply(this,arguments)}))},55609(e,t,a){a.d(t,{E:()=>J});var r,o,i,n,s,p,d,l,u,c,m,h,f,v,g,y,D,w=a(68832),b=a(99436),_=a(79896),k=a(35679),E=a(73284),S=a(7586),C=a(56493),x=a(58021),$=a(47988),N=a(31596),A=a(98593),F=(r=b(function*(){return(yield Promise.resolve().then(a.bind(a,14636))).default}),function(){return r.apply(this,arguments)}),T=(o=b(function*(e,t){return e.json?null:(yield F())(t).start()}),function(e,t){return o.apply(this,arguments)}),O=(i=b(function*(){return a.e(1936).then(a.bind(a,76627))}),function(){return i.apply(this,arguments)}),I=(n=b(function*(){return a.e(9387).then(a.bind(a,30182))}),function(){return n.apply(this,arguments)}),j=({spinner:e,error:t,options:a,action:r,target:o})=>{var i=t.message;i?.includes(N.GE)?i=`${N.GE} Run \`bricks data enable\` first.`:t.isBankAuthError&&(i=`${i}
81
84
  The Data Bank key may be invalid or revoked — run \`bricks data login\` to reissue.`),a.json?(0,S.OW)(i,{action:r,...o&&{target:o}}):e?e.fail(i):console.error(E.default.red(i)),process.exit(1)},B=e=>{try{return JSON.parse(e)}catch{return e}},P=(e,t)=>{try{return JSON.parse(e)}catch{throw Error(`Invalid JSON for ${t}`)}},R=e=>e.split(",").map(e=>e.trim()).filter(Boolean),V=e=>e.masked?e.value:(0,S.$l)(e.value),M=e=>({name:e.name,meta:e.meta,value:V(e),enableExpired:!!e.enableExpired,expiredAt:e.expiredAt||null,createAt:e.createAt||null,hasReadLimit:!!e.limitedReadProperties?.length,hasWriteLimit:!!e.limitedWriteProperties?.length}),L=(s=b(function*(e){var t=yield e.workspace();return t?.bank||{}}),function(e){return s.apply(this,arguments)}),U=()=>{var e=(0,$.getCurrentProfile)(),t=(0,C.requireAuthConnection)(e),a=t.baseUrl,r=t.client;return{profile:e,baseUrl:a,client:r,fingerprint:t.fingerprint,bank:t.bank}},q=(p=b(function*(e,{profile:t,baseUrl:a,fingerprint:r,bank:o}){var i=(yield O()).resolveBankCredentials,n=yield I(),s=n.createBankClient,p=n.resolveBankEndpoint,d=yield i(e,{profile:t,expectedProfile:r,bank:o});return s({endpoint:p(a),spacename:d.spacename,spacekey:d.spacekey})}),function(e,t){return p.apply(this,arguments)}),J=new k.uB("data").description("Data Bank (remote properties) management");J.command("status").description("Show Data Bank status for this workspace").option("-j, --json","Output as JSON").action((d=b(function*(e){var t=U(),a=t.client,r=t.bank,o=yield T(e,"Fetching Data Bank status...");try{var i=yield L(a),n={enabled:!!i.enable_remote_update,spacename:i.spacename||null,keys:(i.keys||[]).map(M),cliKey:r?{keyName:r.keyName||null,spacekey:(0,S.$l)(r.spacekey),issuedAt:r.issuedAt||null}:null};if(o&&o.stop(),e.json)return void(0,S.GF)(n);console.log(E.default.bold("\nData Bank")),console.log("─".repeat(60)),console.log(`Enabled: ${n.enabled?E.default.green("Yes"):E.default.red("No")}`),console.log(`Spacename: ${n.spacename||E.default.gray("N/A")}`),console.log(`Keys: ${n.keys.length}`),console.log(`CLI Key: ${n.cliKey?`${n.cliKey.keyName||"Unnamed"} ${E.default.gray(`(${n.cliKey.spacekey})`)}`:E.default.gray("none (issued automatically on first use)")}`),console.log("─".repeat(60)),n.enabled||console.log(E.default.yellow("Run `bricks data enable` to enable Data Bank."))}catch(t){j({spinner:o,error:t,options:e,action:"data.status"})}}),function(e){return d.apply(this,arguments)}));var Y=(l=b(function*(e,t){var a=U().client,r=e?"data.enable":"data.disable",o=yield T(t,`${e?"Enabling":"Disabling"} Data Bank...`);try{var i=yield a.updateWorkspace({enableBankRemoteUpdate:e}),n=i?.bank||{};o&&o.stop(),(0,A.writeMutationSuccess)({action:r,target:{spacename:n.spacename||null},result:{enabled:!!n.enable_remote_update},json:t.json,message:e?`${E.default.green("Data Bank enabled.")} Spacename: ${E.default.cyan(n.spacename)}`:E.default.green("Data Bank disabled.")})}catch(e){j({spinner:o,error:e,options:t,action:r})}}),function(e,t){return l.apply(this,arguments)});J.command("enable").description("Enable Data Bank on this workspace").option("-j, --json","Output as JSON").action(e=>Y(!0,e)),J.command("disable").description("Disable Data Bank on this workspace").option("-j, --json","Output as JSON").action(e=>Y(!1,e)),J.command("login").description("Issue a Data Bank space key and save it to the active profile").option("--name <keyName>","Space key name","bricks-cli").option("-j, --json","Output as JSON").action((u=b(function*(e){var t=U(),a=t.client,r=t.profile,o=t.fingerprint,i=t.bank,n=yield T(e,"Issuing Data Bank key...");try{var s=(yield O()).issueBankCredentials,p=yield s(a,{keyName:e.name,profile:r,expectedProfile:o,bank:i});n&&n.stop(),(0,A.writeMutationSuccess)({action:"data.login",target:{spacename:p.spacename},result:{keyName:p.keyName,spacekey:(0,S.$l)(p.spacekey),issuedAt:p.issuedAt},json:e.json,message:`${E.default.green("Data Bank key issued and saved.")} ${E.default.gray(`(${p.keyName}, stored in ${$.CONFIG_PATH})`)}`})}catch(t){j({spinner:n,error:t,options:e,action:"data.login"})}}),function(e){return u.apply(this,arguments)})),J.command("logout").description("Remove the stored Data Bank key from the active profile").option("--revoke","Also revoke the key on the workspace").option("-j, --json","Output as JSON").action((c=b(function*(e){var t=U(),a=t.client,r=t.profile,o=t.fingerprint,i=t.bank,n=yield T(e,"Clearing Data Bank key...");try{var s=(yield O()).clearStoredBankCredentials,p=yield s(a,{revoke:e.revoke,profile:r,expectedProfile:o,bank:i}),d=p.cleared,l=p.revoked;n&&n.stop(),(0,A.writeMutationSuccess)({action:"data.logout",target:{profile:r},result:{cleared:d,revoked:l},json:e.json,message:d?E.default.green(`Data Bank key removed${l?" and revoked":""}.`):E.default.yellow("No Data Bank key stored for this profile.")})}catch(t){j({spinner:n,error:t,options:e,action:"data.logout"})}}),function(e){return c.apply(this,arguments)}));var G=new k.uB("keys").description("Data Bank space key management");J.addCommand(G),G.command("list").description("List Data Bank space keys (values are masked; --json shows them when readable)").option("-j, --json","Output as JSON (includes full key values when this login may read them)").action((m=b(function*(e){var t=U().client,a=yield T(e,"Fetching space keys...");try{var r=(yield L(t)).keys||[];if(a&&a.stop(),e.json)return void(0,S.GF)(r);if(0===r.length)return void console.log(E.default.yellow("No space keys found"));console.log(E.default.bold("\nData Bank Space Keys")),console.log("─".repeat(60)),r.map(M).forEach(e=>{var t=e.enableExpired?`expires ${e.expiredAt}`:"no expiry",a=[e.hasReadLimit&&"read-limited",e.hasWriteLimit&&"write-limited"].filter(Boolean).join(", ");console.log(`● ${E.default.cyan(e.name||"Unnamed")} ${E.default.gray(`(${e.meta})`)}`),console.log(` Value: ${E.default.gray(e.value)}`),console.log(` Expiry: ${E.default.gray(t)}${a?E.default.gray(`, ${a}`):""}`),console.log()}),console.log("─".repeat(60))}catch(t){j({spinner:a,error:t,options:e,action:"data.keys.list"})}}),function(e){return m.apply(this,arguments)})),G.command("new <name>").description("Create a new Data Bank space key").option("--expire-at <date>","Expiry time (ISO date, between 1 hour and 90 days from now)").option("--read <propertyIds>","Limit readable properties (comma separated)").option("--write <propertyIds>","Limit writable properties (comma separated)").option("-j, --json","Output as JSON").action((h=b(function*(e,t){var a=U().client,r=yield T(t,"Creating space key...");try{if(t.expireAt&&Number.isNaN(Date.parse(t.expireAt)))throw Error(`Invalid --expire-at date: ${t.expireAt}`);var o=yield L(a),i=new Set((o.keys||[]).map(e=>e.value)),n=yield a.updateWorkspace({newBankKey:{name:e,enableExpired:!!t.expireAt,expiredAt:t.expireAt,limitedReadProps:t.read?R(t.read):void 0,limitedWriteProps:t.write?R(t.write):void 0}}),s=(n?.bank?.keys||[]).filter(e=>!e.masked),p=s.find(e=>!i.has(e.value))||s.filter(t=>t.name===e).at(-1);if(!p)throw Error("Space key was not created");r&&r.stop(),(0,A.writeMutationSuccess)({action:"data.keys.new",target:{name:e},result:p,json:t.json,message:E.default.green(`Space key "${e}" created.`)}),t.json||(console.log(E.default.yellow("\n⚠ Copy this key now — it will not be shown again in full:")),console.log(p.value))}catch(a){j({spinner:r,error:a,options:t,action:"data.keys.new",target:{name:e}})}}),function(e,t){return h.apply(this,arguments)})),G.command("revoke <keyOrName>").description("Revoke a Data Bank space key by value or name").option("-y, --yes","Skip confirmation prompt").option("-j, --json","Output as JSON").action((f=b(function*(e,t){var a=U().client,r=yield T(t,"Resolving space key...");try{var o=yield L(a),i=((e,t)=>{var a=e.find(e=>e.value===t||e.masked&&t.length>8&&e.value===`…${t.slice(-4)}`);if(a)return{key:a,value:t};var r=e.filter(e=>e.name===t);if(0===r.length)throw Error(`No space key matched "${t}"`);if(r.length>1)throw Error(`Multiple space keys named "${t}"; pass the exact key value instead`);var o=w(r,1)[0];if(o.masked)throw Error(`The value of space key "${t}" is masked for this login; pass the full key value instead`);return{key:o,value:o.value}})(o.keys||[],e),n=i.key,s=i.value;if(r&&r.stop(),!(yield(0,x.n)({message:`Revoke space key "${n.name}" (${V(n)})?`,autoYes:t.yes,json:t.json})))return void console.log(E.default.yellow("Cancelled"));var p=yield a.updateWorkspace({revokeBankKey:s});if((p?.bank?.keys||[]).some(e=>e.value===n.value))throw Error(`Space key "${n.name}" was not revoked; check the key value`);(0,A.writeMutationSuccess)({action:"data.keys.revoke",target:{name:n.name,meta:n.meta},result:{revoked:!0},json:t.json,message:E.default.green(`Space key "${n.name}" revoked.`)})}catch(e){j({spinner:r,error:e,options:t,action:"data.keys.revoke"})}}),function(e,t){return f.apply(this,arguments)})),J.command("list").description("List Data Bank properties").option("-k, --keyword <keyword>","Filter by definition title / description or tags").option("-m, --meta <meta>",`Filter by meta (${N.YC.join(" | ")})`).option("-j, --json","Output as JSON").action((v=b(function*(e){var t=U(),a=t.client,r=yield T(e,"Fetching properties...");try{(0,N.jR)(e.meta);var o=yield q(a,t),i=yield o.listProperties({keyword:e.keyword,meta:e.meta});if(r&&r.stop(),e.json)return void(0,S.GF)(i||[]);if(!i||0===i.length)return void console.log(E.default.yellow("No Data Bank properties found"));console.log(E.default.bold(`
82
85
  Data Bank Properties (${i.length})`)),console.log("─".repeat(80)),i.forEach(e=>{var t=e.definition?.title;console.log(`● ${E.default.cyan(e.propertyId)} ${E.default.gray(`(${e.meta})`)}${t?` ${t}`:""}`),e.tags?.length&&console.log(` Tags: ${e.tags.join(", ")}`),console.log(` Value: ${(e=>{if(null==e)return E.default.gray("null");var t=JSON.stringify(e);return t.length>60?`${t.slice(0,60)}…`:t})(e.value)}`),console.log(` Updated: ${E.default.gray(e.updateAt)}`),console.log()}),console.log("─".repeat(80))}catch(t){j({spinner:r,error:t,options:e,action:"data.list"})}}),function(e){return v.apply(this,arguments)})),J.command("get <propertyId>").description("Get a Data Bank property").option("-j, --json","Output as JSON").action((g=b(function*(e,t){var a=U(),r=a.client,o=yield T(t,"Fetching property...");try{var i=yield q(r,a),n=yield i.getProperty(e);if(!n)throw Error(`Property not found: ${e}`);if(o&&o.stop(),t.json)return void(0,S.GF)(n);console.log(E.default.bold(`
83
86
  Data Bank Property: ${n.propertyId}`)),console.log("─".repeat(60)),console.log(`Meta: ${n.meta}`),console.log(`Title: ${n.definition?.title||E.default.gray("N/A")}`),console.log(`Tags: ${n.tags?.join(", ")||E.default.gray("None")}`),console.log(`Last Note: ${n.lastUpdateNote||E.default.gray("N/A")}`),console.log(`Updated: ${E.default.gray(n.updateAt)}`),console.log(`Created: ${E.default.gray(n.createAt)}`),console.log(`
@@ -144,10 +147,10 @@ ${v.default.bold("Exposed Properties")} (${o.expose_properties.length})`),o.expo
144
147
  Resolved ${u}`)),console.log("─".repeat(60)),console.log(`Name: ${o.default.cyan(y.name||"Unnamed")}`),console.log(`ID: ${o.default.gray(y._id)}`),console.log(`Selected By: ${g.selectedBy}`),console.log("─".repeat(60));return}if(0===g.matches.length)return void console.log(o.default.yellow(`No ${c} matched "${e}"`));console.log(o.default.bold(`
145
148
  Matching ${m} (${g.matches.length})`)),console.log("─".repeat(80)),g.matches.forEach(e=>{console.log(`${o.default.cyan(e.name||"Unnamed")} ${o.default.gray(e._id)}`)}),console.log("─".repeat(80))}catch(a){h?h.fail(`Failed to resolve ${t}: ${a.message}`):(0,s.OW)(a.message,{resource:t,query:e}),process.exit(1)}}),function(e,t){return l.apply(this,arguments)}))}},76250(e,t,a){a.d(t,{n:()=>p});var r=a(99436),o=a(73284),i=a(14636),n=a(44618),s=a(56493),p=(e,{description:t,entityName:a,fetchEntity:p})=>{var d;e.command("short-refs <id>").description(t).option("-k, --keyword <keyword>","Filter by shortId or title").option("-t, --types <types>","Comma-separated shortId prefixes to include (e.g. B,C,S)").option("-j, --json","Output as JSON").action((d=r(function*(e,t){var r=(0,s.requireAuth)(),d=(0,i.default)("Fetching short edit references...").start();try{var l=yield p(r,e);if(d.stop(),!l?.short_edit?.enabled)return void console.log(o.default.yellow(`Short Edit is not enabled for this ${a}`));var u=t.types?t.types.split(",").map(e=>e.trim()).filter(Boolean):[],c=(0,n.V)(l.short_edit.ref_map,{keyword:t.keyword,types:u});if(t.json)return void console.log(JSON.stringify(c,null,2));if(0===c.length)return void console.log(o.default.yellow("No short edit references found"));console.log(o.default.bold(`
146
149
  Short Edit References: ${l.name}`)),c.forEach(e=>{console.log(o.default.cyan(`
147
- ${e.label} (${e.prefix}_)`)),e.refs.forEach(({shortId:e,ref:t})=>{var a=t?.title?o.default.gray(`- ${t.title}`):"";console.log(` ${o.default.green(e)} ${a}`)})}),console.log()}catch(e){d.fail(`Failed to fetch short edit references: ${e.message}`),process.exit(1)}}),function(e,t){return d.apply(this,arguments)}))}},38311(e,t,a){a.d(t,{D:()=>u});var r,o,i,n=a(99436),s=a(35679),p=a(73284),d=(r=n(function*(){var e=(yield Promise.resolve().then(a.bind(a,14636))).default,t=yield a.e(6818).then(a.bind(a,53241)),r=t.detectChannel,o=t.detectInstallMethod,i=yield a.e(9405).then(a.bind(a,21068));return{ora:e,detectChannel:r,detectInstallMethod:o,fetchLatestVersionInfo:i.fetchLatestVersionInfo,runUpdateForMethod:i.runUpdateForMethod}}),function(){return r.apply(this,arguments)}),l=(o=n(function*({message:e,defaultValue:t,autoYes:r}){if(r)return!0;(0,(yield Promise.resolve().then(a.bind(a,8479))).isInteractiveTerminal)()||(console.error(p.default.red("Refusing to prompt in a non-interactive shell. Pass -y/--yes to confirm.")),process.exit(1));try{var o=(yield a.e(5658).then(a.bind(a,27521))).confirm;return yield o({message:e,default:t})}catch{return!1}}),function(e){return o.apply(this,arguments)}),u=new s.uB("update-cli").description("Update the BRICKS CLI to the latest version").option("-y, --yes","Skip confirmation prompts").option("--channel <channel>","Override channel (release|beta)").option("--check-update","Only check whether a newer version is available and exit").action((i=n(function*(e){var t,a=yield d(),r=a.ora,o=a.detectChannel,i=a.detectInstallMethod,s=a.fetchLatestVersionInfo,u=a.runUpdateForMethod,c="2.26.0-beta.40",m=i(),h=e.channel||o({version:c,execPath:m.execPath});console.log(p.default.bold(e.checkUpdate?"BRICKS CLI Update Check":"BRICKS CLI Update")),console.log("─".repeat(60)),console.log(`Current version : ${p.default.cyan(c)}`),console.log(`Channel : ${p.default.cyan(h)}`),console.log(`Detected method : ${p.default.cyan(m.method)}`),m.execPath&&"binary"===m.method&&console.log(`Binary path : ${p.default.gray(m.execPath)}`),m.installRoot&&console.log(`Install root : ${p.default.gray(m.installRoot)}`);var f="npm"===m.method||"bun"===m.method?"npm":"cdn",v=r(`Fetching latest version info (${f})...`).start(),g=null,y=null;try{g=(yield s(h,m.method)).version,v.succeed(`Latest ${h} (${f}): ${p.default.green(g)}`)}catch(e){y=e,v.warn(`Could not fetch version info: ${e.message}`)}var D=g&&g===c;if(e.checkUpdate){if(y&&process.exit(2),D)return void console.log(p.default.green("\nUp to date."));g&&(console.log(p.default.yellow(`
150
+ ${e.label} (${e.prefix}_)`)),e.refs.forEach(({shortId:e,ref:t})=>{var a=t?.title?o.default.gray(`- ${t.title}`):"";console.log(` ${o.default.green(e)} ${a}`)})}),console.log()}catch(e){d.fail(`Failed to fetch short edit references: ${e.message}`),process.exit(1)}}),function(e,t){return d.apply(this,arguments)}))}},38311(e,t,a){a.d(t,{D:()=>u});var r,o,i,n=a(99436),s=a(35679),p=a(73284),d=(r=n(function*(){var e=(yield Promise.resolve().then(a.bind(a,14636))).default,t=yield a.e(6818).then(a.bind(a,53241)),r=t.detectChannel,o=t.detectInstallMethod,i=yield a.e(9405).then(a.bind(a,21068));return{ora:e,detectChannel:r,detectInstallMethod:o,fetchLatestVersionInfo:i.fetchLatestVersionInfo,runUpdateForMethod:i.runUpdateForMethod}}),function(){return r.apply(this,arguments)}),l=(o=n(function*({message:e,defaultValue:t,autoYes:r}){if(r)return!0;(0,(yield Promise.resolve().then(a.bind(a,8479))).isInteractiveTerminal)()||(console.error(p.default.red("Refusing to prompt in a non-interactive shell. Pass -y/--yes to confirm.")),process.exit(1));try{var o=(yield a.e(5658).then(a.bind(a,27521))).confirm;return yield o({message:e,default:t})}catch{return!1}}),function(e){return o.apply(this,arguments)}),u=new s.uB("update-cli").description("Update the BRICKS CLI to the latest version").option("-y, --yes","Skip confirmation prompts").option("--channel <channel>","Override channel (release|beta)").option("--check-update","Only check whether a newer version is available and exit").action((i=n(function*(e){var t,a=yield d(),r=a.ora,o=a.detectChannel,i=a.detectInstallMethod,s=a.fetchLatestVersionInfo,u=a.runUpdateForMethod,c="2.26.0-beta.41",m=i(),h=e.channel||o({version:c,execPath:m.execPath});console.log(p.default.bold(e.checkUpdate?"BRICKS CLI Update Check":"BRICKS CLI Update")),console.log("─".repeat(60)),console.log(`Current version : ${p.default.cyan(c)}`),console.log(`Channel : ${p.default.cyan(h)}`),console.log(`Detected method : ${p.default.cyan(m.method)}`),m.execPath&&"binary"===m.method&&console.log(`Binary path : ${p.default.gray(m.execPath)}`),m.installRoot&&console.log(`Install root : ${p.default.gray(m.installRoot)}`);var f="npm"===m.method||"bun"===m.method?"npm":"cdn",v=r(`Fetching latest version info (${f})...`).start(),g=null,y=null;try{g=(yield s(h,m.method)).version,v.succeed(`Latest ${h} (${f}): ${p.default.green(g)}`)}catch(e){y=e,v.warn(`Could not fetch version info: ${e.message}`)}var D=g&&g===c;if(e.checkUpdate){if(y&&process.exit(2),D)return void console.log(p.default.green("\nUp to date."));g&&(console.log(p.default.yellow(`
148
151
  Update available: ${c} → ${g}. Run 'bricks update-cli' to install.`)),process.exit(1)),console.log(p.default.yellow("\nCould not determine current version.")),process.exit(2)}if(D&&(console.log(p.default.green("\nAlready running the latest version.")),!(yield l({message:"Reinstall anyway?",defaultValue:!1,autoYes:e.yes}))))return void console.log(p.default.gray("Skipped."));var w=["npm","bun","binary"].includes(m.method);w||console.log(p.default.yellow(`Cannot auto-detect installer (method: ${m.method}); falling back to binary install.`));var b=w?m.method:"binary";if(!(yield l({message:`Update CLI using "${b}" method?`,defaultValue:!0,autoYes:e.yes})))return void console.log(p.default.yellow("Cancelled."));var _=(t=n(function*(e){console.log(p.default.cyan(`
149
152
  → Running ${e} update...`));try{return yield u(e,h,m),!0}catch(t){return console.error(p.default.yellow(`
150
- ${e} update failed: ${t.message}`)),!1}}),function(e){return t.apply(this,arguments)}),k=yield _(b);!k&&"binary"!==b&&(console.log(p.default.cyan("\nFalling back to binary install (same method used by the desktop app).")),(yield l({message:"Try the binary installer as a fallback?",defaultValue:!0,autoYes:e.yes}))&&(k=yield _("binary"))),k||(console.error(p.default.red("\nUpdate failed. See messages above.")),process.exit(1)),console.log(p.default.green("\nUpdate complete."))}),function(e){return i.apply(this,arguments)}))},1878(e,t,a){a.a(e,async function(e,r){try{a.d(t,{A:()=>N,e:()=>$});var o,i=a(99436),n=a(35679),s=a(73284),p=a(47988),d=a(8479),l=a(85654),u=a(43738),c=a(72381),m=a(32541),h=a(28634),f=a(27594),v=a(12569),g=a(55609),y=a(71335),D=a(68473),w=a(27759),b=a(42400),_=a(98247),k=a(70970),E=a(38311),S=a(50427),C=a(22175),x=e([b]);b=(x.then?(await x)():x)[0];var $=(o=i(function*(){var e,t=(0,d.getUnsupportedBunRuntimeError)();if(t){var r=process.argv.includes("--json")||process.argv.includes("-j");console.error(r?JSON.stringify({error:t}):s.default.red(t)),process.exit(1)}var o=process.argv.findIndex(e=>"--auth-profile"===e||"-ap"===e);if(-1!==o&&process.argv[o+1]){var x=process.argv[o+1];(0,p.setProfileOverride)(x),process.env.BRICKS_PROFILE=x,process.argv.splice(o,2)}n.DM.name("bricks").description("BRICKS CLI - Command-line interface for BRICKS Workspace API").version("2.26.0-beta.40","-v, --version","output the version number").enablePositionalOptions(),n.DM.addCommand(l.s),n.DM.addCommand(u._),n.DM.addCommand(c.B),n.DM.addCommand(m.A),n.DM.addCommand(h.p),n.DM.addCommand(f.n),n.DM.addCommand(v.u),n.DM.addCommand(g.E),n.DM.addCommand(y.oT),n.DM.addCommand(D.K),n.DM.addCommand(w.gf),n.DM.addCommand(b.D),n.DM.addCommand(_.v),n.DM.addCommand(k.l),n.DM.addCommand(E.D),n.DM.addCommand(S.Q),n.DM.addCommand(C.g),n.DM.command("interactive").alias("i").description("Start interactive mode with Ink UI").action(i(function*(){try{var e=(yield Promise.all([a.e(2499),a.e(8295),a.e(4994),a.e(907),a.e(7294)]).then(a.bind(a,94685))).runInteractiveMode;yield e()}catch(e){console.error(s.default.red(`Failed to start interactive mode: ${e.message}`)),process.exit(1)}})),n.DM.command("workspace").alias("ws").description("Show current workspace information").option("-j, --json","Output as JSON").action((e=i(function*(e){var t=(yield Promise.resolve().then(a.bind(a,47988))).getCurrentProfile,r=(yield Promise.resolve().then(a.bind(a,31802))).getConnectionContext,o=(yield Promise.all([a.e(2499),a.e(8295),a.e(907)]).then(a.bind(a,85382))).createClient,i=(yield Promise.resolve().then(a.bind(a,14636))).default,n=t(),p=r(n),d=p.auth,l=p.baseUrl;d||(console.error(s.default.red("Not logged in. Use `bricks auth login` first.")),process.exit(1));var u=i("Fetching workspace info...").start();try{var c=o(l,d),m=yield c.workspace();if(u.stop(),e.json)return void console.log(JSON.stringify(m,null,2));console.log(s.default.bold("\nWorkspace Information")),console.log("─".repeat(60)),console.log(`Name: ${s.default.green(m.name)}`),console.log(`ID: ${s.default.gray(m._id)}`),console.log(`Description: ${m.description||s.default.gray("N/A")}`),console.log(`
153
+ ${e} update failed: ${t.message}`)),!1}}),function(e){return t.apply(this,arguments)}),k=yield _(b);!k&&"binary"!==b&&(console.log(p.default.cyan("\nFalling back to binary install (same method used by the desktop app).")),(yield l({message:"Try the binary installer as a fallback?",defaultValue:!0,autoYes:e.yes}))&&(k=yield _("binary"))),k||(console.error(p.default.red("\nUpdate failed. See messages above.")),process.exit(1)),console.log(p.default.green("\nUpdate complete."))}),function(e){return i.apply(this,arguments)}))},1878(e,t,a){a.a(e,async function(e,r){try{a.d(t,{A:()=>N,e:()=>$});var o,i=a(99436),n=a(35679),s=a(73284),p=a(47988),d=a(8479),l=a(85654),u=a(43738),c=a(72381),m=a(32541),h=a(28634),f=a(27594),v=a(12569),g=a(55609),y=a(71335),D=a(68473),w=a(27759),b=a(42400),_=a(98247),k=a(70970),E=a(38311),S=a(50427),C=a(22175),x=e([b]);b=(x.then?(await x)():x)[0];var $=(o=i(function*(){var e,t=(0,d.getUnsupportedBunRuntimeError)();if(t){var r=process.argv.includes("--json")||process.argv.includes("-j");console.error(r?JSON.stringify({error:t}):s.default.red(t)),process.exit(1)}var o=process.argv.findIndex(e=>"--auth-profile"===e||"-ap"===e);if(-1!==o&&process.argv[o+1]){var x=process.argv[o+1];(0,p.setProfileOverride)(x),process.env.BRICKS_PROFILE=x,process.argv.splice(o,2)}n.DM.name("bricks").description("BRICKS CLI - Command-line interface for BRICKS Workspace API").version("2.26.0-beta.41","-v, --version","output the version number").enablePositionalOptions(),n.DM.addCommand(l.s),n.DM.addCommand(u._),n.DM.addCommand(c.B),n.DM.addCommand(m.A),n.DM.addCommand(h.p),n.DM.addCommand(f.n),n.DM.addCommand(v.u),n.DM.addCommand(g.E),n.DM.addCommand(y.oT),n.DM.addCommand(D.K),n.DM.addCommand(w.gf),n.DM.addCommand(b.D),n.DM.addCommand(_.v),n.DM.addCommand(k.l),n.DM.addCommand(E.D),n.DM.addCommand(S.Q),n.DM.addCommand(C.g),n.DM.command("interactive").alias("i").description("Start interactive mode with Ink UI").action(i(function*(){try{var e=(yield Promise.all([a.e(2499),a.e(8295),a.e(4994),a.e(907),a.e(7294)]).then(a.bind(a,94685))).runInteractiveMode;yield e()}catch(e){console.error(s.default.red(`Failed to start interactive mode: ${e.message}`)),process.exit(1)}})),n.DM.command("workspace").alias("ws").description("Show current workspace information").option("-j, --json","Output as JSON").action((e=i(function*(e){var t=(yield Promise.resolve().then(a.bind(a,47988))).getCurrentProfile,r=(yield Promise.resolve().then(a.bind(a,31802))).getConnectionContext,o=(yield Promise.all([a.e(2499),a.e(8295),a.e(907)]).then(a.bind(a,85382))).createClient,i=(yield Promise.resolve().then(a.bind(a,14636))).default,n=t(),p=r(n),d=p.auth,l=p.baseUrl;d||(console.error(s.default.red("Not logged in. Use `bricks auth login` first.")),process.exit(1));var u=i("Fetching workspace info...").start();try{var c=o(l,d),m=yield c.workspace();if(u.stop(),e.json)return void console.log(JSON.stringify(m,null,2));console.log(s.default.bold("\nWorkspace Information")),console.log("─".repeat(60)),console.log(`Name: ${s.default.green(m.name)}`),console.log(`ID: ${s.default.gray(m._id)}`),console.log(`Description: ${m.description||s.default.gray("N/A")}`),console.log(`
151
154
  ${s.default.bold("Data")}`),console.log(`Remote Update: ${m.bank?.enable_remote_update?s.default.green("Enabled"):s.default.gray("Disabled")}`),console.log(`Spacename: ${m.bank?.spacename||s.default.gray("N/A")}`),console.log("─".repeat(60))}catch(e){u.fail(`Failed to get workspace: ${e.message}`),process.exit(1)}}),function(t){return e.apply(this,arguments)})),n.DM.on("--help",()=>{console.log(""),console.log(s.default.bold("Examples:")),console.log(""),console.log(s.default.gray(" # Sign in with your BRICKS account (opens the browser)")),console.log(" $ bricks auth login"),console.log(""),console.log(s.default.gray(" # Select a workspace as the active profile")),console.log(" $ bricks auth use-workspace"),console.log(""),console.log(s.default.gray(" # Workspace auth (CI/automation): one-time passcode or token")),console.log(" $ bricks auth login-workspace <passcode>"),console.log(""),console.log(s.default.gray(" # List all devices")),console.log(" $ bricks device list"),console.log(""),console.log(s.default.gray(" # Monitor devices in real-time")),console.log(" $ bricks device monitor"),console.log(""),console.log(s.default.gray(" # Control a device")),console.log(" $ bricks device refresh <device-id>"),console.log(" $ bricks device control <device-id> clear-cache"),console.log(""),console.log(s.default.gray(" # Bind a new device")),console.log(' $ bricks device bind <passcode> -n "My Device"'),console.log(""),console.log(s.default.gray(" # List applications")),console.log(" $ bricks app list"),console.log(""),console.log(s.default.gray(" # Start interactive mode")),console.log(" $ bricks interactive"),console.log(""),console.log(s.default.gray(" # Change API endpoint")),console.log(" $ bricks config endpoint beta"),console.log(""),console.log(s.default.gray("Get workspace token from BRICKS Controller:")),console.log(s.default.cyan(" https://control.bricks.tools")),console.log(s.default.gray(" Go to Workspace Settings > API Token"))});var $=process.argv.slice(2);if(0===$.length){if((0,d.shouldStartInteractiveMode)($))try{var N=(yield Promise.all([a.e(2499),a.e(8295),a.e(4994),a.e(907),a.e(7294)]).then(a.bind(a,94685))).runInteractiveMode;yield N();return}catch(e){console.error(s.default.red(`Failed to start interactive mode: ${e.message}`)),process.exit(1)}console.error(s.default.gray("No command provided. Interactive mode requires a TTY, so showing help instead.\n")),n.DM.outputHelp();return}yield n.DM.parseAsync(process.argv)}),function(){return o.apply(this,arguments)});let N=$;r()}catch(e){r(e)}})},31802(e,t,a){a.r(t),a.d(t,{getAuthContext:()=>p,getConnectionContext:()=>s});var r=a(99436),o=a(47988),i=a(63755),n=(e,t)=>{if(!e)throw Error("Not logged in. Run `bricks auth login` first.");if(e.user?.sub!==t)throw Error("OAuth account changed. Re-select the workspace for the current account.");return e},s=e=>{var t=(0,o.getProfileCredentialSnapshot)(e);return{...t,auth:(({tokenInfo:e,oauth:t})=>{if(!e)return null;if("oauth"===e.type){if(!t?.accessToken||!e.oauthSubject||e.oauthSubject!==t.user?.sub||!e.workspaceId)return null;var a,o,s,p,d=e.oauthSubject,l=(o=r(function*(){return n((yield(0,i.EC)()),d).accessToken}),function(){return o.apply(this,arguments)});return{kind:"oauth",workspaceId:e.workspaceId,workspaceName:e.workspaceName,getAccessToken:l,getHeaders:(s=r(function*(){return{authorization:`Bearer ${yield l()}`,"x-bricks-workspace-id":String(e.workspaceId)}}),function(){return s.apply(this,arguments)}),refresh:(p=r(function*(){n((yield(0,i.EC)({forceRefresh:!0})),d)}),function(){return p.apply(this,arguments)})}}return e.token?{kind:"token",token:e.token,workspaceId:e.workspaceId,workspaceName:e.workspaceName,getHeaders:(a=r(function*(){return{authorization:`Bearer ${e.token}`}}),function(){return a.apply(this,arguments)})}:null})(t)}},p=e=>s(e).auth},31596(e,t,a){a.d(t,{GE:()=>o,YC:()=>r,jR:()=>i});var r=["InSubspace","Global"],o="Data Bank is not enabled for this workspace.",i=e=>{if(e&&!r.includes(e))throw Error(`Invalid meta "${e}" (expected ${r.join(" | ")})`)}},56493(e,t,a){a.r(t),a.d(t,{requireAuth:()=>l,requireAuthConnection:()=>d});var r=a(99436),o=a(73284),i=a(47988),n=a(31802),s=a(29988),p=new Set(["$$typeof","asymmetricMatch","catch","constructor","finally","hasOwnProperty","inspect","nodeType","toJSON","toString","valueOf"]),d=(e=(0,i.getCurrentProfile)())=>{var t,a,d,l=(0,n.getConnectionContext)(e),u=l.auth,c=l.baseUrl;return u||(console.error(o.default.red("Not logged in.")),console.error(o.default.gray("Use `bricks auth login` (OAuth) or `bricks auth login-workspace` (workspace token) first.")),process.exit(1)),{...l,client:(t=null,a=r(function*(){return t||=Promise.resolve((0,s.i)()).then(({createClient:e})=>e(c,u))}),d=function(){return a.apply(this,arguments)},new Proxy({},{get:(e,t)=>t===Symbol.toStringTag?"BricksLazyClient":"string"!=typeof t||"then"===t||p.has(t)?void 0:r(function*(...e){var a=yield d(),r=a[t];return"function"==typeof r?r.apply(a,e):r})}))}},l=(e=(0,i.getCurrentProfile)())=>d(e).client},7586(e,t,a){a.d(t,{$l:()=>i,GF:()=>r,OW:()=>o});var r=e=>{console.log(JSON.stringify(e,null,2))},o=(e,t={})=>{console.error(JSON.stringify({ok:!1,error:{message:e,...t}},null,2))},i=(e,t=4)=>e?e.length<=2*t?"*".repeat(e.length):`${e.slice(0,t)}…${e.slice(-t)}`:null},58021(e,t,a){a.d(t,{n:()=>p});var r,o,i=a(99436),n=a(8479),s=(r=i(function*(){return a.e(5658).then(a.bind(a,27521))}),function(){return r.apply(this,arguments)}),p=(o=i(function*({message:e,autoYes:t,json:a}){if(t)return!0;if(a)throw Error("Confirmation required: pass -y/--yes together with --json");if(!(0,n.isInteractiveTerminal)())throw Error("Refusing to prompt in a non-interactive shell. Pass -y/--yes to confirm.");try{var r=(yield s()).confirm;return yield r({message:e,default:!1})}catch{return!1}}),function(e){return o.apply(this,arguments)})},8479(e,t,a){a.r(t),a.d(t,{MINIMUM_BUN_VERSION:()=>r,getUnsupportedBunRuntimeError:()=>i,isInteractiveTerminal:()=>n,shouldStartInteractiveMode:()=>s});var r="1.3.0",o=e=>{var t=String(e).match(/^(\d+)\.(\d+)\.(\d+)/);return t?t.slice(1).map(Number):null},i=(e=process.versions.bun)=>!e||((e,t)=>{var a=o(e),r=o(t);if(!a||!r)return!1;for(var i=0;i<r.length&&!(a[i]>r[i]);i+=1)if(a[i]<r[i])return!1;return!0})(e,r)?null:`Bun ${e} is not supported by BRICKS CLI. Bun ${r} or later is required. Run \`bun upgrade\` and retry.`,n=()=>!!(process.stdin.isTTY&&process.stdout.isTTY&&"function"==typeof process.stdin.setRawMode),s=(e=[])=>0===e.length&&n()},47988(e,t,a){a.r(t),a.d(t,{CONFIG_DIR:()=>x,CONFIG_LOCK_PATH:()=>N,CONFIG_PATH:()=>$,OAUTH_REFRESH_LOCK_PATH:()=>A,clearBankCredentials:()=>eJ,clearConfig:()=>eK,clearOAuth:()=>e$,clearOAuthIfCurrent:()=>eI,clearOAuthIfCurrentAsync:()=>ej,default:()=>eW,getActivityLogBaseUrl:()=>eY,getBankCredentials:()=>eU,getBaseUrl:()=>W,getCurrentProfile:()=>eR,getCurrentProfileSource:()=>eV,getOAuth:()=>eS,getProfileAuthKind:()=>eE,getProfileCredentialSnapshot:()=>er,getProfileCredentialSnapshotAsync:()=>eo,getProfileFingerprint:()=>ei,getToken:()=>Q,getTokenInfo:()=>X,getTokens:()=>z,initializeConfigAsync:()=>G,installOAuthSessionIfCurrent:()=>e_,installOAuthSessionIfCurrentAsync:()=>ek,invalidateOAuthProfileCredentials:()=>eD,invalidateOAuthProfileCredentialsAsync:()=>ew,listProfiles:()=>eL,removeDevtoolsTokenAsync:()=>eg,removeToken:()=>em,removeTokenIfCurrent:()=>eh,replaceOAuthIfCurrent:()=>eT,replaceOAuthIfCurrentAsync:()=>eO,resolveOAuthProfileTarget:()=>en,setActivityLogBaseUrl:()=>eG,setBankCredentials:()=>eq,setBaseUrl:()=>H,setCurrentProfile:()=>eM,setDevtoolsTokenIfProfileCurrent:()=>ef,setDevtoolsTokenIfProfileCurrentAsync:()=>ev,setOAuth:()=>eC,setOAuthAsync:()=>ex,setProfileOverride:()=>eP,setToken:()=>ed,setTokenIfProfileCurrent:()=>eu,setTokenIfProfileCurrentAsync:()=>ec,takeOAuthSession:()=>eN,takeOAuthSessionAsync:()=>eA,withOAuthRefreshLock:()=>M});var r,o,i,n,s,p,d,l,u,c,m,h,f,v,g,y=a(68832),D=a(67996),w=a(99436),b=a(83440),_=a(76982),k=a(79896),E=a(16928),S=a(70857);function C(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var a=e[Symbol.toPrimitive];if(void 0!==a){var r=a.call(e,t||"default");if("object"!=typeof r)return r;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}var x=E.join(S.homedir(),".bricks-cli"),$=E.join(x,"config.json"),N=`${$}.lock`,A=`${$}.oauth-refresh.lock`,F=new Int32Array(new SharedArrayBuffer(4)),T=e=>new Promise(t=>setTimeout(t,e)),O=e=>{if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"ESRCH"!==e.code}},I=e=>{try{var t=k.readFileSync(e,"utf8"),a=k.statSync(e),r=null;try{var o=JSON.parse(t);Number.isInteger(o?.pid)&&"string"==typeof o?.nonce&&(r=o)}catch{}return{raw:t,stat:a,owner:r}}catch(e){if("ENOENT"===e.code)return null;throw e}},j=e=>{var t,a=I(e);if(!a)return!0;var r=a.owner?!O(a.owner.pid):Date.now()-a.stat.mtimeMs>1e3;if(!r)return!1;var o=`${e}.recovery`;try{t=B(o)}catch(e){if("EEXIST"===e.code)return!1;throw e}try{if(!(a=I(e)))return!0;if(!(r=a.owner?!O(a.owner.pid):Date.now()-a.stat.mtimeMs>1e3))return!1;return k.unlinkSync(e),!0}catch(e){if("ENOENT"===e.code)return!0;throw e}finally{P(o,t)}},B=e=>{var t,a={pid:process.pid,nonce:_.randomUUID()},r=`${e}.${a.pid}.${a.nonce}.candidate`;try{t=k.openSync(r,"wx",384),k.writeFileSync(t,JSON.stringify(a)),k.fsyncSync(t),k.closeSync(t),t=void 0}catch(e){if(void 0!==t)try{k.closeSync(t)}catch{}try{k.unlinkSync(r)}catch{}throw e}try{k.linkSync(r,e)}catch(e){try{k.unlinkSync(r)}catch{}throw e}try{k.unlinkSync(r)}catch(e){"ENOENT"!==e.code&&console.error(`Failed to clean up shared BRICKS lock candidate: ${e.message}`)}return{owner:a}},P=(e,{owner:t})=>{try{var a;(a=I(e))&&a.owner?.nonce===t.nonce&&k.unlinkSync(e)}catch(e){"ENOENT"!==e.code&&console.error(`Failed to release shared BRICKS lock: ${e.message}`)}},R=e=>{k.mkdirSync(x,{recursive:!0});for(var t,a=Date.now()+5e3;!t;)try{t=B(N)}catch(e){if("EEXIST"!==e.code)throw e;if(j(N))continue;if(Date.now()>=a)throw Error(`Timed out waiting for shared BRICKS config lock: ${N}`);Atomics.wait(F,0,0,20)}try{return e()}finally{P(N,t)}},V=(r=w(function*(e){k.mkdirSync(x,{recursive:!0});for(var t,a=Date.now()+5e3;!t;)try{t=B(N)}catch(e){if("EEXIST"!==e.code)throw e;if(j(N))continue;if(Date.now()>=a)throw Error(`Timed out waiting for shared BRICKS config lock: ${N}`);yield T(20)}try{var r=e();if(r&&"function"==typeof r.then)throw Error("Shared BRICKS config lock callbacks must be synchronous");return r}finally{P(N,t)}}),function(e){return r.apply(this,arguments)}),M=(o=w(function*(e,{timeoutMs:t=3e4}={}){k.mkdirSync(x,{recursive:!0});for(var a,r=Date.now()+t;!a;)try{a=B(A)}catch(e){if("EEXIST"!==e.code)throw e;if(j(A))continue;if(Date.now()>=r)throw Error(`Timed out waiting for OAuth refresh lock: ${A}`);yield T(20)}try{return yield e()}finally{P(A,a)}}),function(e){return o.apply(this,arguments)}),L=()=>new b.default({projectName:"bricks-cli",cwd:x,configFileMode:384,schema:{oauth:{type:"object",default:{},properties:{accessToken:{type:"string"},refreshToken:{type:["string","null"]},expiresAt:{type:"string"},user:{type:"object"},audience:{type:"string"}}},tokens:{type:"object",default:{},additionalProperties:{type:"object",properties:{type:{type:"string",enum:["oauth"]},oauthSubject:{type:"string"},token:{type:"string"},name:{type:"string"},workspaceId:{type:"string"},workspaceName:{type:"string"},workspaceBilling:{type:"object"},createdAt:{type:"string"},baseUrl:{type:"string"},activityLogBaseUrl:{type:"string"},bank:{type:"object"}}}},currentProfile:{type:"string",default:"default"},baseUrl:{type:"string",default:"https://display.bricks.tools"},activityLogBaseUrl:{type:"string",default:"https://activity-log.bricks.tools"},devtoolsTokens:{type:"object",default:{},additionalProperties:{type:"object",additionalProperties:{type:"object",properties:{token:{type:"string"},expiresAt:{type:"string"},jti:{type:"string"},workspaceId:{type:"string"}}}}}}}),U=null,q=null,J=()=>U||=L(),Y=(i=w(function*(){if(U)return U;q||=V(()=>U||=L());try{return yield q}finally{q=null}}),function(){return i.apply(this,arguments)}),G=(n=w(function*(){yield Y()}),function(){return n.apply(this,arguments)}),K={get:e=>J().get(e),set:(e,t)=>{var a=J();return R(()=>a.set(e,t))},clear:()=>{var e=J();return R(()=>e.clear())},setAsync:(s=w(function*(e,t){var a=yield Y();return V(()=>a.set(e,t))}),function(e,t){return s.apply(this,arguments)}),update:(e,t)=>{var a=J();return R(()=>{var r=t(a.get(e));return a.set(e,r),r})},updateAsync:(p=w(function*(e,t){var a=yield Y();return V(()=>{var r=t(a.get(e));return a.set(e,r),r})}),function(e,t){return p.apply(this,arguments)}),snapshot:e=>{var t=J().store;return Object.fromEntries(e.map(e=>[e,t[e]]))},snapshotAsync:(d=w(function*(e){var t=(yield Y()).store;return Object.fromEntries(e.map(e=>[e,t[e]]))}),function(e){return d.apply(this,arguments)}),transaction:(e,t)=>{var a=J();return R(()=>{var r=t(Object.fromEntries(e.map(e=>[e,a.get(e)])))||{};return Object.keys(r).length>0&&a.set(r),r})},transactionAsync:(l=w(function*(e,t){var a=yield Y();return V(()=>{var r=t(Object.fromEntries(e.map(e=>[e,a.get(e)])))||{};return Object.keys(r).length>0&&a.set(r),r})}),function(e,t){return l.apply(this,arguments)})},W=(e=eR())=>{var t=K.get("tokens");return t[e]?.baseUrl||K.get("baseUrl")},H=(e,t)=>{t?K.update("tokens",(a={})=>({...a,[t]:{...a[t],baseUrl:e}})):K.set("baseUrl",e)},z=()=>K.get("tokens"),Q=(e="default")=>{var t=K.get("tokens");return t[e]?.token},X=(e="default")=>K.get("tokens")[e],Z=(e,t,a,r)=>{if(!e)return null;var o=null==e.workspaceId?null:String(e.workspaceId);return"oauth"===e.type?e.oauthSubject&&e.oauthSubject===t?.user?.sub?{kind:"oauth",workspaceId:o,oauthSubject:e.oauthSubject,baseUrl:a,activityLogBaseUrl:r}:null:e.token?{kind:"token",workspaceId:o,token:e.token,baseUrl:a,activityLogBaseUrl:r}:null},ee=(e,t,a,r,o)=>{if(!e)return!1;var i=Z(t,a,t?.baseUrl||r,t?.activityLogBaseUrl||o);return!!i&&i.kind===e.kind&&i.workspaceId===e.workspaceId&&i.baseUrl===e.baseUrl&&i.activityLogBaseUrl===e.activityLogBaseUrl&&("oauth"===i.kind?i.oauthSubject===e.oauthSubject:i.token===e.token)},et=(e,t,a)=>({exists:void 0!==e,kind:e?.type==="oauth"?"oauth":e?.token?"token":"incomplete",workspaceId:e?.workspaceId==null?null:String(e.workspaceId),credential:e?.type==="oauth"?e.oauthSubject||null:e?.token||null,baseUrl:t,activityLogBaseUrl:a}),ea=(e,{tokens:t={},oauth:a,devtoolsTokens:r={},baseUrl:o,activityLogBaseUrl:i})=>{var n=t[e],s=n?.baseUrl||o,p=n?.activityLogBaseUrl||i,d=Z(n,a,s,p);return{profile:e,tokenInfo:n,oauth:a,fingerprint:d,baseline:et(n,s,p),bank:d&&n?.bank||null,devtoolsTokens:r[e]||{},baseUrl:s,activityLogBaseUrl:p}},er=(e="default")=>ea(e,K.snapshot(["tokens","oauth","devtoolsTokens","baseUrl","activityLogBaseUrl"])),eo=(u=w(function*(e="default"){return ea(e,(yield K.snapshotAsync(["tokens","oauth","devtoolsTokens","baseUrl","activityLogBaseUrl"])))}),function(){return u.apply(this,arguments)}),ei=(e="default")=>er(e).fingerprint,en=(e,t,a)=>{for(var r=K.snapshot(["tokens","baseUrl","activityLogBaseUrl"]),o=r.tokens||{},i=e,n=2;;){var s=o[i];if(!s||"oauth"===s.type&&s.oauthSubject===a&&String(s.workspaceId)===String(t))break;i=`${e}-${n}`,n+=1}var p=o[i];return{profile:i,baseline:et(p,p?.baseUrl||r.baseUrl,p?.activityLogBaseUrl||r.activityLogBaseUrl)}},es=(e,t,a,r)=>{var o=a[e],i=o?.workspaceId&&t?.workspaceId&&String(o.workspaceId)===String(t.workspaceId),n=o?.type==="oauth"&&t?.type==="oauth"&&!!o.oauthSubject&&o.oauthSubject===t.oauthSubject||o?.type!=="oauth"&&t?.type!=="oauth"&&!!o?.token&&o.token===t?.token,s=i&&n,p={tokens:{...a,[e]:{...o?.baseUrl?{baseUrl:o.baseUrl}:{},...o?.activityLogBaseUrl?{activityLogBaseUrl:o.activityLogBaseUrl}:{},...s&&o?.bank?{bank:o.bank}:{},...t,createdAt:new Date().toISOString()}}};if(!s&&r[e]){var d={...r};delete d[e],p.devtoolsTokens=d}return p},ep=(e,t)=>{if(e&&t?.user?.sub!==e)throw Error("OAuth account changed. Re-select the workspace for the current account.")},ed=(e,t,{expectedOAuthSubject:a}={})=>{K.transaction(a?["tokens","devtoolsTokens","oauth"]:["tokens","devtoolsTokens"],({tokens:r={},devtoolsTokens:o={},oauth:i})=>(ep(a,i),es(e,t,r,o)))},el=(e,t,a,r)=>!!e&&JSON.stringify(e)===JSON.stringify(et(t,t?.baseUrl||a,t?.activityLogBaseUrl||r)),eu=(e,t,a,{expectedOAuthSubject:r,makeCurrent:o=!1}={})=>{var i=!1;return K.transaction(["tokens","devtoolsTokens","oauth","currentProfile","baseUrl","activityLogBaseUrl"],({tokens:n={},devtoolsTokens:s={},oauth:p,baseUrl:d,activityLogBaseUrl:l})=>{if(!el(a,n[e],d,l))return{};ep(r,p),i=!0;var u=es(e,t,n,s);return o?{...u,currentProfile:e}:u}),i},ec=(c=w(function*(e,t,a,{expectedOAuthSubject:r,makeCurrent:o=!1}={}){var i=!1;return yield K.transactionAsync(["tokens","devtoolsTokens","oauth","currentProfile","baseUrl","activityLogBaseUrl"],({tokens:n={},devtoolsTokens:s={},oauth:p,baseUrl:d,activityLogBaseUrl:l})=>{if(!el(a,n[e],d,l))return{};ep(r,p),i=!0;var u=es(e,t,n,s);return o?{...u,currentProfile:e}:u}),i}),function(e,t,a){return c.apply(this,arguments)}),em=e=>{K.transaction(["tokens","devtoolsTokens"],({tokens:t={},devtoolsTokens:a={}})=>{var r={...t};delete r[e];var o={tokens:r};if(a[e]){var i={...a};delete i[e],o.devtoolsTokens=i}return o})},eh=(e,t)=>{var a=!1;return K.transaction(["tokens","devtoolsTokens"],({tokens:r={},devtoolsTokens:o={}})=>{if(i=r[e],!i||!t||String(i.workspaceId??"")!==String(t.workspaceId??"")||("oauth"===t.type?"oauth"!==i.type||i.oauthSubject!==t.oauthSubject:t.token?"oauth"===i.type||i.token!==t.token:JSON.stringify(i)!==JSON.stringify(t)))return{};a=!0;var i,n={...r};delete n[e];var s={...o};return delete s[e],{tokens:n,devtoolsTokens:s}}),a},ef=(e,t,a,r)=>{var o=!1;return K.transaction(["tokens","oauth","devtoolsTokens","baseUrl","activityLogBaseUrl"],({tokens:i={},oauth:n,devtoolsTokens:s={},baseUrl:p,activityLogBaseUrl:d})=>ee(t,i[e],n,p,d)?(o=!0,{devtoolsTokens:{...s,[e]:{...s[e],[a]:r}}}):{}),o},ev=(m=w(function*(e,t,a,r){var o=!1;return yield K.transactionAsync(["tokens","oauth","devtoolsTokens","baseUrl","activityLogBaseUrl"],({tokens:i={},oauth:n,devtoolsTokens:s={},baseUrl:p,activityLogBaseUrl:d})=>ee(t,i[e],n,p,d)?(o=!0,{devtoolsTokens:{...s,[e]:{...s[e],[a]:r}}}):{}),o}),function(e,t,a,r){return m.apply(this,arguments)}),eg=(h=w(function*(e,t){var a=!1;return yield K.transactionAsync(["devtoolsTokens"],({devtoolsTokens:r={}})=>{var o=r[e];if(!o?.[t])return{};a=!0,o[t];var i=D(o,[t].map(C));return{devtoolsTokens:{...r,[e]:i}}}),a}),function(e,t){return h.apply(this,arguments)}),ey=(e,t)=>{if(e)return t(["tokens","devtoolsTokens"],({tokens:t={},devtoolsTokens:a={}})=>{var r={...t},o=[];for(var i of Object.entries(t)){var n=y(i,2),s=n[0],p=n[1];if(p?.type==="oauth"&&(!p.oauthSubject||p.oauthSubject===e)){o.push(s);var d={...p,oauthSubject:p.oauthSubject||e};delete d.bank,r[s]=d}}var l={...a},u=!1;return o.forEach(e=>{l[e]&&(delete l[e],u=!0)}),{tokens:r,...u?{devtoolsTokens:l}:{}}})},eD=e=>ey(e,K.transaction),ew=e=>ey(e,K.transactionAsync),eb=(e,t,a)=>{if(r=a.oauth,e?.accessToken?!eF(e,r):!!r?.accessToken)return{result:{installed:!1,identityChanged:!1,previous:null},updates:{}};var r,o=a.oauth?.accessToken?a.oauth:null,i=o?.user?.sub,n=!!(i&&t?.user?.sub&&i!==t.user.sub),s={installed:!0,identityChanged:n,previous:o};if(!n)return{result:s,updates:{oauth:t}};var p={...a.tokens||{}},d={...a.devtoolsTokens||{}},l=!1;for(var u of Object.entries(a.tokens||{})){var c=y(u,2),m=c[0],h=c[1];if(h?.type==="oauth"&&(!h.oauthSubject||h.oauthSubject===i)){var f={...h,oauthSubject:h.oauthSubject||i};delete f.bank,p[m]=f,d[m]&&(delete d[m],l=!0)}}return{result:s,updates:{oauth:t,tokens:p,...l?{devtoolsTokens:d}:{}}}},e_=(e,t)=>{var a;return K.transaction(["oauth","tokens","devtoolsTokens"],r=>{var o=eb(e,t,r);return a=o.result,o.updates}),a},ek=(f=w(function*(e,t){var a;return yield K.transactionAsync(["oauth","tokens","devtoolsTokens"],r=>{var o=eb(e,t,r);return a=o.result,o.updates}),a}),function(e,t){return f.apply(this,arguments)}),eE=(e="default")=>{var t=X(e);return t?"oauth"===t.type?"oauth":t.token?"token":null:null},eS=()=>{var e=K.get("oauth");return e&&Object.keys(e).length>0?e:null},eC=e=>K.set("oauth",e),ex=e=>K.setAsync("oauth",e),e$=()=>K.set("oauth",{}),eN=()=>{var e=null;return K.update("oauth",t=>(t?.accessToken&&(e=t),{})),e},eA=(v=w(function*(){var e=null;return yield K.updateAsync("oauth",t=>(t?.accessToken&&(e=t),{})),e}),function(){return v.apply(this,arguments)}),eF=(e,t)=>!!e&&!!t&&e.accessToken===t.accessToken&&e.refreshToken===t.refreshToken,eT=(e,t)=>{var a=!1;return K.update("oauth",r=>eF(e,r)?(a=!0,t||{}):r||{}),a},eO=(g=w(function*(e,t){var a=!1;return yield K.updateAsync("oauth",r=>eF(e,r)?(a=!0,t||{}):r||{}),a}),function(e,t){return g.apply(this,arguments)}),eI=e=>eT(e,{}),ej=e=>eO(e,{}),eB=null,eP=e=>{eB=e},eR=()=>eB||process.env.BRICKS_PROFILE||K.get("currentProfile"),eV=()=>eB?"override":process.env.BRICKS_PROFILE?"env":"config",eM=e=>K.set("currentProfile",e),eL=()=>{var e=K.get("tokens"),t=K.get("currentProfile");return Object.keys(e).map(a=>({...e[a],name:a,current:a===t}))},eU=(e="default")=>{var t=K.get("tokens")[e];if(t?.type==="oauth"){var a=eS();if(!t.oauthSubject||t.oauthSubject!==a?.user?.sub)return null}return t?.bank||null},eq=(e,t,{expectedProfile:a}={})=>{var r=!1;return K.transaction(["tokens","oauth","baseUrl","activityLogBaseUrl"],({tokens:o={},oauth:i,baseUrl:n,activityLogBaseUrl:s})=>(!a||ee(a,o[e],i,n,s))&&o[e]?(r=!0,{tokens:{...o,[e]:{...o[e],bank:t}}}):{}),r},eJ=(e,{expectedProfile:t,expectedSpacekey:a}={})=>{var r=!1;return K.transaction(["tokens","oauth","baseUrl","activityLogBaseUrl"],({tokens:o={},oauth:i,baseUrl:n,activityLogBaseUrl:s})=>{if(t&&!ee(t,o[e],i,n,s)||!o[e]?.bank||a&&o[e].bank.spacekey!==a)return{};r=!0;var p={...o[e]};return delete p.bank,{tokens:{...o,[e]:p}}}),r},eY=(e=eR())=>{var t=K.get("tokens");return t[e]?.activityLogBaseUrl||K.get("activityLogBaseUrl")},eG=(e,t)=>{t?K.update("tokens",(a={})=>({...a,[t]:{...a[t],activityLogBaseUrl:e}})):K.set("activityLogBaseUrl",e)},eK=()=>{K.clear()};let eW=K},54782(e,t,a){a.d(t,{Cj:()=>i,vc:()=>o});var r="http://localhost:3006",o=(e,t,a,o=process.env)=>{var i=((e,t=process.env)=>{var a;if(t.BRICKS_CONTROLLER_URL)return t.BRICKS_CONTROLLER_URL.replace(/\/$/,"");try{a=new URL(e)}catch{return null}return"localhost"===a.hostname||"127.0.0.1"===a.hostname?r:/^display(-[a-z0-9]+)?\.bricks\.tools$/.test(a.hostname)?`${a.protocol}//${a.hostname.replace(/^display/,"control")}`:null})(e,o);if(!i)return null;var n=i===r?`dev-${t}`:t,s=Object.entries(a).map(([e,t])=>`${e}=${encodeURIComponent(t)}`).join("&");return`${i}/${n}?${s}`},i=(e,t,a=process.env)=>o(e,"webLauncher.html",{token:t},a)},9683(e,t,a){a.d(t,{Ed:()=>o,RZ:()=>r,mz:()=>i});var r=3e5,o=(e,t=Date.now())=>{if(!e)return{state:"unknown",tone:"gray",glyph:"○",label:"Unknown"};var a=t-new Date(e).getTime();return a<=r?{state:"online",tone:"green",glyph:"●",label:"Online"}:{state:"offline",tone:a<36e5?"yellow":"red",glyph:"○",label:a<36e5?`${Math.floor(a/6e4)}m ago`:a<864e5?`${Math.floor(a/36e5)}h ago`:`${Math.floor(a/864e5)}d ago`}},i=({state:e,glyph:t,label:a})=>`${t} ${"offline"===e?`Offline (${a})`:a}`},75646(e,t,a){a.r(t),a.d(t,{discoverDevToolsServers:()=>p,httpProbeSubnet:()=>d,verifyDevToolsServer:()=>l});var r,o,i=a(99436),n=a(19557),s="bricks-devtools",p=({timeout:e=3e3,idleTimeout:t=0}={})=>(0,n.YH)({port:19900,timeout:e,idleTimeout:t,buildQuery:()=>Buffer.from(JSON.stringify({t:"QUERY",v:"1.0",s:s,d:{id:`cli-${(0,n.BW)()}`}})),parseMessage:(e,t)=>{var a=(0,n.nl)(e,e=>e?.s===s);if(!a)return null;var r=t.address;return{key:`${r}:${a.port}`,value:{...a,address:r}}}}),d=(r=i(function*({port:e=19851,connectTimeout:t=500,concurrency:a=50,timeout:r=0}={}){var o=(0,n.r9)();if(0===o.length)return[];var s=[],p=r>0?Date.now()+r:0,d=[],u=new Set;for(var c of o){var m=c.address.split(".").slice(0,3).join(".");if(!u.has(m)){u.add(m);for(var h=1;h<255;h++)d.push(`${m}.${h}`)}}for(var f=0;f<d.length&&!(p&&Date.now()>=p);f+=a){var v=d.slice(f,f+a);yield Promise.allSettled(v.map(function(){var a=i(function*(a){var r=yield l(a,e,t);r&&s.push({...r,address:a,port:e})});return function(e){return a.apply(this,arguments)}}()))}return s}),function(){return r.apply(this,arguments)}),l=(o=i(function*(e,t,a=3e3){return(0,n.uE)(`http://${e}:${t}/devtools/info`,a)}),function(e,t){return o.apply(this,arguments)})},29988(e,t,a){a.d(t,{U:()=>o,i:()=>r});var r=()=>"u">typeof module&&"function"==typeof module.require?module.require("../gql/client.js"):Promise.all([a.e(2499),a.e(8295),a.e(907)]).then(a.bind(a,85382)),o=()=>"u">typeof module&&"function"==typeof module.require?module.require("../gql/controller-client.js"):Promise.all([a.e(2499),a.e(8295),a.e(7494)]).then(a.bind(a,59957))},19557(e,t,a){a.d(t,{BW:()=>s,YH:()=>u,nl:()=>d,r9:()=>l,uE:()=>c});var r,o=a(99436),i=a(41314),n=a(48161),s=()=>Math.random().toString(36).slice(2,9),p=new Set(["ANNOUNCE","RESPONSE"]),d=(e,t)=>{var a=JSON.parse(e.toString());return t(a)&&p.has(a.t)&&a.d?.info||null},l=()=>{var e=[];for(var t of Object.values(n.networkInterfaces()))for(var a of t)if(function(){if("IPv4"!==a.family||a.internal)return 1;var t=a.address.split(".").map(Number),r=a.netmask.split(".").map(Number),o=t.map((e,t)=>(e|255&~r[t]).toString()).join(".");e.push({address:a.address,broadcast:o})}())continue;return e},u=({port:e,timeout:t=3e3,idleTimeout:a=0,buildQuery:r,parseMessage:o})=>new Promise((n,s)=>{var p=new Map,d=i.createSocket("udp4"),u=null,c=null,m=!1,h=e=>{if(!m){m=!0,clearTimeout(u),clearTimeout(c);try{d.close()}catch{}e?s(e):n([...p.values()])}};d.on("error",h),d.on("message",(e,t)=>{if(!m)try{var r=o(e,t);if(!r||p.has(r.key))return;p.set(r.key,r.value),a&&!m&&(clearTimeout(c),c=setTimeout(h,a))}catch{}});try{d.bind(()=>{if(!m)try{d.setBroadcast(!0);var a=r();for(var o of(()=>{var e=new Set(["255.255.255.255","127.0.0.1"]);for(var t of l())e.add(t.broadcast);return[...e]})())d.send(a,0,a.length,e,o);u=setTimeout(h,t)}catch(e){h(e)}})}catch(e){h(e)}}),c=(r=o(function*(e,t=3e3){var a,r=new AbortController;try{a=setTimeout(()=>r.abort(),t);var o=yield fetch(e,{signal:r.signal});if(!o.ok)return null;return yield o.json()}catch{return null}finally{void 0!==a&&clearTimeout(a),r.abort()}}),function(e){return r.apply(this,arguments)})},63755(e,t,a){a.d(t,{EC:()=>M,IC:()=>L,UY:()=>j,X9:()=>J,Zd:()=>P,b2:()=>I,bo:()=>R,iF:()=>U,n_:()=>S,ph:()=>q});var r,o,i,n,s,p,d,l,u=a(68832),c=a(99436),m=a(76982),h=a(58611),f=a(35317),v=a(79657),g=a(64007),y=a(47988),D=process.env.BRICKS_OAUTH_DOMAIN||"auth0.bricks.tools",w=process.env.BRICKS_OAUTH_AUDIENCE||"https://display.bricks.tools",b="openid profile email offline_access",_=process.env.BRICKS_OAUTH_CLIENT_ID||"Atyy2gp0suIWE33rj8LtJ0pJpIGHiGaT",k="/callback",E="127.0.0.1",S=()=>!!_,C=(e,t,{signal:a}={})=>(()=>{var e=process.env.HTTPS_PROXY||process.env.https_proxy;if(!e)return v.Ay;var t=new g(e);return(e,a={})=>(0,v.Ay)(e,{...a,agent:t})})()(`https://${D}${e}`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString(),signal:a}),x=(r=c(function*(e){var t;try{t=yield e.json()}catch(e){if(e?.name==="AbortError")throw e;t={}}if(!e.ok){var a=Error(t.error_description||t.error||`HTTP ${e.status}`);throw a.code=t.error,a}return t}),function(e){return r.apply(this,arguments)}),$=(o=c(function*(e,t,{signal:a}={}){var r=new AbortController,o=()=>r.abort();a?.addEventListener("abort",o,{once:!0}),a?.aborted&&o();var i=setTimeout(()=>r.abort(),15e3);try{return yield x((yield C(e,t,{signal:r.signal})))}finally{clearTimeout(i),a?.removeEventListener("abort",o)}}),function(e,t){return o.apply(this,arguments)}),N=e=>String(e).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;"),A=({title:e,heading:t,message:a})=>`<!doctype html>
152
155
  <html lang="en">
153
156
  <head>