diff --git a/CHANGELOG.md b/CHANGELOG.md index f9bb439..7ff4e67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **CI Boots the Packaged MCP Bundle**: the MCP build step now starts the freshly built `dist/mcp/server.js` and completes a handshake, instead of only checking that it compiles. The artifact is the only thing that ships, so an unbootable bundle is now caught in CI rather than at runtime. Deliberately **not** a byte-for-byte freshness diff: the minifier allocates identifiers differently across platforms and Bun versions, so the bundle is not reproducible across runners — measured, an ubuntu rebuild of the macOS-built committed file differs only in renamed minified variables with identical code. ### Fixed +- **Read-Only MCP Refused Three Read-Only `approval-runs` Verbs**: `approval-runs search`, `approval-runs pick` and `approval-runs bridge` were refused by the read-only tool even though each only queries. The #117 note that `pick` had "moved into read-only" was true of the tool registry but not of the CLI allow-list, which is exactly the kind of split-brain the next entry prevents. +- **Consistency Test Between the CLI Allow-List and the Tool Registry**: the two read/write classifications are maintained by hand in different files, and they had already disagreed twice (`analytics analyze` allow-listed while its tool POSTs; the three verbs above missing). A test now derives the pairing mechanically — every `action === "x"` in `src/cli/commands/*` that dispatches to a `runTool("seal_…")` — and fails when a CLI verb that reaches a read-only tool is itself refused. It asserts a minimum number of pairs so a change in dispatch shape cannot make it silently vacuous, and names its two exceptions explicitly: the `deploy ` short forms, which `deploy` rejects at runtime, and `approval-runs search`, an accepted alias of `list` with no help-registry row. - **MCP Server Bundle Could Not Start At All**: the plugin shipped `dist/mcp/server.js` as its MCP entry point, but that bundle threw `TypeError: ... is not a constructor` while loading and never answered a single request. Because MCP defaults to off, it failed silently — enabling it produced no `seal_cli` tool and no visible error. - Root cause: the MCP entry (`src/server.ts`) was circularly entangled with the CLI command graph (`server → cli/runner → cli/commands/mcp → server`, and `server → cli/runner → cli/commands/http → http/routes → server`). When `bun build --target=node` flattened that cycle together with zod's own `core ↔ classic` cycle, zod's class initialisers ended up ordered after the top-level `z.lazy()` call the SDK makes at import time, leaving `ZodLazy` undefined at call time. - Fix: moved `tokenizeCommand` / `normalizeCliArgs` into a leaf module (`src/cli/tokenize.ts`) and made the `mcp` command import the server lazily, removing both cycles. The stock build command now emits a working bundle. diff --git a/dist/mcp/server.js b/dist/mcp/server.js index ec651c2..6d59067 100644 --- a/dist/mcp/server.js +++ b/dist/mcp/server.js @@ -2175,6 +2175,6 @@ selection, source authentication, response compaction, and diagnostics-friendly `)}catch{}let i=Buffer.concat(b);if(i.length<1000)throw Error(`Downloaded content is suspiciously small (${i.length} bytes)`);kS0(Y,i),yT(`✓ Download completed successfully (${(i.length/1024/1024).toFixed(1)} MB)`);return}catch(B){if(N)clearTimeout(N);if(T)clearTimeout(T);if(A)clearTimeout(A);let j=O||(B instanceof Error?B.message:String(B));W=Error(j),yT(` ↳ Mirror failed: ${W.message}`)}finally{if(N)clearTimeout(N);if(T)clearTimeout(T);if(A)clearTimeout(A)}}throw Error(`Failed to download asset from all mirrors: ${W?.message}`)}function Ug1($,Y,z){let U=gU("tar",["-xzf",$,"-C",Y],{stdio:"pipe"});if(U.status!==0)throw Error(`Failed to extract tar archive: ${U.stderr.toString()}`);bS0($);let Q=z==="windows"?"seal-use.exe":"seal-use",J=gU("find",[Y,"-type","f"],{encoding:"utf8"}).stdout.trim().split(` `).filter(Boolean),I=J.find((K)=>K.endsWith(`/${Q}`)||K.endsWith(Q));if(I)return I;return J[0]||$}function Qg1($,Y,z){let U=gU("unzip",["-q","-o",$,"-d",Y],{stdio:"pipe"});if(U.status!==0)throw Error(`Failed to extract zip archive: ${U.stderr.toString()}`);bS0($);let Q=z==="windows"?"seal-use.exe":"seal-use",J=gU("find",[Y,"-type","f"],{encoding:"utf8"}).stdout.trim().split(` -`).filter(Boolean),I=J.find((K)=>K.endsWith(`/${Q}`)||K.endsWith(Q));if(I)return I;return J[0]||$}function nS0($,Y){let z=$.replace(/^v/,"").split(".").map((Q)=>Number.parseInt(Q,10)||0),U=Y.replace(/^v/,"").split(".").map((Q)=>Number.parseInt(Q,10)||0);for(let Q=0;QI)return 1;if(J0}function uS0($,Y,z={}){let U=gU($,Y,{cwd:z.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(U.stdout)console.error(U.stdout.trimEnd());if(U.stderr)console.error(U.stderr.trimEnd());if(U.status!==0)throw Error(`${$} ${Y.join(" ")} failed with status ${U.status}`)}var iS0="yunyingk/seal-use",Tq="yunyingk/seal-home",aS1="SEAL_USE_GITHUB_REPO",tS1="SEAL_HOME_GITHUB_REPO";var pS0=o(()=>{yS0();Nq();a9();Uo();J4();Io()});async function dS0($,Y,z,U,Q){if($==="create"){let J=S(Q.options.name)??Y,I=S(Q.options.phone);if(!J||!I)throw Error("Usage: seal-use users create --name --phone [--dept ]");let K=S(Q.options.dept)??S(Q.options.departmentId);await k0("seal_user_create",z,U,{name:J,phone:I,departmentIds:K?[K]:void 0},C0(Q.options));return}if($==="reset-password"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users reset-password ");await k0("seal_user_reset_password",z,U,{userId:J},C0(Q.options));return}if($==="search"||$==="list"){let J=Y??S(Q.options.keyword)??S(Q.options.query)??"";await k0("seal_user_search",z,U,{keyword:J},C0(Q.options));return}if($==="get"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users get ");await k0("seal_user_get",z,U,{userId:J},C0(Q.options));return}if($==="delete"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users delete ");await k0("seal_user_delete",z,U,{userId:J},C0(Q.options));return}if($==="activate"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users activate ");await k0("seal_user_activate",z,U,{userId:J},C0(Q.options));return}if($==="delegation"||$==="impersonate"){let J=Y??S(Q.options.userId)??S(Q.options.phone);if(!J)throw Error("Usage: seal-use users delegation [--note ]");let I=S(Q.options.note);await k0("seal_user_delegation_create",z,U,{userIdOrPhone:J,note:I},C0(Q.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}var mS0=o(()=>{o4();D4();J4()});import{dirname as Zo,join as Jg1}from"node:path";import{fileURLToPath as Ig1}from"node:url";function Wg1($){if(!$.length)return!1;let Y=$[0]?.toLowerCase(),z=$[1]?.toLowerCase();if(Y&&Gg1.has(Y))return!0;if((Y==="service"||Y==="daemon")&&z==="run")return!0;return!1}function Bq($,Y={}){if(Wg1($))return rS0($,Y);let z=oS0.then(()=>rS0($,Y));return oS0=z.then(()=>{return},()=>{return}),z}async function rS0($,Y){let z=[],U=[],Q=console.log,J=console.error,I={appRoot:Y.appRoot??lS0,entryFile:Y.entryFile??Jg1(Y.appRoot??lS0,"src","cli.ts"),launcher:Y.launcher};console.log=(...K)=>{z.push(Dl(K))},console.error=(...K)=>{U.push(Dl(K))};try{return await Hg1($,I),{stdout:qq(z),stderr:qq(U),isError:!1,exitCode:0}}catch(K){let G=Vq(K instanceof Error?K.message:String(K)),W=EZ(K);if(U.push(G),W.nextAction&&!G.includes("Next action:"))U.push(`\uD83D\uDC49 Next action: ${W.nextAction}`);return{stdout:qq(z),stderr:qq(U),isError:!0,exitCode:W.exitCode}}finally{console.log=Q,console.error=J}}async function Hg1($,Y){let z=Zq($),[U,Q,J]=z.command;if(U==="version"||U==="v"||Boolean(z.options.version)||Boolean(z.options.v)||Boolean(z.options.V)){c0(PW);return}let I=sR0(z);if(I.isHelp){$_0(I.target);return}if(!U||!Kg1.has(U))throw Error(`Unknown command: ${z.command.join(" ")}. Run 'seal-use help' for available commands.`);if(U==="webhook"&&(Q==="resource-pack"||Q==="pack"||Q==="material-pack")&&J==="preview"){let W=z.command[3]??S(z.options.file)??S(z.options.input);if(!W)throw Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");await U_0(W,hK(z.options));return}if(U==="openapi"){US0(z);return}if(U==="mcp-config"){tl();return}if(U==="skill"){PS0(Q,J,z);return}if(U==="mcp"||U==="server"){await eh0(Q,z);return}if(U==="probe"){await ZS0(Q,J,z);return}if(U==="doctor"){await bh0(Q,J,z);return}if(U==="test"){await Go(Q,J,z);return}if(U==="config"){lv0(Q,J,z);return}if(U==="service"){await Jo(Q,Y,z);return}if(U==="stop"){await Jo("stop",Y,z);return}if(U==="http"||U==="serve"){await rh0(z);return}if(U==="update"||U==="changelog"){let W=U==="changelog"||Q==="changelog"||Q==="log"||Q==="history"||F0(z.options.changelog)===!0,H=Q==="check"||F0(z.options.check)===!0||F0(z.options["check-only"])===!0,X=S(z.options.version)??S(z.options.tag)??(!W&&!H&&Q&&!Q.startsWith("-")?Q:void 0);await cS0(Y,{checkOnly:H,changelogOnly:W,limit:s0(z.options.limit),force:F0(z.options.force),targetVersion:X,repo:S(z.options.repo)});return}if(U==="tools"&&Q==="list"){SS0();return}if(U==="corps"||U==="corp"){if(Q==="regression"||Q==="test-regression"){await Go("regression",J,z);return}await yv0(Q,J,z);return}if(U==="delegation"&&Q==="create"&&(("from-link"in z.options)||("link"in z.options))){let W=S(z.options["from-link"])??S(z.options.link);if(!W)throw Error("Usage: seal-use delegation create --from-link [--note ]");await Yh0(W,S(z.options.note));return}if(U==="rules"&&Q==="lint"&&(("file"in z.options)||("f"in z.options))){let W;try{W=E1(S(z.options.corp))}catch{W={id:"local",name:"Local Workspace",source:{type:"native"}}}await el(Q,J,null,W,z);return}if(U==="auth"&&(Q==="extract-keys"||Q==="extract-key")){await iv0(J,z);return}let K=E1(S(z.options.corp));if(U==="source"){await TS0(Q,K);return}if(U==="auth"){await cv0(Q,K,z);return}let G=await j1(K);if(U==="delegation"){await zh0(Q,J,G,K,z);return}if(U==="users"){await dS0(Q,J,G,K,z);return}if(U==="contacts"){await rv0(Q,J,G,K,z);return}if(U==="data"){await av0(Q,G,K,z);return}if(U==="llm"){await ah0(Q,G,K,z);return}if(U==="permissions"){await JS0(Q,G,K,z);return}if(U==="billing"){await dv0(Q,G,K,z);return}if(U==="webhook"||U==="webhooks"){await HT(Q,J,G,K,z);return}if(U==="context"){await ev0(G,K,z);return}if(U==="rules"){await el(Q,J,G,K,z);return}if(U==="approval-runs"){await Q_0(Q,J,G,K,z);return}if(U==="analytics"){await I_0(Q,J,G,K,z);return}if(U==="simulation"){await NS0(Q,J,G,K,z);return}if(U==="deploy"){await Qh0(Q,J,z.command[3],G,K,z);return}if(U==="preference"||U==="preferences"){await GS0(Q,J,z.command[3],z.command[4],G,K,z);return}if(U==="tool"){await vS0(Q,G,K,z);return}throw Error(`Unknown command: ${z.command.join(" ")}. Run 'seal-use help' for available commands.`)}var lS0,Kg1,Gg1,oS0;var sl=o(()=>{i8();a9();J_0();K_0();pv0();mv0();ov0();sv0();tv0();$h0();fl();Uh0();Jh0();ih0();sh0();th0();$S0();QS0();IS0();WS0();qS0();VS0();Io();DS0();AS0();jS0();_S0();hS0();gS0();pS0();mS0();Bl();L$();o4();D4();Nl();J4();lS0=Zo(Zo(Zo(Ig1(import.meta.url)))),Kg1=new Set(["config","service","stop","http","serve","update","tools","corps","corp","tool","source","auth","delegation","users","contacts","data","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","analytics","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","doctor","changelog","test"]),Gg1=new Set(["http","server","web","mcp"]);oS0=Promise.resolve()});function Vg1($){let{command:Y}=Zq($),z=(Y[0]??"").toLowerCase();return{area:Xg1[z]??z,actionTokens:Y.slice(1).map((U)=>U.toLowerCase())}}function sS0($){let Y,z;try{({area:Y,actionTokens:z}=Vg1($))}catch{return!1}if(z.length===0&&qg1.has(Y))return!0;if(Y==="tool"){let Q=z[0];return Q!==void 0&&xR0(Q)}let U=Zg1[Y];if(!U)return!1;return U.some((Q)=>{let J=Q.split(" ").filter(Boolean);if(J.length===0)return z.length===0;if(J.length>z.length)return!1;return J.every((I,K)=>I===z[K])})}var Xg1,Zg1,qg1;var aS0=o(()=>{Xq();D4();Xg1={corp:"corps",webhooks:"webhook",preferences:"preference"},Zg1={corps:["list","search","get","current"],rules:["count","list","versions","version","get","search","lint","linters","pull"],webhook:["ready","status","list","get","resource-pack export","resource-pack preview"],"approval-runs":["summary","stats","count","export","flow","list","get","cited-rules","document-summary","attachments","result","url"],simulation:["batch-records","status","wait","specifications","approval-definitions","list","get","templates","integrations"],deploy:["hosecloud requirements","hosecloud list","hosecloud get","hosecloud status"],preference:["get","thinking-depth policies list"],config:["paths","get","mode","lint"],auth:["diagnose"],delegation:["list"],users:["search","get","delegation"],contacts:["departments","children","users","sync-time"],data:["expenses","invoices"],llm:["config","providers"],permissions:["available","configs"],billing:["status","plans","features"],analytics:["insight","risks","performance","export"],source:["config"],tools:["list"],skill:["dump","status"],service:["status","logs"],doctor:["","guide","paths","tenant"],openapi:[""]},qg1=new Set(["version","v","help","changelog","mcp-config"])});var YS0={};x8(YS0,{tokenizeCommand:()=>Dq,startServer:()=>Jg0,resolveMcpEnabled:()=>Ug0,createServer:()=>Qg0,SEAL_MCP_ENABLED_ENV:()=>Yg0,SEAL_CLI_WRITE_TOOL_NAME:()=>Cq,SEAL_CLI_TOOL_NAME:()=>kT,LEGACY_SEAL_MCP_ENABLED_ENV:()=>zg0});import{dirname as jq,resolve as tS0}from"node:path";import{fileURLToPath as Lg1}from"node:url";function Ug0($=process.env[Yg0]??process.env[zg0]){if($===void 0)return!1;return["1","true","yes","on"].includes($.trim().toLowerCase())}function Qg0($={}){let Y=$.enableCli??!0,z=new qW({name:"seal-use",version:P1},{capabilities:{tools:{}}});if(Y){let U=L.strictObject({command:L.string().describe("A seal-use CLI command, with or without the leading 'seal-use' or 'seal-home'.")});z.registerTool(kT,{title:"Run read-only seal-use CLI command",description:"Run a read-only seal-use CLI command and return its JSON stdout. Only commands that read tenant state without changing it are accepted here; anything that mutates tenant state, publishes configuration, mints credentials, self-updates or starts a server is "+`refused — use ${Cq} for those after confirming with the user.`,inputSchema:U,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},async({command:Q})=>eS0(Q,{requireReadOnly:!0})),z.registerTool(Cq,{title:"Run mutating seal-use CLI command",description:"Run a seal-use CLI command that changes tenant state, publishes configuration, or sends things outward (create/update/push/mark/bind/sync/deploy/delete/reset-password, rule publishing, simulation batches, self-update). Confirm the exact command with the user before calling this tool.",inputSchema:U,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},async({command:Q})=>eS0(Q,{requireReadOnly:!1}))}return z}async function eS0($,Y){let z=Y.requireReadOnly?kT:Cq;if(!$?.trim())return Eq({stdout:"",stderr:`${z} requires a non-empty command string`,isError:!0,exitCode:2});let U;try{if(U=ph0(Dq($)),!U.length)throw Error(`${z} requires a non-empty command string`)}catch(Q){let J=EZ(Q);return Eq({stdout:"",stderr:Q instanceof Error?Q.message:String(Q),isError:!0,exitCode:J.exitCode})}if(Y.requireReadOnly&&!sS0(U))return Eq({stdout:"",stderr:`${kT} only runs read-only commands, and "${U.join(" ")}" is not one of them. Confirm the command with the user, then call ${Cq}.`,isError:!0,exitCode:2});try{return Eq(await Bq(U,{appRoot:$g0,entryFile:m7,launcher:{command:process.execPath,args:[m7,"--seal-home-cli"]}}))}catch(Q){let J=EZ(Q);return Eq({stdout:"",stderr:Q instanceof Error?Q.message:String(Q),isError:!0,exitCode:J.exitCode})}}function Jg0(){let $=Ug0(),Y=qe(()=>Qg0({enableCli:$}));return console.error($?"seal-use MCP server running on stdio":"seal-use MCP server connected with seal_cli disabled by configuration"),Y}function Eq($){return{content:[{type:"text",text:$.isError?$.stderr||$.stdout:$.stdout}],isError:$.isError}}async function Fg1(){let $=await Bq(process.argv.slice(3),{appRoot:$g0,entryFile:m7,launcher:{command:process.execPath,args:[m7,"--seal-use-cli"]}});if($.stdout)process.stdout.write($.stdout);if($.stderr)process.stderr.write(`${$.stderr}${$.stderr.endsWith(` +`).filter(Boolean),I=J.find((K)=>K.endsWith(`/${Q}`)||K.endsWith(Q));if(I)return I;return J[0]||$}function nS0($,Y){let z=$.replace(/^v/,"").split(".").map((Q)=>Number.parseInt(Q,10)||0),U=Y.replace(/^v/,"").split(".").map((Q)=>Number.parseInt(Q,10)||0);for(let Q=0;QI)return 1;if(J0}function uS0($,Y,z={}){let U=gU($,Y,{cwd:z.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(U.stdout)console.error(U.stdout.trimEnd());if(U.stderr)console.error(U.stderr.trimEnd());if(U.status!==0)throw Error(`${$} ${Y.join(" ")} failed with status ${U.status}`)}var iS0="yunyingk/seal-use",Tq="yunyingk/seal-home",aS1="SEAL_USE_GITHUB_REPO",tS1="SEAL_HOME_GITHUB_REPO";var pS0=o(()=>{yS0();Nq();a9();Uo();J4();Io()});async function dS0($,Y,z,U,Q){if($==="create"){let J=S(Q.options.name)??Y,I=S(Q.options.phone);if(!J||!I)throw Error("Usage: seal-use users create --name --phone [--dept ]");let K=S(Q.options.dept)??S(Q.options.departmentId);await k0("seal_user_create",z,U,{name:J,phone:I,departmentIds:K?[K]:void 0},C0(Q.options));return}if($==="reset-password"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users reset-password ");await k0("seal_user_reset_password",z,U,{userId:J},C0(Q.options));return}if($==="search"||$==="list"){let J=Y??S(Q.options.keyword)??S(Q.options.query)??"";await k0("seal_user_search",z,U,{keyword:J},C0(Q.options));return}if($==="get"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users get ");await k0("seal_user_get",z,U,{userId:J},C0(Q.options));return}if($==="delete"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users delete ");await k0("seal_user_delete",z,U,{userId:J},C0(Q.options));return}if($==="activate"){let J=Y??S(Q.options.userId);if(!J)throw Error("Usage: seal-use users activate ");await k0("seal_user_activate",z,U,{userId:J},C0(Q.options));return}if($==="delegation"||$==="impersonate"){let J=Y??S(Q.options.userId)??S(Q.options.phone);if(!J)throw Error("Usage: seal-use users delegation [--note ]");let I=S(Q.options.note);await k0("seal_user_delegation_create",z,U,{userIdOrPhone:J,note:I},C0(Q.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}var mS0=o(()=>{o4();D4();J4()});import{dirname as Zo,join as Jg1}from"node:path";import{fileURLToPath as Ig1}from"node:url";function Wg1($){if(!$.length)return!1;let Y=$[0]?.toLowerCase(),z=$[1]?.toLowerCase();if(Y&&Gg1.has(Y))return!0;if((Y==="service"||Y==="daemon")&&z==="run")return!0;return!1}function Bq($,Y={}){if(Wg1($))return rS0($,Y);let z=oS0.then(()=>rS0($,Y));return oS0=z.then(()=>{return},()=>{return}),z}async function rS0($,Y){let z=[],U=[],Q=console.log,J=console.error,I={appRoot:Y.appRoot??lS0,entryFile:Y.entryFile??Jg1(Y.appRoot??lS0,"src","cli.ts"),launcher:Y.launcher};console.log=(...K)=>{z.push(Dl(K))},console.error=(...K)=>{U.push(Dl(K))};try{return await Hg1($,I),{stdout:qq(z),stderr:qq(U),isError:!1,exitCode:0}}catch(K){let G=Vq(K instanceof Error?K.message:String(K)),W=EZ(K);if(U.push(G),W.nextAction&&!G.includes("Next action:"))U.push(`\uD83D\uDC49 Next action: ${W.nextAction}`);return{stdout:qq(z),stderr:qq(U),isError:!0,exitCode:W.exitCode}}finally{console.log=Q,console.error=J}}async function Hg1($,Y){let z=Zq($),[U,Q,J]=z.command;if(U==="version"||U==="v"||Boolean(z.options.version)||Boolean(z.options.v)||Boolean(z.options.V)){c0(PW);return}let I=sR0(z);if(I.isHelp){$_0(I.target);return}if(!U||!Kg1.has(U))throw Error(`Unknown command: ${z.command.join(" ")}. Run 'seal-use help' for available commands.`);if(U==="webhook"&&(Q==="resource-pack"||Q==="pack"||Q==="material-pack")&&J==="preview"){let W=z.command[3]??S(z.options.file)??S(z.options.input);if(!W)throw Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");await U_0(W,hK(z.options));return}if(U==="openapi"){US0(z);return}if(U==="mcp-config"){tl();return}if(U==="skill"){PS0(Q,J,z);return}if(U==="mcp"||U==="server"){await eh0(Q,z);return}if(U==="probe"){await ZS0(Q,J,z);return}if(U==="doctor"){await bh0(Q,J,z);return}if(U==="test"){await Go(Q,J,z);return}if(U==="config"){lv0(Q,J,z);return}if(U==="service"){await Jo(Q,Y,z);return}if(U==="stop"){await Jo("stop",Y,z);return}if(U==="http"||U==="serve"){await rh0(z);return}if(U==="update"||U==="changelog"){let W=U==="changelog"||Q==="changelog"||Q==="log"||Q==="history"||F0(z.options.changelog)===!0,H=Q==="check"||F0(z.options.check)===!0||F0(z.options["check-only"])===!0,X=S(z.options.version)??S(z.options.tag)??(!W&&!H&&Q&&!Q.startsWith("-")?Q:void 0);await cS0(Y,{checkOnly:H,changelogOnly:W,limit:s0(z.options.limit),force:F0(z.options.force),targetVersion:X,repo:S(z.options.repo)});return}if(U==="tools"&&Q==="list"){SS0();return}if(U==="corps"||U==="corp"){if(Q==="regression"||Q==="test-regression"){await Go("regression",J,z);return}await yv0(Q,J,z);return}if(U==="delegation"&&Q==="create"&&(("from-link"in z.options)||("link"in z.options))){let W=S(z.options["from-link"])??S(z.options.link);if(!W)throw Error("Usage: seal-use delegation create --from-link [--note ]");await Yh0(W,S(z.options.note));return}if(U==="rules"&&Q==="lint"&&(("file"in z.options)||("f"in z.options))){let W;try{W=E1(S(z.options.corp))}catch{W={id:"local",name:"Local Workspace",source:{type:"native"}}}await el(Q,J,null,W,z);return}if(U==="auth"&&(Q==="extract-keys"||Q==="extract-key")){await iv0(J,z);return}let K=E1(S(z.options.corp));if(U==="source"){await TS0(Q,K);return}if(U==="auth"){await cv0(Q,K,z);return}let G=await j1(K);if(U==="delegation"){await zh0(Q,J,G,K,z);return}if(U==="users"){await dS0(Q,J,G,K,z);return}if(U==="contacts"){await rv0(Q,J,G,K,z);return}if(U==="data"){await av0(Q,G,K,z);return}if(U==="llm"){await ah0(Q,G,K,z);return}if(U==="permissions"){await JS0(Q,G,K,z);return}if(U==="billing"){await dv0(Q,G,K,z);return}if(U==="webhook"||U==="webhooks"){await HT(Q,J,G,K,z);return}if(U==="context"){await ev0(G,K,z);return}if(U==="rules"){await el(Q,J,G,K,z);return}if(U==="approval-runs"){await Q_0(Q,J,G,K,z);return}if(U==="analytics"){await I_0(Q,J,G,K,z);return}if(U==="simulation"){await NS0(Q,J,G,K,z);return}if(U==="deploy"){await Qh0(Q,J,z.command[3],G,K,z);return}if(U==="preference"||U==="preferences"){await GS0(Q,J,z.command[3],z.command[4],G,K,z);return}if(U==="tool"){await vS0(Q,G,K,z);return}throw Error(`Unknown command: ${z.command.join(" ")}. Run 'seal-use help' for available commands.`)}var lS0,Kg1,Gg1,oS0;var sl=o(()=>{i8();a9();J_0();K_0();pv0();mv0();ov0();sv0();tv0();$h0();fl();Uh0();Jh0();ih0();sh0();th0();$S0();QS0();IS0();WS0();qS0();VS0();Io();DS0();AS0();jS0();_S0();hS0();gS0();pS0();mS0();Bl();L$();o4();D4();Nl();J4();lS0=Zo(Zo(Zo(Ig1(import.meta.url)))),Kg1=new Set(["config","service","stop","http","serve","update","tools","corps","corp","tool","source","auth","delegation","users","contacts","data","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","analytics","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","doctor","changelog","test"]),Gg1=new Set(["http","server","web","mcp"]);oS0=Promise.resolve()});function Vg1($){let{command:Y}=Zq($),z=(Y[0]??"").toLowerCase();return{area:Xg1[z]??z,actionTokens:Y.slice(1).map((U)=>U.toLowerCase())}}function sS0($){let Y,z;try{({area:Y,actionTokens:z}=Vg1($))}catch{return!1}if(z.length===0&&qg1.has(Y))return!0;if(Y==="tool"){let Q=z[0];return Q!==void 0&&xR0(Q)}let U=Zg1[Y];if(!U)return!1;return U.some((Q)=>{let J=Q.split(" ").filter(Boolean);if(J.length===0)return z.length===0;if(J.length>z.length)return!1;return J.every((I,K)=>I===z[K])})}var Xg1,Zg1,qg1;var aS0=o(()=>{Xq();D4();Xg1={corp:"corps",webhooks:"webhook",preferences:"preference"},Zg1={corps:["list","search","get","current"],rules:["count","list","versions","version","get","search","lint","linters","pull"],webhook:["ready","status","list","get","resource-pack export","resource-pack preview"],"approval-runs":["summary","stats","count","export","flow","list","search","pick","bridge","get","cited-rules","document-summary","attachments","result","url"],simulation:["batch-records","status","wait","specifications","approval-definitions","list","get","templates","integrations"],deploy:["hosecloud requirements","hosecloud list","hosecloud get","hosecloud status"],preference:["get","thinking-depth policies list"],config:["paths","get","mode","lint"],auth:["diagnose"],delegation:["list"],users:["search","get","delegation"],contacts:["departments","children","users","sync-time"],data:["expenses","invoices"],llm:["config","providers"],permissions:["available","configs"],billing:["status","plans","features"],analytics:["insight","risks","performance","export"],source:["config"],tools:["list"],skill:["dump","status"],service:["status","logs"],doctor:["","guide","paths","tenant"],openapi:[""]},qg1=new Set(["version","v","help","changelog","mcp-config"])});var YS0={};x8(YS0,{tokenizeCommand:()=>Dq,startServer:()=>Jg0,resolveMcpEnabled:()=>Ug0,createServer:()=>Qg0,SEAL_MCP_ENABLED_ENV:()=>Yg0,SEAL_CLI_WRITE_TOOL_NAME:()=>Cq,SEAL_CLI_TOOL_NAME:()=>kT,LEGACY_SEAL_MCP_ENABLED_ENV:()=>zg0});import{dirname as jq,resolve as tS0}from"node:path";import{fileURLToPath as Lg1}from"node:url";function Ug0($=process.env[Yg0]??process.env[zg0]){if($===void 0)return!1;return["1","true","yes","on"].includes($.trim().toLowerCase())}function Qg0($={}){let Y=$.enableCli??!0,z=new qW({name:"seal-use",version:P1},{capabilities:{tools:{}}});if(Y){let U=L.strictObject({command:L.string().describe("A seal-use CLI command, with or without the leading 'seal-use' or 'seal-home'.")});z.registerTool(kT,{title:"Run read-only seal-use CLI command",description:"Run a read-only seal-use CLI command and return its JSON stdout. Only commands that read tenant state without changing it are accepted here; anything that mutates tenant state, publishes configuration, mints credentials, self-updates or starts a server is "+`refused — use ${Cq} for those after confirming with the user.`,inputSchema:U,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},async({command:Q})=>eS0(Q,{requireReadOnly:!0})),z.registerTool(Cq,{title:"Run mutating seal-use CLI command",description:"Run a seal-use CLI command that changes tenant state, publishes configuration, or sends things outward (create/update/push/mark/bind/sync/deploy/delete/reset-password, rule publishing, simulation batches, self-update). Confirm the exact command with the user before calling this tool.",inputSchema:U,annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},async({command:Q})=>eS0(Q,{requireReadOnly:!1}))}return z}async function eS0($,Y){let z=Y.requireReadOnly?kT:Cq;if(!$?.trim())return Eq({stdout:"",stderr:`${z} requires a non-empty command string`,isError:!0,exitCode:2});let U;try{if(U=ph0(Dq($)),!U.length)throw Error(`${z} requires a non-empty command string`)}catch(Q){let J=EZ(Q);return Eq({stdout:"",stderr:Q instanceof Error?Q.message:String(Q),isError:!0,exitCode:J.exitCode})}if(Y.requireReadOnly&&!sS0(U))return Eq({stdout:"",stderr:`${kT} only runs read-only commands, and "${U.join(" ")}" is not one of them. Confirm the command with the user, then call ${Cq}.`,isError:!0,exitCode:2});try{return Eq(await Bq(U,{appRoot:$g0,entryFile:m7,launcher:{command:process.execPath,args:[m7,"--seal-home-cli"]}}))}catch(Q){let J=EZ(Q);return Eq({stdout:"",stderr:Q instanceof Error?Q.message:String(Q),isError:!0,exitCode:J.exitCode})}}function Jg0(){let $=Ug0(),Y=qe(()=>Qg0({enableCli:$}));return console.error($?"seal-use MCP server running on stdio":"seal-use MCP server connected with seal_cli disabled by configuration"),Y}function Eq($){return{content:[{type:"text",text:$.isError?$.stderr||$.stdout:$.stdout}],isError:$.isError}}async function Fg1(){let $=await Bq(process.argv.slice(3),{appRoot:$g0,entryFile:m7,launcher:{command:process.execPath,args:[m7,"--seal-use-cli"]}});if($.stdout)process.stdout.write($.stdout);if($.stderr)process.stderr.write(`${$.stderr}${$.stderr.endsWith(` `)?"":` `}`);process.exitCode=$.exitCode}var m7,$g0,kT="seal_cli",Cq="seal_cli_write",Yg0="SEAL_USE_MCP_ENABLED",zg0="SEAL_HOME_MCP_ENABLED",wg1;var zS0=o(async()=>{Xe();Ve();B$();sl();aS0();L$();a9();m7=Lg1(import.meta.url),$g0=m7.includes("/dist/mcp/")||m7.includes("\\dist\\mcp\\")?jq(jq(jq(m7))):jq(jq(m7));wg1=Boolean(I0.main==I0.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&tS0(process.argv[1])===tS0(m7));if(wg1)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await Fg1();else try{Jg0()}catch($){console.error($),process.exitCode=1}});await zS0();export{Dq as tokenizeCommand,Jg0 as startServer,Ug0 as resolveMcpEnabled,Qg0 as createServer,Yg0 as SEAL_MCP_ENABLED_ENV,Cq as SEAL_CLI_WRITE_TOOL_NAME,kT as SEAL_CLI_TOOL_NAME,zg0 as LEGACY_SEAL_MCP_ENABLED_ENV}; diff --git a/src/cli/read-only.test.ts b/src/cli/read-only.test.ts index e566a8e..af260ad 100644 --- a/src/cli/read-only.test.ts +++ b/src/cli/read-only.test.ts @@ -1,4 +1,6 @@ import { describe, expect, test } from "bun:test"; +import { readFileSync, readdirSync } from "node:fs"; +import { join } from "node:path"; import { HELP_REGISTRY } from "./help.js"; import { KNOWN_AREAS } from "./runner.js"; import { SEAL_MUTATING_TOOLS, SEAL_READ_ONLY_TOOLS, sealTools } from "../domains/seal/tools.js"; @@ -16,10 +18,15 @@ describe("CLI read-only classification", () => { } }); + // Actions the dispatcher accepts that carry no help-registry row, so they are documented + // nowhere else. Kept explicit: anything not a registry entry and not listed here fails below. + const ACTIONS_WITHOUT_REGISTRY_ENTRY = new Set(["approval-runs search"]); + test("every allow-listed command exists in the help registry", () => { const byArea = new Map(HELP_REGISTRY.map((area) => [area.area, area.commands.map((c) => c.name)])); for (const { area, action } of listReadOnlyCommands()) { + if (ACTIONS_WITHOUT_REGISTRY_ENTRY.has(`${area} ${action}`)) continue; expect({ area, dispatchable: KNOWN_AREAS.has(area) }).toEqual({ area, dispatchable: true }); expect({ area, action, known: byArea.get(area)?.includes(action) }).toEqual({ area, @@ -117,3 +124,41 @@ describe("CLI read-only classification", () => { expect(isReadOnlyCliCommand(["--json"])).toBe(false); }); }); + +// The two classifications are maintained by hand, in different files: the CLI allow-list here and +// SEAL_READ_ONLY_TOOLS in the tool registry. Nothing stopped them from disagreeing, and they did — +// `analytics analyze` was allow-listed while its tool POSTs, and three read-only approval-runs verbs +// were simply missing. This derives one from the other and fails on any new disagreement. +describe("CLI allow-list agrees with the tool registry", () => { + // `deploy` only accepts `deploy hosecloud `; the short `deploy ` form throws + // "未知的发布目标系统" at runtime, so these pairs are unreachable rather than refused. + const UNREACHABLE_CLI_FORMS = new Set(["deploy requirements", "deploy list", "deploy status"]); + + test("every CLI verb dispatching to a read-only tool is itself read-only", () => { + const files = readdirSync(join(import.meta.dir, "commands")).filter( + (f) => f.endsWith(".ts") && !f.endsWith(".test.ts") + ); + + const pairs: Array<{ area: string; action: string; tool: string }> = []; + for (const file of files) { + const area = file.replace(/\.ts$/, ""); + const source = readFileSync(join(import.meta.dir, "commands", file), "utf8"); + const pattern = /action === "([a-z0-9-]+)"[\s\S]{0,600}?runTool\(\s*"(seal_[a-z_0-9]+)"/g; + let match; + while ((match = pattern.exec(source))) { + pairs.push({ area, action: match[1]!, tool: match[2]! }); + } + } + + // If the dispatch shape changes this silently finds nothing, which would make the test vacuous. + expect(pairs.length).toBeGreaterThan(50); + + const disagreements = pairs + .filter((pair) => SEAL_READ_ONLY_TOOLS.has(pair.tool)) + .filter((pair) => !UNREACHABLE_CLI_FORMS.has(`${pair.area} ${pair.action}`)) + .filter((pair) => !isReadOnlyCliCommand([pair.area, pair.action])) + .map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`); + + expect(disagreements).toEqual([]); + }); +}); diff --git a/src/cli/read-only.ts b/src/cli/read-only.ts index 7ee165f..ccf5af6 100644 --- a/src/cli/read-only.ts +++ b/src/cli/read-only.ts @@ -37,6 +37,10 @@ const READ_ONLY_COMMANDS: Record = { "export", "flow", "list", + // `search` is an accepted alias of `list` in the dispatcher but has no help-registry entry. + "search", + "pick", + "bridge", "get", "cited-rules", "document-summary",