superclawd 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -11
- package/dist/hook-helper.mjs +4 -4
- package/dist/index.js +76 -93
- package/dist/mcp-server.mjs +2 -2
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ One command. Your standards, every session.
|
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
8
|
npm install -g superclawd
|
|
9
|
-
superclawd
|
|
9
|
+
superclawd login # connect this machine in your browser (one time)
|
|
10
10
|
superclawd # launch Claude Code, supercharged
|
|
11
11
|
```
|
|
12
12
|
|
|
@@ -38,18 +38,15 @@ npm install -g superclawd
|
|
|
38
38
|
|
|
39
39
|
## Set up (one time)
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
Connect this machine to your account in the browser — no copy‑pasting:
|
|
42
42
|
|
|
43
43
|
```bash
|
|
44
|
-
superclawd
|
|
44
|
+
superclawd login
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
This opens your browser. Approve the request under **Settings → Devices**, and the CLI receives a credential for this machine automatically. You only do this once per machine.
|
|
48
48
|
|
|
49
|
-
|
|
50
|
-
superclawd configure --show # show your current configuration
|
|
51
|
-
superclawd configure --reset # clear it and start over
|
|
52
|
-
```
|
|
49
|
+
Manage or revoke your connected machines any time under **Settings → Devices** in the dashboard. Re‑running `superclawd login` rotates this machine's credential.
|
|
53
50
|
|
|
54
51
|
## Use it
|
|
55
52
|
|
|
@@ -65,13 +62,13 @@ That launches Claude Code with your workspace's skills, agents, commands, workfl
|
|
|
65
62
|
|
|
66
63
|
## Your default workspace
|
|
67
64
|
|
|
68
|
-
On more than one team or project? A
|
|
65
|
+
On more than one team or project? A connected machine works across **all** your workspaces. `superclawd switch` sets your **default workspace** — the one each `superclawd` launch boots into:
|
|
69
66
|
|
|
70
67
|
```bash
|
|
71
68
|
superclawd switch
|
|
72
69
|
```
|
|
73
70
|
|
|
74
|
-
Pick from your workspaces and you're set; your next `superclawd` launch uses it. No need to
|
|
71
|
+
Pick from your workspaces and you're set; your next `superclawd` launch uses it. No need to log in again.
|
|
75
72
|
|
|
76
73
|
Prefer to choose per launch? Turn on **Choose workspace at startup** in `superclawd config` — then every `superclawd` shows the picker first and boots into whatever you pick (just for that session; your default stays put).
|
|
77
74
|
|
|
@@ -117,7 +114,7 @@ superclawd update
|
|
|
117
114
|
| Command | Description |
|
|
118
115
|
| --- | --- |
|
|
119
116
|
| `superclawd` | Launch Claude Code with your workspace loaded |
|
|
120
|
-
| `superclawd
|
|
117
|
+
| `superclawd login` | Connect this machine in your browser (one time per machine) |
|
|
121
118
|
| `superclawd switch` | Set your default workspace (pick from yours) |
|
|
122
119
|
| `superclawd config` | Toggle notifications + launch options |
|
|
123
120
|
| `superclawd update` | Update to the latest version |
|
package/dist/hook-helper.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
|
|
2
|
-
import{readFileSync as m,writeFileSync as $,existsSync as F}from"node:fs";import{basename as
|
|
2
|
+
import{readFileSync as m,writeFileSync as $,existsSync as F}from"node:fs";import{basename as B}from"node:path";import{randomUUID as Y}from"node:crypto";import{spawn as b}from"node:child_process";var N=`SUPERCLAWD \u2014 operating manual (always in effect):
|
|
3
3
|
- The ALWAYS rules below are ALREADY LOADED and active for this entire session.
|
|
4
4
|
Apply them directly to all work. Do NOT call any tool to fetch them \u2014 you
|
|
5
5
|
already have them in full.
|
|
@@ -8,8 +8,8 @@ import{readFileSync as m,writeFileSync as $,existsSync as F}from"node:fs";import
|
|
|
8
8
|
the \`get_directives\` tool with that file's skillId (a UUID) BEFORE acting,
|
|
9
9
|
and apply what it returns. Those skill files are pointers, not the rules.
|
|
10
10
|
- Only call \`get_directives\` with a UUID skillId taken from an activated skill
|
|
11
|
-
file. Never call it for the ALWAYS rules, and never pass a skill name.`;function
|
|
11
|
+
file. Never call it for the ALWAYS rules, and never pass a skill name.`;function R(t){let e=N,n=(t||"").trim();return n&&(e+=`
|
|
12
12
|
|
|
13
13
|
ALWAYS \u2014 foundational rules (already loaded & active for this whole session; apply directly, never fetch):
|
|
14
|
-
${n}`),e}function k(t,e){return JSON.stringify({hookSpecificOutput:{hookEventName:t,additionalContext:
|
|
15
|
-
`).filter(Boolean);for(let n=e.length-1;n>=0;n--){let o=JSON.parse(e[n]),s=o.message??o;if((s.role??o.type)==="assistant"){let r=s.content,i=Array.isArray(r)?r.map(c=>c.text??"").join(" "):typeof r=="string"?r:"";if(i.trim())return i.trim().slice(0,300)}}}catch{}return""}function z(t,e,n){if(!(!
|
|
14
|
+
${n}`),e}function k(t,e){return JSON.stringify({hookSpecificOutput:{hookEventName:t,additionalContext:R(e)}})}import{homedir as D}from"node:os";import{join as f}from"node:path";import{readFileSync as P,writeFileSync as re,mkdirSync as ie,chmodSync as ce,existsSync as ae}from"node:fs";var fe=(process.env.SUPERCLAWD_BACKEND||"real").toLowerCase();var pe=process.env.SUPERCLAWD_MCP_API_URL||"https://mcp-api.superclawd.com",ue=process.env.SUPERCLAWD_API_URL||"https://api.superclawd.com",x=process.env.SUPERCLAWD_HOME||f(D(),".superclawd"),L=f(x,"sessions"),U=f(x,"config.json");function W(t){if(!t||typeof t!="object")return{};let e=t,n=e.credentials??{...typeof e.keyId=="string"?{keyId:e.keyId}:{},...typeof e.secret=="string"?{secret:e.secret}:{},...typeof e.workspace=="string"?{workspace:e.workspace}:{}},o=e.preferences??{...typeof e.skipPermissions=="boolean"?{skipPermissions:e.skipPermissions}:{},...typeof e.notifications=="boolean"?{notifications:e.notifications}:{},...typeof e.chooseWorkspaceAtStartup=="boolean"?{chooseWorkspaceAtStartup:e.chooseWorkspaceAtStartup}:{}},s={};return Object.keys(n).length&&(s.credentials=n),Object.keys(o).length&&(s.preferences=o),typeof e.machineId=="string"&&(s.machineId=e.machineId),s}function T(){try{return W(JSON.parse(P(U,"utf8")))}catch{return null}}function M(){return T()?.preferences?.notifications===!0}function j(t){return f(L,t)}function J(t){return f(t,"config.json")}function K(t){try{return JSON.parse(P(J(t),"utf8"))}catch{return null}}function l(t){let e=t?K(j(t)):null;return e&&typeof e.notifications=="boolean"?e.notifications:M()}var de=1e3*60*60*24*3;var y=process.env.SUPERCLAWD_MCP_API_URL||"https://mcp-api.superclawd.com",S=(process.env.SUPERCLAWD_BACKEND||"real").toLowerCase(),p=process.env.MCP_KEY_ID||"",u=process.env.MCP_SECRET||"",d=process.env.MCP_WORKSPACE||"";function C(){return{"content-type":"application/json","x-mcp-key-id":p,"x-mcp-secret":u,"x-workspace-slug":d,"x-request-id":Y()}}async function I(t,e){let n=new AbortController,o=setTimeout(()=>n.abort(),e);try{return await fetch(t,{headers:C(),signal:n.signal})}finally{clearTimeout(o)}}async function q(t,e="SessionStart"){let n="";if(t)try{n=m(t,"utf8")}catch{}if(S!=="mock"&&p&&u&&d)try{let o=await I(`${y}/api/prompt/foundational`,3e3);if(o.ok){let s=await o.json();typeof s.text=="string"&&(n=s.text)}}catch{}process.stdout.write(k(e,n))}async function G(){let t=()=>process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}})),e=()=>process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"SuperClawd: out of credits. Top up at app.superclawd.com to load directives."}}));if(S==="mock"||!p||!u||!d)return void t();try{let n=await I(`${y}/api/prompt/balance`,2e3);if(!n.ok)return void t();let s=(await n.json()).content,r=(Array.isArray(s)?s.map(i=>i.text??"").join(""):"").match(/<current_balance>([\d.]+)<\/current_balance>/);return r&&Number(r[1])<=0?void e():void t()}catch{return void t()}}function g(){return new Promise(t=>{let e="";try{process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>e+=n),process.stdin.on("end",()=>t(e)),process.stdin.on("error",()=>t(e)),setTimeout(()=>t(e),1500)}catch{t(e)}})}function H(t){if(!t||!F(t))return"";try{let e=m(t,"utf8").trim().split(`
|
|
15
|
+
`).filter(Boolean);for(let n=e.length-1;n>=0;n--){let o=JSON.parse(e[n]),s=o.message??o;if((s.role??o.type)==="assistant"){let r=s.content,i=Array.isArray(r)?r.map(c=>c.text??"").join(" "):typeof r=="string"?r:"";if(i.trim())return i.trim().slice(0,300)}}}catch{}return""}function z(t,e,n){if(!(!l(e??"")||S==="mock"||!p||!u||!d))try{let o=process.argv[1];if(!o)return;let s=Buffer.from(n,"utf8").toString("base64");b(process.execPath,[o,"notify-bg",t,e??"",s],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function V(t,e,n){if(!l(e??"")||S==="mock"||!p||!u||!d)return;let o={};try{o=JSON.parse(n)}catch{}let s=B(process.cwd()),a=t==="attention",r=a?o.message||"Claude needs your input":H(o.transcript_path)||"Session finished",i=`[${s}] ${r}`.slice(0,500),c=e||process.env.SUPERCLAWD_SESSION_ID||"",O={type:a?"attention_needed":"completion",summary:i,sms_summary:i.slice(0,110),x_session_request_id:c},w=()=>_(`${y}/api/prompt/notify-checkpoint`,4e3,{method:"POST",headers:{...C(),"x-session-request-id":c},body:JSON.stringify(O)});try{let h=await w();h.status===404&&c&&(await _(`${y}/api/prompt/inspector`,4e3,{method:"POST",headers:{...C(),"x-session-request-id":c},body:JSON.stringify({ide:!0,platform:"claude-code",llm_model:"claude",x_session_request_id:c,notify_on_checkpoint:!0,enable_session_files:!1})}).catch(()=>{}),h=await w())}catch{}}async function _(t,e,n){let o=new AbortController,s=setTimeout(()=>o.abort(),e);try{return await fetch(t,{...n,signal:o.signal})}finally{clearTimeout(s)}}function A(t,e,n){try{b(t,e,{detached:!0,stdio:"ignore",env:n??process.env}).unref()}catch{}}function E(t,e,n){if(process.platform==="darwin"){let o=n?`display notification m with title ${v(t)} subtitle ${v(n)} sound name "Glass"`:`display notification m with title ${v(t)} sound name "Glass"`;A("osascript",["-e","on run {m}","-e",o,"-e","end run",e]);return}process.platform!=="win32"&&A("notify-send",[t,e])}function v(t){return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function X(t,e,n){if(l(n??"")){if(t==="attention"){let o="";try{o=JSON.parse(e).message??""}catch{}if(o.includes("waiting for your input"))return;E("Claude Code",o||"Claude needs you","Needs you");return}E("Claude Code","Done \u2014 your turn.")}}function Q(t,e){let n=Number(process.env.SUPERCLAWD_REMIND_EVERY??8);if(!Number.isFinite(n)||n<=0||!t||!e)return;let o=0;try{o=parseInt(m(e,"utf8").trim(),10)||0}catch{}o+=1;try{$(e,String(o))}catch{}if(o%n!==0)return;let s="";try{s=m(t,"utf8")}catch{return}s&&process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:s}}))}async function Z(){let t=process.argv[2];if(t==="gate")return await g(),G();if(t==="notify"){let e=process.argv[3],n=process.argv[4],o=await g();z(e,n,o);return}if(t==="notify-bg"){let e=process.argv[3],n=process.argv[4]||void 0,o=Buffer.from(process.argv[5]||"","base64").toString("utf8");return V(e,n,o)}if(t==="notify-local"){let e=process.argv[3],n=process.argv[4]||void 0,o=await g();X(e,o,n);return}if(t==="remind"){Q(process.argv[3],process.argv[4]);return}return await g(),q(process.argv[3],process.argv[4]||"SessionStart")}var ee=new Set(["gate","notify","notify-bg","notify-local","remind"]);Z().catch(()=>{let t=process.argv[2];ee.has(t)||process.stdout.write(k(process.argv[4]||"SessionStart",""))});
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
|
|
3
|
-
import{spawn as
|
|
4
|
-
`,{mode:384});try{
|
|
5
|
-
`)}catch{}}function ke(e,t){
|
|
3
|
+
import{spawn as at,spawnSync as fo}from"node:child_process";import{fileURLToPath as it}from"node:url";import{existsSync as ct}from"node:fs";import{homedir as ft}from"node:os";import{join as G}from"node:path";import{randomBytes as mt}from"node:crypto";import{readFileSync as gt,writeFileSync as de,mkdirSync as pe,chmodSync as ht,existsSync as fe}from"node:fs";var Q=(process.env.SUPERCLAWD_BACKEND||"real").toLowerCase(),g=Q==="mock",A=process.env.SUPERCLAWD_MCP_API_URL||"https://mcp-api.superclawd.com",j=process.env.SUPERCLAWD_API_URL||"https://api.superclawd.com",Z=process.env.SUPERCLAWD_HOME||G(ft(),".superclawd"),K=G(Z,"sessions"),F=G(Z,"config.json");function wt(e){if(!e||typeof e!="object")return{};let t=e,o=t.credentials??{...typeof t.keyId=="string"?{keyId:t.keyId}:{},...typeof t.secret=="string"?{secret:t.secret}:{},...typeof t.workspace=="string"?{workspace:t.workspace}:{}},n=t.preferences??{...typeof t.skipPermissions=="boolean"?{skipPermissions:t.skipPermissions}:{},...typeof t.notifications=="boolean"?{notifications:t.notifications}:{},...typeof t.chooseWorkspaceAtStartup=="boolean"?{chooseWorkspaceAtStartup:t.chooseWorkspaceAtStartup}:{}},r={};return Object.keys(o).length&&(r.credentials=o),Object.keys(n).length&&(r.preferences=n),typeof t.machineId=="string"&&(r.machineId=t.machineId),r}function me(){let e=x()??{};if(e.machineId)return e.machineId;let t=mt(16).toString("hex");return P({...e,machineId:t}),t}function x(){try{return wt(JSON.parse(gt(F,"utf8")))}catch{return null}}function P(e){pe(Z,{recursive:!0}),de(F,`${JSON.stringify(e,null,2)}
|
|
4
|
+
`,{mode:384});try{ht(F,384)}catch{}}function ge(){return x()?.preferences?.skipPermissions===!0}function kt(){return x()?.preferences?.notifications===!0}function he(){return x()?.preferences?.chooseWorkspaceAtStartup===!0}function we(e){return G(e,"config.json")}function yt(e,t){try{pe(e,{recursive:!0}),de(we(e),`${JSON.stringify(t,null,2)}
|
|
5
|
+
`)}catch{}}function ke(e,t){fe(we(e))||yt(e,{notifications:kt(),...t?{workspace:t}:{}})}function ye(){fe(F)||P({credentials:{keyId:"",secret:"",workspace:""},preferences:{notifications:!1,skipPermissions:!1,chooseWorkspaceAtStartup:!1}})}var Se=1e3*60*60*24*3;function Ce(){if(g)return{ok:!0,session:{keyId:process.env.MCP_KEY_ID||"mock-key",secret:process.env.MCP_SECRET||"mock-secret",workspace:process.env.MCP_WORKSPACE||"mock-workspace",apiUrl:A}};let e=x()?.credentials??{},t=process.env.MCP_KEY_ID||e.keyId,o=process.env.MCP_SECRET||e.secret,n=process.env.MCP_WORKSPACE||e.workspace;return!t||!o||!n?{ok:!1,error:"Not authenticated. Run `superclawd login` to get started."}:{ok:!0,session:{keyId:t,secret:o,workspace:n,apiUrl:A}}}import{randomUUID as $e}from"node:crypto";function _e(e){return{"content-type":"application/json","x-mcp-key-id":e.keyId,"x-mcp-secret":e.secret,"x-workspace-slug":e.workspace,"x-request-id":$e()}}async function B(e,t){let o=await fetch(`${e.apiUrl}${t}`,{headers:_e(e)}),n=await o.json().catch(()=>null);return{status:o.status,ok:o.ok,body:n}}async function H(e,t,o){try{let n=await fetch(`${e}/api/prompt/workspaces`,{headers:{"content-type":"application/json","x-mcp-key-id":t,"x-mcp-secret":o,"x-request-id":$e()}}),r=await n.json().catch(()=>null);return{ok:n.ok,status:n.status,workspaces:r?.workspaces??[]}}catch{return{ok:!1,status:0,workspaces:[]}}}async function ve(e,t,o,n={}){let r=await fetch(`${e.apiUrl}${t}`,{method:"POST",headers:{..._e(e),...n},body:JSON.stringify(o)}),s=await r.json().catch(()=>null);return{status:r.status,ok:r.ok,body:s}}async function xe(e,t){e.message("Loading your workspaces\u2026");let o=await H(A,t.keyId,t.secret);if(!o.ok||o.workspaces.length===0)return{};let n=await e.selectWorkspace(o.workspaces,t.workspace);return n===null?{cancelled:!0}:{workspace:n}}async function be(e){if(g)return{ok:!0};try{let t=await B(e,"/api/prompt/catalog");return t.ok?{ok:!0}:t.status===401?{ok:!1,error:"Your credentials are invalid or expired. Run `superclawd login` again."}:t.status===404?{ok:!1,error:"Workspace not found. Run `superclawd switch` to pick one."}:t.status===403?{ok:!1,error:"You are not a member of this workspace."}:t.status===502||t.status===503||t.status===504?{ok:!1,error:`SuperClawd backend is unreachable or starting up (HTTP ${t.status}). Try again in a moment.`}:{ok:!1,error:`Auth check failed (HTTP ${t.status}).`}}catch(t){return{ok:!1,error:`Cannot reach SuperClawd backend (${String(t)}).`}}}var ee=[{id:"skill-backend-001",name:"backend-api-conventions",action:"code",executionMode:"auto",description:"writing, creating, modifying, or reviewing backend API code \u2014 HTTP endpoints, routes, controllers, request handlers, or server-side validation and security",categories:[{name:"endpoint-design",instructions:["Name routes with plural nouns and kebab-case (e.g. /user-profiles).","Return RFC-7807 problem+json on errors, never bare strings.","Validate and sanitize every request body against a schema before use."]},{name:"security",instructions:["Use parameterized queries only; never string-concatenate SQL.","Rate-limit auth endpoints to 5 requests/minute per IP."]}]},{id:"skill-testing-001",name:"testing-standards",action:"test",executionMode:"auto",description:"writing or updating automated tests \u2014 unit tests, integration tests, test files, assertions, mocks, or test coverage",categories:[{name:"unit",instructions:["One behavioral assertion per test; name tests as should_<expectation>.","Mock only at process boundaries (network, fs, clock)."]}]},{id:"skill-always-001",name:"repo-foundations",action:"behave",executionMode:"always",description:"foundational rules that always apply in this repository",categories:[{name:"house-rules",instructions:["Every source file must start with a one-line header comment describing its purpose.","Prefer clarity over cleverness; match the surrounding code's style."]}]}];var Me=[{id:"agent-reviewer-001",name:"code-reviewer",description:"Reviews a diff for correctness and security issues. Use after writing code.",vendor:"anthropic",model:"claude-sonnet-4-6",temperature:.2,prompt:"You are a meticulous senior code reviewer. Examine the change for correctness, security, and clarity. Report concrete findings with file:line; do not rewrite the code unless asked.",mode:"subagent",tools:{read:"allow",glob:"allow",grep:"allow",edit:"deny",write:"deny",bash:"deny",webfetch:"deny",task:"deny"},steps:null,inheritWorkspaceContext:!1},{id:"agent-orchestrator-001",name:"orchestrator",description:"Coordinates multi-step coding tasks and delegates focused work. Use when a task spans several files or steps.",vendor:"anthropic",model:"claude-sonnet-4-6",temperature:.3,prompt:"You are an orchestrator. Break the request into concrete steps, perform the edits directly, and keep changes minimal and focused on what was asked.",mode:"subagent",tools:{read:"allow",glob:"allow",grep:"allow",edit:"allow",write:"allow",bash:"deny",webfetch:"deny",task:"allow"},steps:null,inheritWorkspaceContext:!0}],Re=[{name:"ship-checklist",description:"Run this team's pre-merge checklist.",arguments:[{name:"scope",description:"what is being shipped",required:!1}],content:`Pre-merge checklist for $ARGUMENTS:
|
|
6
6
|
1. Tests pass and cover new behavior.
|
|
7
7
|
2. No secrets or debug logging left in.
|
|
8
8
|
3. Public APIs documented.
|
|
@@ -15,8 +15,8 @@ E2001 upstream_unavailable`}];var Ee=[{id:"workflow-deploy-001",name:"production
|
|
|
15
15
|
3. Tag the release.
|
|
16
16
|
4. Run db migrations.
|
|
17
17
|
5. Deploy and watch error rate for 10m.
|
|
18
|
-
6. Announce in #releases.`}];function
|
|
19
|
-
`);return{skills:e,agents:
|
|
18
|
+
6. Announce in #releases.`}];function St(){let e=ee.filter(o=>o.executionMode==="auto").map(o=>({id:o.id,name:o.name,action:o.action,executionMode:o.executionMode,description:o.description})),t=ee.filter(o=>o.executionMode==="always").flatMap(o=>o.categories.flatMap(n=>n.instructions)).map((o,n)=>`${n+1}. ${o}`).join(`
|
|
19
|
+
`);return{skills:e,agents:Me,commands:Re.map(({name:o,description:n,arguments:r})=>({name:o,description:n,arguments:r})),resources:Pe.map(({name:o,description:n})=>({name:o,description:n})),workflows:Ee.map(({id:o,name:n,description:r})=>({id:o,name:n,description:r})),foundational:{text:t}}}async function Ae(e){if(g)return St();let t=await B(e,"/api/prompt/catalog");if(!t.ok||!t.body)throw new Error(`Failed to fetch catalog (HTTP ${t.status}).`);return{skills:(t.body.skills??[]).filter(n=>n.executionMode==="auto"),agents:t.body.agents??[],commands:t.body.commands??[],resources:t.body.resources??[],workflows:t.body.workflows??[],foundational:{text:t.body.foundational?.text??""}}}async function Ie(e,t){if(g)return!0;try{return(await ve(e,"/api/prompt/inspector",{ide:!0,platform:"claude-code",llm_model:"claude",x_session_request_id:t,notify_on_checkpoint:!0,enable_session_files:!1},{"x-session-request-id":t})).ok}catch{return!1}}import{mkdirSync as Nt,writeFileSync as Ft,chmodSync as Gt}from"node:fs";import{dirname as Ge,join as je}from"node:path";function _(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)||"skill"}function Ct(e){return`${(e.description??e.name).trim().replace(/\.$/,"")}. SuperClawd-managed "${e.name}" guidance for ${e.action} tasks.`}function $t(e){return`# ${e.name} (SuperClawd-managed)
|
|
20
20
|
|
|
21
21
|
The authoritative instructions for this skill are managed in SuperClawd and
|
|
22
22
|
are **not** included here. You must fetch them before acting.
|
|
@@ -30,13 +30,13 @@ are **not** included here. You must fetch them before acting.
|
|
|
30
30
|
|
|
31
31
|
Do not proceed using only this description \u2014 it is a pointer, not the rules.
|
|
32
32
|
If \`get_directives\` returns an error, tell the user and stop.
|
|
33
|
-
`}function
|
|
34
|
-
name: ${
|
|
33
|
+
`}function _t(e){let t=Ct(e).replace(/"/g,'\\"');return`---
|
|
34
|
+
name: ${_(e.name)}
|
|
35
35
|
description: "${t}"
|
|
36
36
|
user-invocable: false
|
|
37
37
|
---
|
|
38
38
|
|
|
39
|
-
`}function
|
|
39
|
+
`}function Oe(e){let t=new Set,o=[];for(let n of e){let r=_(n.name),s=2;for(;t.has(r);)r=`${_(n.name)}-${s++}`;t.add(r),o.push({relPath:`skills/${r}/SKILL.md`,content:_t(n)+$t(n)})}return o}var vt=`SUPERCLAWD \u2014 operating manual (always in effect):
|
|
40
40
|
- The ALWAYS rules below are ALREADY LOADED and active for this entire session.
|
|
41
41
|
Apply them directly to all work. Do NOT call any tool to fetch them \u2014 you
|
|
42
42
|
already have them in full.
|
|
@@ -45,24 +45,24 @@ user-invocable: false
|
|
|
45
45
|
the \`get_directives\` tool with that file's skillId (a UUID) BEFORE acting,
|
|
46
46
|
and apply what it returns. Those skill files are pointers, not the rules.
|
|
47
47
|
- Only call \`get_directives\` with a UUID skillId taken from an activated skill
|
|
48
|
-
file. Never call it for the ALWAYS rules, and never pass a skill name.`;function te(e){let t=
|
|
48
|
+
file. Never call it for the ALWAYS rules, and never pass a skill name.`;function te(e){let t=vt,o=(e||"").trim();return o&&(t+=`
|
|
49
49
|
|
|
50
50
|
ALWAYS \u2014 foundational rules (already loaded & active for this whole session; apply directly, never fetch):
|
|
51
|
-
${o}`),t}function
|
|
51
|
+
${o}`),t}function xt(e){return e.inheritWorkspaceContext!==!1}function bt(e){return te(e).trim()}function Te(e,t){if(!xt(e))return e.prompt;let o=bt(t);return o?`${o}
|
|
52
52
|
|
|
53
53
|
---
|
|
54
54
|
|
|
55
|
-
${e.prompt}`:e.prompt}var
|
|
55
|
+
${e.prompt}`:e.prompt}var Le={read:"Read",glob:"Glob",grep:"Grep",edit:"Edit",write:"Write",bash:"Bash",webfetch:"WebFetch",task:"Task"};function Mt(e){return e==="allow"||e==="ask"||e===!0}function Rt(e){let t=e.tools??{};return Object.keys(Le).filter(o=>Mt(t[o])).map(o=>Le[o])}function Pt(e){let t=[`name: ${_(e.name)}`,`description: "${(e.description??e.name).replace(/"/g,'\\"')}"`];e.vendor==="anthropic"&&e.model&&e.model!=="default"&&t.push(`model: ${JSON.stringify(e.model)}`);let o=Rt(e);return o.length&&t.push(`tools: ${o.join(", ")}`),`---
|
|
56
56
|
${t.join(`
|
|
57
57
|
`)}
|
|
58
58
|
---
|
|
59
59
|
|
|
60
|
-
`}function De(e,t={}){let o=t.foundationalText??"",n=new Set,r=[];for(let s of e){let
|
|
60
|
+
`}function De(e,t={}){let o=t.foundationalText??"",n=new Set,r=[];for(let s of e){let a=_(s.name),d=2;for(;n.has(a);)a=`${_(s.name)}-${d++}`;n.add(a),r.push({relPath:`agents/${a}.md`,content:Pt(s)+Te(s,o)})}return r}function Et(e){return e.arguments.length?e.arguments.map(t=>t.required?`<${t.name}>`:`[${t.name}]`).join(" "):""}function At(e){let t=[`description: "${e.description.replace(/"/g,'\\"')}"`],o=Et(e);return o&&t.push(`argument-hint: ${o}`),`---
|
|
61
61
|
${t.join(`
|
|
62
62
|
`)}
|
|
63
63
|
---
|
|
64
64
|
|
|
65
|
-
`}function
|
|
65
|
+
`}function It(e){return`This is the SuperClawd command **${e.name}**. Its content is managed in
|
|
66
66
|
SuperClawd and fetched on use.
|
|
67
67
|
|
|
68
68
|
**REQUIRED \u2014 do this now:**
|
|
@@ -71,7 +71,7 @@ SuperClawd and fetched on use.
|
|
|
71
71
|
2. Execute the returned command content, substituting these arguments: $ARGUMENTS
|
|
72
72
|
|
|
73
73
|
Do not improvise the command from this description.
|
|
74
|
-
`}function
|
|
74
|
+
`}function We(e){let t=new Set,o=[];for(let n of e){let r=_(n.name),s=2;for(;t.has(r);)r=`${_(n.name)}-${s++}`;t.add(r),o.push({relPath:`commands/${r}.md`,content:At(n)+It(n)})}return o}function Ot(e,t){let n=`${(e.description??e.name).trim().replace(/\.$/,"")}. Runs the '${e.name}' SuperClawd workflow.`.replace(/"/g,'\\"'),r=`# ${e.name} (SuperClawd workflow)
|
|
75
75
|
|
|
76
76
|
This is a managed multi-step workflow. Fetch its steps before starting.
|
|
77
77
|
|
|
@@ -87,7 +87,7 @@ description: "${n}"
|
|
|
87
87
|
user-invocable: false
|
|
88
88
|
---
|
|
89
89
|
|
|
90
|
-
${r}`}}function
|
|
90
|
+
${r}`}}function Tt(e,t){let o=`Run the SuperClawd workflow **${e.name}**:
|
|
91
91
|
|
|
92
92
|
1. Call the \`get_workflow\` tool with \`workflowId\`: \`${e.id}\`.
|
|
93
93
|
2. Follow the returned steps in order, using any arguments: $ARGUMENTS
|
|
@@ -95,7 +95,7 @@ ${r}`}}function Ut(e,t){let o=`Run the SuperClawd workflow **${e.name}**:
|
|
|
95
95
|
description: "${n}"
|
|
96
96
|
---
|
|
97
97
|
|
|
98
|
-
${o}`}}function
|
|
98
|
+
${o}`}}function Ue(e){let t=new Set,o=[];for(let n of e){let r=_(n.name),s=2;for(;t.has(r);)r=`${_(n.name)}-${s++}`;t.add(r),o.push(Ot(n,r)),o.push(Tt(n,r))}return o}var Lt=`---
|
|
99
99
|
description: Audit this session against your active SuperClawd directives.
|
|
100
100
|
---
|
|
101
101
|
|
|
@@ -107,7 +107,7 @@ Audit the work done so far in this session against your active SuperClawd direct
|
|
|
107
107
|
4. Flag anything relevant you may have skipped \u2014 and if so, fetch and apply/run it now.
|
|
108
108
|
|
|
109
109
|
Be concise; this is a compliance check, not a code review.
|
|
110
|
-
`,
|
|
110
|
+
`,Dt=`---
|
|
111
111
|
description: Show SuperClawd service status, workspace info, and credit balance.
|
|
112
112
|
---
|
|
113
113
|
|
|
@@ -118,14 +118,14 @@ Give me a concise SuperClawd status overview. Call these tools and summarize the
|
|
|
118
118
|
3. \`check_balance\` \u2014 current credit balance.
|
|
119
119
|
|
|
120
120
|
Present it as a tidy summary; do not take any other action.
|
|
121
|
-
`,
|
|
121
|
+
`,Wt=`---
|
|
122
122
|
description: Toggle SuperClawd notifications for this session.
|
|
123
123
|
---
|
|
124
124
|
|
|
125
125
|
The user wants to flip SuperClawd notifications for this session.
|
|
126
126
|
|
|
127
127
|
Call the \`notifications\` tool (no arguments \u2014 it toggles the current on/off state), then report the resulting state in one short line. Do not take any other action.
|
|
128
|
-
`,
|
|
128
|
+
`,Ut=`---
|
|
129
129
|
description: Apply maximum extended thinking (ultrathink) to the work at hand.
|
|
130
130
|
argument-hint: "[task or question]"
|
|
131
131
|
---
|
|
@@ -133,104 +133,87 @@ argument-hint: "[task or question]"
|
|
|
133
133
|
To perform this work, please ultrathink \u2014 reason as deeply and carefully as you can before acting. Surface edge cases, weigh alternatives, and check your assumptions.
|
|
134
134
|
|
|
135
135
|
$ARGUMENTS
|
|
136
|
-
`;function
|
|
137
|
-
${
|
|
138
|
-
|
|
139
|
-
`)&&r.output.write(i):r.output.write(i)}),n.on("SIGINT",()=>{n.close(),process.stdout.write(`
|
|
140
|
-
`),o(null)}),n.question(e,i=>{n.close(),t&&process.stdout.write(`
|
|
141
|
-
`),o(i.trim())}),t&&(s=!0)})}function eo(e,t){return new Promise(o=>{let n=process.stdin;if(!n.isTTY){o(e[0]?.slug??null);return}let r=t?e.findIndex(u=>u.slug===t):-1,s=Math.max(0,r>=0?r:e.findIndex(u=>u.role==="owner")),i=u=>{u||process.stdout.write(`${$}[${e.length}A`);for(let a=0;a<e.length;a++){let l=e[a],E=a===s?`${$}[38;5;208m\u276F `:" ";process.stdout.write(`${$}[2K${E}${l.name} ${$}[2m${l.slug} \xB7 ${l.role}${$}[0m
|
|
136
|
+
`;function Ne(){return[{relPath:"commands/audit-work.md",content:Lt},{relPath:"commands/status.md",content:Dt},{relPath:"commands/notifications.md",content:Wt},{relPath:"commands/ultrathink.md",content:Ut}]}function Fe(e){let t="hooks/foundational-fallback.txt",o=`${e.pluginDir}/${t}`,n=`${e.pluginDir}/hooks/reminder-context.txt`,r=`${e.pluginDir}/stepcount`,s=c=>({type:"command",command:`node "${e.helperPath}" ${c}`}),a=c=>({...s(c),async:!0}),d={SessionStart:[{hooks:[s(`foundational "${o}" SessionStart`)]}],Notification:[{matcher:"permission_prompt|elicitation_dialog|elicitation_complete|elicitation_response|auth_success",hooks:[a(`notify-local attention "${e.launchId}"`),a(`notify attention "${e.launchId}"`)]}],Stop:[{hooks:[a(`notify-local stop "${e.launchId}"`)]}],SessionEnd:[{hooks:[a(`notify completion "${e.launchId}"`)]}]},m=[{relPath:t,content:e.foundational.text??""}],u=Number(process.env.SUPERCLAWD_REMIND_EVERY??8),i=(e.foundational.text??"").trim();return u>0&&i&&(d.PostToolUse=[{matcher:"*",hooks:[s(`remind "${n}" "${r}"`)]}],m.push({relPath:"hooks/reminder-context.txt",content:`REMINDER \u2014 these SuperClawd always-rules remain in effect:
|
|
137
|
+
${i}`})),e.gate&&(d.PreToolUse=[{matcher:"mcp__plugin_superclawd_superclawd__.*",hooks:[s("gate")]}]),m.push({relPath:"hooks/hooks.json",content:JSON.stringify({hooks:d},null,2)}),m}function jt(e,t,o,n){let r={SUPERCLAWD_BACKEND:Q,SUPERCLAWD_MCP_API_URL:A,SUPERCLAWD_SESSION_ID:o};return g||(r.MCP_KEY_ID=e.keyId,r.MCP_SECRET=e.secret,r.MCP_WORKSPACE=e.workspace),process.env.NODE_EXTRA_CA_CERTS&&(r.NODE_EXTRA_CA_CERTS=process.env.NODE_EXTRA_CA_CERTS),process.env.SUPERCLAWD_HOME&&(r.SUPERCLAWD_HOME=process.env.SUPERCLAWD_HOME),process.env.SUPERCLAWD_LOG_FILE&&(r.SUPERCLAWD_LOG_FILE=process.env.SUPERCLAWD_LOG_FILE),process.env.SUPERCLAWD_DEBUG&&(r.SUPERCLAWD_DEBUG=process.env.SUPERCLAWD_DEBUG),process.env.SUPERCLAWD_MOCK_TIER&&(r.SUPERCLAWD_MOCK_TIER=process.env.SUPERCLAWD_MOCK_TIER),process.env.SUPERCLAWD_MOCK_BALANCE&&(r.SUPERCLAWD_MOCK_BALANCE=process.env.SUPERCLAWD_MOCK_BALANCE),n.length&&(r.SUPERCLAWD_RESOURCES=JSON.stringify(n.map(a=>({name:a.name,description:a.description})))),{relPath:".claude-plugin/plugin.json",content:JSON.stringify({name:"superclawd",description:"SuperClawd skills + live, metered directives for Claude Code.",mcpServers:{superclawd:{command:"node",args:[t],env:r}}},null,2)}}function Ke(e){let{pluginDir:t,session:o,catalog:n,serverPath:r,launchId:s}=e,a=je(Ge(r),"hook-helper.mjs"),d=process.env.SUPERCLAWD_GATE==="1",m=[jt(o,r,s,n.resources),...Oe(n.skills),...De(n.agents,{foundationalText:n.foundational.text}),...We(n.commands),...Ue(n.workflows),...Ne(),...Fe({foundational:n.foundational,helperPath:a,pluginDir:t,launchId:s,gate:d})],u=[];for(let i of m){let c=je(t,i.relPath);Nt(Ge(c),{recursive:!0}),Ft(c,i.content),i.executable&&Gt(c,493),u.push(i.relPath)}return{pluginDir:t,skillCount:n.skills.length,agentCount:n.agents.length,commandCount:n.commands.length,workflowCount:n.workflows.length,files:u}}import{mkdirSync as Kt,rmSync as Be,readdirSync as Bt,statSync as Ht}from"node:fs";import{join as oe}from"node:path";import{randomBytes as Yt}from"node:crypto";function He(){let e=`${Date.now().toString(36)}-${Yt(4).toString("hex")}`,t=oe(K,e),o=oe(t,"plugin");return Kt(o,{recursive:!0}),{id:e,dir:t,pluginDir:o}}function Ye(e){try{Be(e.dir,{recursive:!0,force:!0})}catch{}}function qe(e=Date.now()){let t=0,o=[];try{o=Bt(K)}catch{return 0}for(let n of o){let r=oe(K,n);try{e-Ht(r).mtimeMs>Se&&(Be(r,{recursive:!0,force:!0}),t++)}catch{}}return t}import{createInterface as qt}from"node:readline";var M="\x1B";function Jt(e){return new Promise(t=>{let o=qt({input:process.stdin,output:process.stdout});o.on("SIGINT",()=>{o.close(),process.stdout.write(`
|
|
138
|
+
`),t(null)}),o.question(e,n=>{o.close(),t(n.trim())})})}function zt(e,t){return new Promise(o=>{let n=process.stdin;if(!n.isTTY){o(e[0]?.slug??null);return}let r=t?e.findIndex(u=>u.slug===t):-1,s=Math.max(0,r>=0?r:e.findIndex(u=>u.role==="owner")),a=u=>{u||process.stdout.write(`${M}[${e.length}A`);for(let i=0;i<e.length;i++){let c=e[i],I=i===s?`${M}[38;5;208m\u276F `:" ";process.stdout.write(`${M}[2K${I}${c.name} ${M}[2m${c.slug} \xB7 ${c.role}${M}[0m
|
|
142
139
|
`)}};process.stdout.write(`Select your default workspace (\u2191/\u2193 \xB7 Enter \xB7 Esc cancels):
|
|
143
|
-
${
|
|
144
|
-
`),o(null)):
|
|
145
|
-
`?(d(),o(e[s].slug)):
|
|
146
|
-
`),{workspace:
|
|
147
|
-
`);let r=await
|
|
148
|
-
`),{ok:!0};let
|
|
149
|
-
Welcome to SuperClawd. Let's connect your workspace.
|
|
150
|
-
`),process.stdout.write(`Grab your MCP credentials from https://app.superclawd.com (Settings \u2192 MCP Keys).
|
|
151
|
-
`),process.stdout.write(`${$}[2mPress Ctrl-C anytime to cancel.${$}[0m
|
|
152
|
-
|
|
153
|
-
`)):(process.stdout.write(`
|
|
154
|
-
Configure SuperClawd credentials (press Enter to keep an existing value).
|
|
155
|
-
`),process.stdout.write(`${$}[2mPress Ctrl-C anytime to cancel.${$}[0m
|
|
156
|
-
|
|
157
|
-
`));let r=await ne(`MCP Key ID${o.keyId?` [${Je(o.keyId)}]`:""}: `);if(r===null)return{ok:!0,cancelled:!0};let s=r||o.keyId||"",i=await ne(`MCP Secret${o.secret?" [keep current]":""}: `,!0);if(i===null)return{ok:!0,cancelled:!0};let d=i||o.secret||"";if(!s||!d)return{ok:!1,error:"MCP Key ID and Secret are required."};let p=await Ve(s,d,o.workspace??"");if(p.cancelled)return{ok:!0,cancelled:!0};if(p.error)return{ok:!1,error:p.error};let u=p.workspace??"";if(!u)return{ok:!1,error:"A workspace is required."};process.stdout.write(`
|
|
158
|
-
Validating credentials\u2026
|
|
159
|
-
`);let a={keyId:s,secret:d,workspace:u,apiUrl:P},l=Date.now(),E=await U(a),D=Date.now()-l;return D<qe&&await Zt(qe-D),E.ok?(I({...t,credentials:{keyId:s,secret:d,workspace:u}}),process.stdout.write(`\u2713 Connected to workspace "${u}".
|
|
160
|
-
|
|
161
|
-
`),{ok:!0}):{ok:!1,error:E.error??"Validation failed."}}async function Qe(){if(g)return process.stdout.write(`Mock mode \u2014 workspace switching is not used.
|
|
162
|
-
`),{ok:!0};let e=x()??{},t=e.credentials??{};if(!t.keyId||!t.secret)return{ok:!1,error:"No credentials yet. Run `superclawd configure` first."};let o=await Ve(t.keyId,t.secret,t.workspace??"");if(o.cancelled)return{ok:!0,cancelled:!0};if(o.error)return{ok:!1,error:o.error};let n=o.workspace??"";return n?n===t.workspace?(process.stdout.write(`
|
|
140
|
+
${M}[?25l`),a(!0),n.setRawMode(!0),n.resume();let d=()=>{n.off("data",m);try{n.setRawMode(!1)}catch{}n.pause(),process.stdout.write(`${M}[?25h`)},m=u=>{let i=u.toString();i===""||i===M?(d(),process.stdout.write(`
|
|
141
|
+
`),o(null)):i==="\r"||i===`
|
|
142
|
+
`?(d(),o(e[s].slug)):i===`${M}[A`||i==="k"?(s=(s-1+e.length)%e.length,a(!1)):(i===`${M}[B`||i==="j")&&(s=(s+1)%e.length,a(!1))};n.on("data",m)})}async function ne(e,t,o){let n=await H(A,e,t);if(n.status===401)return{error:"Your credentials are invalid or expired."};if(n.ok&&n.workspaces.length>0){if(n.workspaces.length===1){let a=n.workspaces[0];return process.stdout.write(`Using workspace "${a.slug}" (your only workspace).
|
|
143
|
+
`),{workspace:a.slug}}let s=await zt(n.workspaces,o);return s?{workspace:s}:{cancelled:!0}}n.ok&&process.stdout.write(`No workspaces found for this account \u2014 enter a slug manually.
|
|
144
|
+
`);let r=await Jt(`Workspace slug${o?` [${o}]`:""}: `);return r===null?{cancelled:!0}:{workspace:r||o||""}}async function Je(){if(g)return process.stdout.write(`Mock mode \u2014 workspace switching is not used.
|
|
145
|
+
`),{ok:!0};let e=x()??{},t=e.credentials??{};if(!t.keyId||!t.secret)return{ok:!1,error:"No credentials yet. Run `superclawd login` first."};let o=await ne(t.keyId,t.secret,t.workspace??"");if(o.cancelled)return{ok:!0,cancelled:!0};if(o.error)return{ok:!1,error:o.error};let n=o.workspace??"";return n?n===t.workspace?(process.stdout.write(`
|
|
163
146
|
Default workspace is already "${n}".
|
|
164
147
|
|
|
165
|
-
`),{ok:!0}):(
|
|
148
|
+
`),{ok:!0}):(P({...e,credentials:{...t,workspace:n}}),process.stdout.write(`
|
|
166
149
|
\u2713 Default workspace set to "${n}".
|
|
167
150
|
|
|
168
|
-
`),{ok:!0}):{ok:!1,error:"A workspace is required."}}function
|
|
169
|
-
`);
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
`)
|
|
176
|
-
`);
|
|
177
|
-
|
|
151
|
+
`),{ok:!0}):{ok:!1,error:"A workspace is required."}}import{hostname as Vt}from"node:os";import{spawn as Xt}from"node:child_process";var Qt=e=>new Promise(t=>setTimeout(t,e));function Zt(e){try{let t=process.platform,r=Xt(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}async function ze(){if(g)return process.stdout.write(`Mock mode \u2014 login is not needed.
|
|
152
|
+
`),{ok:!0};let e=me(),t=Vt()||"Unknown device",o;try{let c=await fetch(`${j}/api/auth/cli/device/start`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({machineId:e,hostname:t})});if(!c.ok)return{ok:!1,error:`Couldn't start login (HTTP ${c.status}).`};o=await c.json()}catch{return{ok:!1,error:`Couldn't reach ${j}.`}}let n=o.verification_uri_complete||o.verification_uri;process.stdout.write(`
|
|
153
|
+
To authorize this machine, open:
|
|
154
|
+
${n}
|
|
155
|
+
|
|
156
|
+
and confirm this code matches: ${o.user_code}
|
|
157
|
+
|
|
158
|
+
`),Zt(n),process.stdout.write(`Waiting for approval\u2026 (Ctrl-C to cancel)
|
|
159
|
+
`);let r=(o.interval||5)*1e3,s=Date.now()+(o.expires_in||600)*1e3,a,d;for(;Date.now()<s;){await Qt(r);let c;try{c=await(await fetch(`${j}/api/auth/cli/device/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({deviceCode:o.device_code})})).json()}catch{continue}if(c.status==="approved"){a=c.key_id,d=c.secret;break}if(c.status==="denied")return{ok:!1,error:"Request was denied in the browser."};if(c.status==="expired")return{ok:!1,error:"Login request expired. Run `superclawd login` again."}}if(!a||!d)return{ok:!1,error:"Login timed out. Run `superclawd login` again."};process.stdout.write(`\u2713 Authorized.
|
|
160
|
+
|
|
161
|
+
`);let m=x()??{},u=await ne(a,d,m.credentials?.workspace??"");if(u.error)return{ok:!1,error:u.error};if(u.cancelled)return P({...m,credentials:{...m.credentials,keyId:a,secret:d}}),process.stdout.write("Saved your credential. Run `superclawd switch` to choose a workspace.\n\n"),{ok:!0,cancelled:!0};let i=u.workspace??"";return P({...m,credentials:{keyId:a,secret:d,workspace:i}}),process.stdout.write(`\u2713 Connected to workspace "${i}".
|
|
162
|
+
|
|
163
|
+
`),{ok:!0}}var h="\x1B",Y=[{key:"notifications",label:"Notifications",description:"Default for new sessions \u2014 ping when Claude needs you or finishes",defaultOn:!1},{key:"skipPermissions",label:"Dangerously skip permissions",description:"Launch Claude Code with --dangerously-skip-permissions (no approval prompts)",defaultOn:!1},{key:"chooseWorkspaceAtStartup",label:"Choose workspace at startup",description:"Pick the workspace to boot into each time you run superclawd",defaultOn:!1}].sort((e,t)=>e.label.localeCompare(t.label)),re=(e,t)=>e.preferences?.[t.key]??t.defaultOn;async function Ve(){let e=x()??{},t=process.stdin;if(!t.isTTY){process.stdout.write(`SuperClawd options:
|
|
164
|
+
`);for(let o of Y)process.stdout.write(` ${re(e,o)?"on ":"off"} ${o.label}
|
|
165
|
+
`);return}await new Promise(o=>{let n=Y.length,r=n+2,s=0,a=u=>{u||process.stdout.write(`${h}[${r}A`);for(let i=0;i<n;i++){let c=Y[i],I=i===s?`${h}[38;5;208m\u276F `:" ",z=re(e,c)?`${h}[38;5;208m[\u2713]${h}[0m`:"[ ]";process.stdout.write(`${h}[2K${I}${z} ${c.label}${h}[0m ${h}[2m${c.description}${h}[0m
|
|
178
166
|
`)}process.stdout.write(`${h}[2K
|
|
179
167
|
`),process.stdout.write(`${h}[2K${h}[2mPress Esc (or Ctrl-C) to exit${h}[0m
|
|
180
168
|
`)};process.stdout.write(`
|
|
181
169
|
SuperClawd options ${h}[2m(\u2191/\u2193 move \xB7 Space/Enter to toggle)${h}[0m
|
|
182
|
-
${h}[?25l`),
|
|
183
|
-
`)},
|
|
184
|
-
`||
|
|
185
|
-
`)}function
|
|
170
|
+
${h}[?25l`),a(!0),t.setRawMode(!0),t.resume();let d=()=>{t.off("data",m);try{t.setRawMode(!1)}catch{}t.pause(),process.stdout.write(`${h}[?25h
|
|
171
|
+
`)},m=u=>{let i=u.toString();if(i===""||i===h)d(),o();else if(i==="\r"||i===`
|
|
172
|
+
`||i===" "){let c=Y[s];e.preferences={...e.preferences,[c.key]:!re(e,c)},P(e),a(!1)}else i===`${h}[A`||i==="k"?(s=(s-1+n)%n,a(!1)):(i===`${h}[B`||i==="j")&&(s=(s+1)%n,a(!1))};t.on("data",m)})}import{execSync as tt}from"node:child_process";var f="\x1B",E=`${f}[38;5;208m`,T=`${f}[2m`,ae=`${f}[31m`,w=`${f}[0m`,eo=`${f}[?1049h`,Xe=`${f}[?1049l`,to=`${f}[?25l`,se=`${f}[?25h`,oo=`${f}[?1007l`,Qe=`${f}[?1007h`,no=`${f}[?1000l${f}[?1002l${f}[?1003l${f}[?1004l${f}[?1006l${f}[?1015l`,ie=`${f}[2J${f}[H`,q=[" _ _"," ____ _ _ __ ___ _ _ __| |__ ___ __ ____| |","(_-< || | '_ \\/ -_) '_/ _| / _` \\ V V / _` |","/__/\\_,_| .__/\\___|_| \\__|_\\__,_|\\_/\\_/\\__,_|"," |_|"],Ze=45,D=36,ro=140,so=350,v=e=>void process.stdout.write(e),io=e=>new Promise(t=>setTimeout(t,e)),O=e=>e>0?" ".repeat(e):"",ot=process.platform!=="win32";function ao(){if(!ot)return null;try{return tt("stty -g </dev/tty",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}function et(e){if(ot)try{tt(`stty ${e} </dev/tty`,{stdio:"ignore"})}catch{}}var J=null;function nt(e){J?.(),J=null,process.stderr.write(`${ae}\u2717 ${e}${w}
|
|
173
|
+
`)}function co(e,t){return v(`${E}${q.join(`
|
|
186
174
|
`)}${w} ${T}v${t}${w}
|
|
187
175
|
|
|
188
|
-
`),{async phase(o,n){
|
|
189
|
-
`)},message(o){
|
|
190
|
-
`)},async selectWorkspace(o,n){return n??o[0]?.slug??null},async ready(o){
|
|
191
|
-
`)},fail(o){
|
|
192
|
-
`)},note(o){
|
|
193
|
-
`)},handoff(){},finish(){}}}function
|
|
194
|
-
`.repeat(
|
|
195
|
-
`;
|
|
196
|
-
`;let
|
|
197
|
-
|
|
198
|
-
`;let X=Math.max(0,Math.floor((k-
|
|
199
|
-
`;let
|
|
200
|
-
`.repeat(
|
|
201
|
-
`;
|
|
202
|
-
`;for(let
|
|
203
|
-
`;let b=`v${t}`;
|
|
204
|
-
`?(process.stdin.off("data",R),process.stdin.on("data",
|
|
205
|
-
`)},note(){},handoff(){s&&(process.stdin.off("data",
|
|
176
|
+
`),{async phase(o,n){v(`${T} \xB7 ${n}${w}
|
|
177
|
+
`)},message(o){v(`${T} \xB7 ${o}${w}
|
|
178
|
+
`)},async selectWorkspace(o,n){return n??o[0]?.slug??null},async ready(o){v(`${E} \u2713 ${o}${w}
|
|
179
|
+
`)},fail(o){v(`${ae} \u2717 ${o}${w}
|
|
180
|
+
`)},note(o){v(` ${o}
|
|
181
|
+
`)},handoff(){},finish(){}}}function lo(e,t){let o=ao(),n=0,r=!0,s=!1,a=l=>{l.includes(3)&&i()},d=()=>{let l=process.stdin;if(l.isTTY){try{l.setRawMode(!0)}catch{}l.resume(),l.on("data",a),s=!0}},m=()=>{if(!s)return;let l=process.stdin;l.off("data",a);try{l.setRawMode(!1)}catch{}l.pause(),s=!1},u=()=>{m();try{process.stdin.isTTY&&process.stdin.setRawMode(!1)}catch{}v(se+Qe+Xe),o&&et(o)},i=()=>{r&&u(),r=!1,process.exit(130)},c=()=>{m(),r&&v(se+Qe+Xe)},I=()=>{process.off("SIGINT",i),process.off("SIGTERM",i),process.off("exit",c),J=null};et("-echo"),v(eo+to+oo+no),d(),process.on("SIGINT",i),process.on("SIGTERM",i),process.on("exit",c),J=u;let z=(l,S)=>{let k=process.stdout.columns||80,$=process.stdout.rows||24,p=Math.floor(l*D/e);p<0&&(p=0),p>D&&(p=D);let R="\u2588".repeat(p)+"\u2591".repeat(D-p),b=Math.floor(l*100/e),C=D+6,W=Math.max(0,Math.floor(($-9)/2)),y=ie+`
|
|
182
|
+
`.repeat(W),L=Math.max(0,Math.floor((k-Ze)/2));for(let pt of q)y+=`${O(L)}${E}${pt}${w}
|
|
183
|
+
`;y+=`
|
|
184
|
+
`;let U=Math.max(0,Math.floor((k-S.length)/2));y+=`${O(U)}${T}${S}${w}
|
|
185
|
+
|
|
186
|
+
`;let X=Math.max(0,Math.floor((k-C)/2));y+=`${O(X)}${E}${R}${w} ${String(b).padStart(3)}%
|
|
187
|
+
`;let N=`v${t}`,ut=Math.max(1,$-1),dt=Math.max(1,k-N.length-1);y+=`${f}[${ut};${dt}H${E}${N}${w}`,v(y)},le=async(l,S,k)=>{let $=k-(Date.now()-n);$>0&&await io($),z(l,S),n=Date.now()},ue=l=>{let S=process.stdout.columns||80,k=process.stdout.rows||24,$=Math.max(0,Math.floor((k-(q.length+1+l.length))/2)),p=ie+`
|
|
188
|
+
`.repeat($),R=Math.max(0,Math.floor((S-Ze)/2));for(let C of q)p+=`${O(R)}${E}${C}${w}
|
|
189
|
+
`;p+=`
|
|
190
|
+
`;for(let C of l)p+=`${C}
|
|
191
|
+
`;let b=`v${t}`;p+=`${f}[${Math.max(1,k-1)};${Math.max(1,S-b.length-1)}H${E}${b}${w}`,v(p)},V=(l,S)=>{let k=process.stdout.columns||80,$="Select your workspace \u2191/\u2193 \xB7 Enter \xB7 Esc cancels",p=Math.max(0,Math.floor((k-$.length)/2)),R=y=>` ${y.name} ${y.slug} \xB7 ${y.role}`,b=Math.max(...l.map(y=>R(y).length)),C=Math.max(0,Math.floor((k-b)/2)),W=[`${O(p)}${T}${$}${w}`,""];for(let y=0;y<l.length;y++){let L=l[y],U=y===S,X=U?`${E}\u276F `:" ",N=U?`${E}${L.name}${w}`:L.name;W.push(`${O(C)}${X}${N} ${T}${L.slug} \xB7 ${L.role}${w}`)}ue(W)};return{phase:(l,S)=>le(l-1,S,ro),ready:l=>le(e,l,so),message(l){let S=process.stdout.columns||80,k=Math.max(0,Math.floor((S-l.length)/2));ue([`${O(k)}${T}${l}${w}`]),n=Date.now()},selectWorkspace(l,S){return new Promise(k=>{let $=S?l.findIndex(b=>b.slug===S):-1,p=$>=0?$:0;s&&process.stdin.off("data",a),V(l,p);let R=b=>{let C=b.toString();C===""||C===f?(process.stdin.off("data",R),k(null)):C==="\r"||C===`
|
|
192
|
+
`?(process.stdin.off("data",R),process.stdin.on("data",a),k(l[p].slug)):C===`${f}[A`||C==="k"?(p=(p-1+l.length)%l.length,V(l,p)):(C===`${f}[B`||C==="j")&&(p=(p+1)%l.length,V(l,p))};process.stdin.on("data",R)})},fail(l){r&&u(),r=!1,I(),process.stderr.write(`${ae}\u2717 ${l}${w}
|
|
193
|
+
`)},note(){},handoff(){s&&(process.stdin.off("data",a),process.stdin.pause(),s=!1),v(ie+se),process.off("SIGINT",i),process.off("SIGTERM",i)},finish(){r&&u(),r=!1,I()}}}function uo(){return process.platform!=="win32"?!0:!!(process.env.WT_SESSION||process.env.TERM_PROGRAM||process.env.TERM)}function rt(e){let t=process.stdout.isTTY===!0,o=e.version??"";return e.plain||!t||!uo()?co(e.total,o):lo(e.total,o)}var st={name:"superclawd",version:"0.1.1",description:"Claude Code, supercharged \u2014 your team's standards, every session. The superclawd CLI loads your workspace's skills, agents, commands, workflows, and live directives into Claude Code as a plugin.",author:"SuperClawd <support@superclawd.com>",license:"SEE LICENSE IN LICENSE",homepage:"https://superclawd.com",repository:{type:"git",url:"https://github.com/superclawd-ai/superclawd"},bugs:{url:"https://github.com/superclawd-ai/superclawd/issues"},keywords:["superclawd","claude-code","claude","plugin","skills","agents","mcp","ai-assistant","coding-standards","model-context-protocol"],engines:{node:">=20"},type:"module",main:"dist/index.js",bin:{superclawd:"dist/index.js"},files:["dist","README.md","LICENSE"],scripts:{build:"node build.mjs",dev:"node build.mjs && tsx src/index.ts",typecheck:"tsc --noEmit",lint:"eslint 'src/**/*.{ts,tsx}'","lint:fix":"eslint 'src/**/*.{ts,tsx}' --fix",format:"prettier --check 'src/**/*.{ts,tsx}'","format:fix":"prettier --write 'src/**/*.{ts,tsx}'",selftest:"tsx test/mcp-selftest.ts",test:"node build.mjs && tsx test/mcp-selftest.ts",prepublishOnly:"npm run build","publish:npm":"npm publish","version:bump":"npm version patch --no-git-tag-version"},dependencies:{"@modelcontextprotocol/sdk":"^1.7.0",zod:"^3.24.2"},devDependencies:{"@eslint/js":"^9.39.1","@types/node":"^22.10.0","@typescript-eslint/eslint-plugin":"^8.44.1","@typescript-eslint/parser":"^8.44.1",esbuild:"^0.24.0",eslint:"^9.36.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4",prettier:"^3.6.2",tsx:"^4.19.0",typescript:"^5.7.0"}};var lt=st.version,ce=process.env.SUPERCLAWD_DRY_RUN==="1"||process.argv.includes("--dry-run");function mo(){if(process.env.SUPERCLAWD_MCP_SERVER_PATH)return process.env.SUPERCLAWD_MCP_SERVER_PATH;let e=it(new URL("./mcp-server.mjs",import.meta.url));return ct(e)?e:it(new URL("../dist/mcp-server.mjs",import.meta.url))}function go(){return`superclawd \u2014 Claude Code, supercharged with your SuperClawd workspace.
|
|
206
194
|
|
|
207
195
|
Usage:
|
|
208
196
|
superclawd Launch Claude with your skills/agents/directives loaded
|
|
209
|
-
superclawd
|
|
197
|
+
superclawd login Sign in via your browser
|
|
210
198
|
superclawd switch Set your default workspace (pick from yours)
|
|
211
199
|
superclawd config Toggle launch options + default notifications preference
|
|
212
200
|
superclawd update Update to the latest version (npm i -g superclawd)
|
|
213
201
|
superclawd version
|
|
214
202
|
superclawd help
|
|
215
203
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
MCP_KEY_ID, MCP_SECRET, MCP_WORKSPACE credentials
|
|
220
|
-
`}function wo(){try{return!mo("claude",["--version"],{stdio:"ignore"}).error}catch{return!1}}function ko(e){let t=["--plugin-dir",e.pluginDir];return t.push("--allowedTools","mcp__plugin_superclawd_superclawd__*"),ge()&&t.push("--dangerously-skip-permissions"),new Promise(o=>{let n=pt("claude",t,{stdio:"inherit"});n.on("error",r=>o({code:127,error:`Could not launch claude: ${r.message}. Is Claude Code installed and on PATH?`})),n.on("close",r=>o({code:r??0}))})}function Co(){return process.stdout.write(`Updating superclawd (npm i -g superclawd@latest)\u2026
|
|
221
|
-
`),new Promise(e=>{let t=pt("npm install -g superclawd@latest",{stdio:"inherit",shell:!0});t.on("error",o=>{process.stderr.write(`\u2717 Could not run npm: ${o.message}. Is npm on your PATH?
|
|
204
|
+
Not authenticated yet? Run \`superclawd login\` first.
|
|
205
|
+
`}function ho(){try{return!fo("claude",["--version"],{stdio:"ignore"}).error}catch{return!1}}function wo(e){let t=["--plugin-dir",e.pluginDir];return t.push("--allowedTools","mcp__plugin_superclawd_superclawd__*"),ge()&&t.push("--dangerously-skip-permissions"),new Promise(o=>{let n=at("claude",t,{stdio:"inherit"});n.on("error",r=>o({code:127,error:`Could not launch claude: ${r.message}. Is Claude Code installed and on PATH?`})),n.on("close",r=>o({code:r??0}))})}function ko(){return process.stdout.write(`Updating superclawd (npm i -g superclawd@latest)\u2026
|
|
206
|
+
`),new Promise(e=>{let t=at("npm install -g superclawd@latest",{stdio:"inherit",shell:!0});t.on("error",o=>{process.stderr.write(`\u2717 Could not run npm: ${o.message}. Is npm on your PATH?
|
|
222
207
|
`),e(127)}),t.on("close",o=>{o===0?process.stdout.write("\u2713 Updated. Run `superclawd version` to confirm.\n"):process.stderr.write(`\u2717 Update failed (npm exited ${o}).
|
|
223
|
-
`),e(o??1)})})}async function yo(){if(!ce&&!
|
|
208
|
+
`),e(o??1)})})}async function yo(){if(!ce&&!ho())return process.stderr.write(`\u2717 Claude Code isn't installed (or isn't on your PATH).
|
|
224
209
|
|
|
225
210
|
SuperClawd supercharges Claude Code, so you'll need it first:
|
|
226
211
|
\u2192 https://claude.com/code
|
|
227
212
|
|
|
228
213
|
Once it's installed, run \`superclawd\` again.
|
|
229
|
-
`),1;g||
|
|
230
|
-
`),1;let t=e.session,o=
|
|
231
|
-
`),
|
|
232
|
-
`),
|
|
233
|
-
`),0):(process.stderr.write(`\u2717 ${n.error??"Configuration failed."}
|
|
234
|
-
`),1)}async function $o(){let e=await Qe();return e.cancelled?(process.stdout.write(`Cancelled.
|
|
214
|
+
`),1;g||ye();let e=Ce();if(!e.ok&&!g)return process.stderr.write(`${e.error??"Could not resolve credentials."}
|
|
215
|
+
`),1;let t=e.session,o=rt({total:5,plain:ce,version:lt});if(!g&&he()&&process.stdin.isTTY){let c=await xe(o,t);if(c.cancelled)return o.finish(),130;c.workspace&&(t={...t,workspace:c.workspace})}await o.phase(1,"Resolving credentials\u2026"),await o.phase(2,"Authenticating\u2026");let n=await be(t);if(!n.ok)return o.fail(n.error??"Authentication failed."),1;await o.phase(3,g?"Loading mock catalog\u2026":"Fetching your workspace\u2026");let r;try{r=await Ae(t)}catch(c){return o.fail(`Catalog fetch failed: ${String(c)}`),1}await o.phase(4,"Establishing session\u2026"),qe();let s=He();ke(s.dir,t.workspace);let a=mo();if(!ct(a))return o.fail(`Bundled MCP server not found at ${a}. Run \`npm run build\` first.`),1;await Ie(t,s.id),await o.phase(5,"Generating plugin\u2026");let d=Ke({pluginDir:s.pluginDir,session:t,catalog:r,serverPath:a,launchId:s.id}),m=g?"mock":t.workspace;if(await o.ready(`${m} \xB7 ${d.skillCount} skills \xB7 ${d.commandCount} commands \xB7 ${d.workflowCount} workflows`),ce){o.note("Dry run \u2014 not launching Claude. Generated files:");for(let c of d.files)o.note(` ${c}`);return 0}o.handoff();let{code:u,error:i}=await wo(s);return o.finish(),Ye(s),i&&process.stderr.write(`${i}
|
|
216
|
+
`),i?127:u}async function So(){let e=await ze();return e.cancelled||e.ok?0:(process.stderr.write(`\u2717 ${e.error??"Login failed."}
|
|
217
|
+
`),1)}async function Co(){let e=await Je();return e.cancelled?(process.stdout.write(`Cancelled.
|
|
235
218
|
`),0):e.ok?0:(process.stderr.write(`\u2717 ${e.error??"Workspace switch failed."}
|
|
236
|
-
`),1)}async function
|
|
219
|
+
`),1)}async function $o(){let[e]=process.argv.slice(2).filter(t=>t!=="--dry-run");switch(e){case"login":process.exit(await So());return;case"switch":process.exit(await Co());return;case"config":await Ve(),process.exit(0);return;case"update":process.exit(await ko());return;case"version":case"--version":case"-v":console.log(lt);return;case"help":case"--help":case"-h":console.log(go());return;default:process.exit(await yo())}}$o().catch(e=>{nt(String(e)),process.exit(1)});
|
package/dist/mcp-server.mjs
CHANGED
|
@@ -71,8 +71,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
71
71
|
`:`[${n[c]}\r
|
|
72
72
|
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function ss(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===x.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ue(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===x.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=os(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===x.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===x.ZodBranded&&t.keyType._def.type._def.typeName===x.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=ns(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Qp(t,e){if(e.mapStrategy==="record")return ss(t,e);let r=N(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ue(e),n=N(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ue(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function ef(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function tf(t){return t.target==="openAi"?void 0:{not:ue({...t,currentPath:[...t.currentPath,"not"]})}}function rf(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Tn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function of(t,e){if(e.target==="openApi3")return nf(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Tn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Tn[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return nf(t,e)}var nf=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>N(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function sf(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Tn[t.innerType._def.typeName],nullable:!0}:{type:[Tn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=N(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=N(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function af(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",fc(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?H(r,"minimum",n.value,n.message,e):H(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),H(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?H(r,"maximum",n.value,n.message,e):H(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),H(r,"maximum",n.value,n.message,e));break;case"multipleOf":H(r,"multipleOf",n.value,n.message,e);break}return r}function cf(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=A0(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=N(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=j0(t,e);return i!==void 0&&(n.additionalProperties=i),n}function j0(t,e){if(t.catchall._def.typeName!=="ZodNever")return N(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function A0(t){try{return t.isOptional()}catch{return!0}}var uf=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return N(t.innerType._def,e);let r=N(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ue(e)},r]}:ue(e)};var lf=(t,e)=>{if(e.pipeStrategy==="input")return N(t.in._def,e);if(e.pipeStrategy==="output")return N(t.out._def,e);let r=N(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=N(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function df(t,e){return N(t.type._def,e)}function pf(t,e){let n={type:"array",uniqueItems:!0,items:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&H(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&H(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function ff(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>N(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:N(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>N(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function mf(t){return{not:ue(t)}}function hf(t){return ue(t)}var gf=(t,e)=>N(t.innerType._def,e);var _f=(t,e,r)=>{switch(e){case x.ZodString:return os(t,r);case x.ZodNumber:return af(t,r);case x.ZodObject:return cf(t,r);case x.ZodBigInt:return Fp(t,r);case x.ZodBoolean:return Bp();case x.ZodDate:return mc(t,r);case x.ZodUndefined:return mf(r);case x.ZodNull:return rf(r);case x.ZodArray:return Vp(t,r);case x.ZodUnion:case x.ZodDiscriminatedUnion:return of(t,r);case x.ZodIntersection:return Gp(t,r);case x.ZodTuple:return ff(t,r);case x.ZodRecord:return ss(t,r);case x.ZodLiteral:return Yp(t,r);case x.ZodEnum:return Jp(t);case x.ZodNativeEnum:return ef(t);case x.ZodNullable:return sf(t,r);case x.ZodOptional:return uf(t,r);case x.ZodMap:return Qp(t,r);case x.ZodSet:return pf(t,r);case x.ZodLazy:return()=>t.getter()._def;case x.ZodPromise:return df(t,r);case x.ZodNaN:case x.ZodNever:return tf(r);case x.ZodEffects:return Wp(t,r);case x.ZodAny:return ue(r);case x.ZodUnknown:return hf(r);case x.ZodDefault:return Kp(t,r);case x.ZodBranded:return ns(t,r);case x.ZodReadonly:return gf(t,r);case x.ZodCatch:return Hp(t,r);case x.ZodPipeline:return lf(t,r);case x.ZodFunction:case x.ZodVoid:case x.ZodSymbol:return;default:return(n=>{})(e)}};function N(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==qp)return a}if(n&&!r){let a=M0(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=_f(t,t.typeName,e),i=typeof s=="function"?N(s(),e):s;if(i&&D0(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var M0=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:rs(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ue(e)):e.$refStrategy==="seen"?ue(e):void 0}},D0=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var _c=(t,e)=>{let r=Up(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:N(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ue(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=N(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ue(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function q0(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function yc(t,e){var r,n,o;return Qe(t)?Xa(t,{target:q0(e?.target),io:(r=e?.pipeStrategy)!==null&&r!==void 0?r:"input"}):_c(t,{strictUnions:(n=e?.strictUnions)!==null&&n!==void 0?n:!0,pipeStrategy:(o=e?.pipeStrategy)!==null&&o!==void 0?o:"input"})}function vc(t){let e=Ur(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");let n=No(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function bc(t,e){let r=Zo(t,e);if(!r.success)throw r.error;return r.data}var L0=6e4,is=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(Uo,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(Fo,r=>{this._onprogress(r)}),this.setRequestHandler(Vo,r=>({}))}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),Q.fromError(X.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,o;this._transport=e;let s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s?.(),this._onclose()};let i=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{i?.(c),this._onerror(c)};let a=(o=this._transport)===null||o===void 0?void 0:o.onmessage;this._transport.onmessage=(c,u)=>{a?.(c,u),oc(c)||Sp(c)?this._onresponse(c):bp(c)?this._onrequest(c,u):$p(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=Q.fromError(X.ConnectionClosed,"Connection closed");for(let o of r.values())o(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,r){var n,o;let s=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,i=this._transport;if(s===void 0){i?.send({jsonrpc:"2.0",id:e.id,error:{code:X.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let c={signal:a.signal,sessionId:i?.sessionId,_meta:(o=e.params)===null||o===void 0?void 0:o._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,l,d)=>this.request(u,l,{...d,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>s(e,c)).then(u=>{if(!a.signal.aborted)return i?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var l;if(!a.signal.aborted)return i?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:X.InternalError,message:(l=u.message)!==null&&l!==void 0?l:"Internal error",...u.data!==void 0&&{data:u.data}}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),oc(e))n(e);else{let o=Q.fromError(e.error.code,e.error.message,e.error.data);n(o)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}=n??{};return new Promise((a,c)=>{var u,l,d,h,m,p;if(!this._transport){c(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(l=n?.signal)===null||l===void 0||l.throwIfAborted();let f=this._requestMessageId++,g={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),g.params={...e.params,_meta:{...((d=e.params)===null||d===void 0?void 0:d._meta)||{},progressToken:f}});let v=P=>{var R;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),(R=this._transport)===null||R===void 0||R.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(P)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(le=>this._onerror(new Error(`Failed to send cancellation: ${le}`))),c(P)};this._responseHandlers.set(f,P=>{var R;if(!(!((R=n?.signal)===null||R===void 0)&&R.aborted)){if(P instanceof Error)return c(P);try{let le=Zo(r,P.result);le.success?a(le.data):c(le.error)}catch(le){c(le)}}}),(h=n?.signal)===null||h===void 0||h.addEventListener("abort",()=>{var P;v((P=n?.signal)===null||P===void 0?void 0:P.reason)});let $=(m=n?.timeout)!==null&&m!==void 0?m:L0,w=()=>v(Q.fromError(X.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(f,$,n?.maxTotalTimeout,w,(p=n?.resetTimeoutOnProgress)!==null&&p!==void 0?p:!1),this._transport.send(g,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>{this._cleanupTimeout(f),c(P)})})}async notification(e,r){var n,o;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((o=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&o!==void 0?o:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(u,r).catch(l=>this._onerror(l))});return}let a={...e,jsonrpc:"2.0"};await this._transport.send(a,r)}setRequestHandler(e,r){let n=vc(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=bc(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=vc(e);this._notificationHandlers.set(n,o=>{let s=bc(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function yf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function vf(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];yf(i)&&yf(s)?r[o]={...i,...s}:r[o]=s}return r}var sg=vl(sl(),1),ig=vl(og(),1);function Iz(){let t=new sg.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,ig.default)(t),t}var Vs=class{constructor(e){this._ajv=e??Iz()}getValidator(e){var r;let n="$id"in e&&typeof e.$id=="string"?(r=this._ajv.getSchema(e.$id))!==null&&r!==void 0?r:this._ajv.compile(e):this._ajv.compile(e);return o=>n(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var Fs=class extends is{constructor(e,r){var n,o;super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(En.options.map((s,i)=>[s,i])),this.isMessageIgnored=(s,i)=>{let a=this._loggingLevels.get(i);return a?this.LOG_LEVEL_SEVERITY.get(s)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._instructions=r?.instructions,this._jsonSchemaValidator=(o=r?.jsonSchemaValidator)!==null&&o!==void 0?o:new Vs,this.setRequestHandler(sc,s=>this._oninitialize(s)),this.setNotificationHandler(ic,()=>{var s;return(s=this.oninitialized)===null||s===void 0?void 0:s.call(this)}),this._capabilities.logging&&this.setRequestHandler(lc,async(s,i)=>{var a;let c=i.sessionId||((a=i.requestInfo)===null||a===void 0?void 0:a.headers["mcp-session-id"])||void 0,{level:u}=s.params,l=En.safeParse(u);return l.success&&this._loggingLevels.set(c,l.data),{}})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=vf(this._capabilities,e)}assertCapabilityForMethod(e){var r,n,o;switch(e){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(!((o=this._clientCapabilities)===null||o===void 0)&&o.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){var r,n;switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!(!((n=(r=this._clientCapabilities)===null||r===void 0?void 0:r.elicitation)===null||n===void 0)&&n.url))throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:gp.includes(r)?r:nc,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Lo)}async createMessage(e,r){var n,o;if((e.tools||e.toolChoice)&&!(!((o=(n=this._clientCapabilities)===null||n===void 0?void 0:n.sampling)===null||o===void 0)&&o.tools))throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],i=Array.isArray(s.content)?s.content:[s.content],a=i.some(d=>d.type==="tool_result"),c=e.messages.length>1?e.messages[e.messages.length-2]:void 0,u=c?Array.isArray(c.content)?c.content:[c.content]:[],l=u.some(d=>d.type==="tool_use");if(a){if(i.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let d=new Set(u.filter(m=>m.type==="tool_use").map(m=>m.id)),h=new Set(i.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(d.size!==h.size||![...d].every(m=>h.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.request({method:"sampling/createMessage",params:e},dc,r)}async elicitInput(e,r){var n,o,s,i,a;switch((n=e.mode)!==null&&n!==void 0?n:"form"){case"url":{if(!(!((s=(o=this._clientCapabilities)===null||o===void 0?void 0:o.elicitation)===null||s===void 0)&&s.url))throw new Error("Client does not support url elicitation.");let u=e;return this.request({method:"elicitation/create",params:u},es,r)}case"form":{if(!(!((a=(i=this._clientCapabilities)===null||i===void 0?void 0:i.elicitation)===null||a===void 0)&&a.form))throw new Error("Client does not support form elicitation.");let u=e.mode==="form"?e:{...e,mode:"form"},l=await this.request({method:"elicitation/create",params:u},es,r);if(l.action==="accept"&&l.content&&u.requestedSchema)try{let h=this._jsonSchemaValidator.getValidator(u.requestedSchema)(l.content);if(!h.valid)throw new Q(X.InvalidParams,`Elicitation response content does not match requested schema: ${h.errorMessage}`)}catch(d){throw d instanceof Q?d:new Q(X.InternalError,`Error validating elicitation response: ${d instanceof Error?d.message:String(d)}`)}return l}}}createElicitationCompletionNotifier(e,r){var n,o;if(!(!((o=(n=this._clientCapabilities)===null||n===void 0?void 0:n.elicitation)===null||o===void 0)&&o.url))throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},pc,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var cg=Symbol.for("mcp.completable");function ug(t){return!!t&&typeof t=="object"&&cg in t}function lg(t){let e=t[cg];return e?.complete}var ag;(function(t){t.Completable="McpCompletable"})(ag||(ag={}));var Zz=/^[A-Za-z0-9._-]{1,128}$/;function Oz(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!Zz.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function Cz(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function fl(t){let e=Oz(t);return Cz(t,e.warnings),e.isValid}var Bs=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Fs(e,r)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Bt(Xo)),this.server.assertCanSetRequestHandler(Bt(Qo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Xo,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Vr(r.inputSchema);return o?yc(o,{strictUnions:!0,pipeStrategy:"input"}):Nz})(),annotations:r.annotations,_meta:r._meta};if(r.outputSchema){let o=Vr(r.outputSchema);o&&(n.outputSchema=yc(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Qo,async(e,r)=>{let n=this._registeredTools[e.params.name],o;try{if(!n)throw new Q(X.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Q(X.InvalidParams,`Tool ${e.params.name} disabled`);if(n.inputSchema){let s=n.callback,i=Vr(n.inputSchema),a=i??n.inputSchema,c=await Oo(a,e.params.arguments);if(!c.success)throw new Q(X.InvalidParams,`Input validation error: Invalid arguments for tool ${e.params.name}: ${Co(c.error)}`);let u=c.data;o=await Promise.resolve(s(u,r))}else{let s=n.callback;o=await Promise.resolve(s(r))}if(n.outputSchema&&!o.isError){if(!o.structuredContent)throw new Q(X.InvalidParams,`Output validation error: Tool ${e.params.name} has an output schema but no structured content was provided`);let s=Vr(n.outputSchema),i=await Oo(s,o.structuredContent);if(!i.success)throw new Q(X.InvalidParams,`Output validation error: Invalid structured content for tool ${e.params.name}: ${Co(i.error)}`)}}catch(s){if(s instanceof Q&&s.code===X.UrlElicitationRequired)throw s;return this.createToolError(s instanceof Error?s.message:String(s))}return o}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Bt(ts)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ts,async e=>{switch(e.params.ref.type){case"ref/prompt":return Ap(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Mp(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Q(X.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new Q(X.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Q(X.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return so;let o=Ur(n.argsSchema),s=o?.[e.params.argument.name];if(!ug(s))return so;let i=lg(s);if(!i)return so;let a=await i(e.params.argument.value,e.params.context);return pg(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return so;throw new Q(X.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return so;let s=await o(e.params.argument.value,e.params.context);return pg(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Bt(Ko)),this.server.assertCanSetRequestHandler(Bt(Wo)),this.server.assertCanSetRequestHandler(Bt(Jo)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ko,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Wo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Jo,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Q(X.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new Q(X.InvalidParams,`Resource ${n} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Bt(Go)),this.server.assertCanSetRequestHandler(Bt(Yo)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Go,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Az(r.argsSchema):void 0}))})),this.server.setRequestHandler(Yo,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Q(X.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Q(X.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Vr(n.argsSchema),s=await Oo(o,e.params.arguments);if(!s.success)throw new Q(X.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${Co(s.error)}`);let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredResourceTemplates[e],a.name&&(this._registeredResourceTemplates[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.template<"u"&&(i.resourceTemplate=a.template),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=i,i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Lr(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Lr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,i}_createRegisteredTool(e,r,n,o,s,i,a,c){fl(e);let u={title:r,description:n,inputSchema:dg(o),outputSchema:dg(s),annotations:i,_meta:a,callback:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&fl(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=u)),typeof l.title<"u"&&(u.title=l.title),typeof l.description<"u"&&(u.description=l.description),typeof l.paramsSchema<"u"&&(u.inputSchema=Lr(l.paramsSchema)),typeof l.callback<"u"&&(u.callback=l.callback),typeof l.annotations<"u"&&(u.annotations=l.annotations),typeof l._meta<"u"&&(u._meta=l._meta),typeof l.enabled<"u"&&(u.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];ml(c)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!ml(r[0])&&(i=r.shift())):typeof c=="object"&&c!==null&&(i=r.shift())}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var Nz={type:"object",properties:{}};function ml(t){return typeof t!="object"||t===null?!1:Object.keys(t).length===0||Object.values(t).some(jz)}function jz(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function dg(t){if(t)return ml(t)?Lr(t):t}function Az(t){let e=Ur(t);return e?Object.entries(e).map(([r,n])=>{let o=Bd(n),s=Hd(n);return{name:r,description:o,required:!s}}):[]}function Bt(t){let e=Ur(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");let n=No(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function pg(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var so={completion:{values:[],hasMore:!1}};import mg from"node:process";var Hs=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
73
73
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Mz(r)}clear(){this._buffer=void 0}};function Mz(t){return zp.parse(JSON.parse(t))}function fg(t){return JSON.stringify(t)+`
|
|
74
|
-
`}var Ks=class{constructor(e=mg.stdin,r=mg.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Hs,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(r=>{let n=fg(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};async function Pg(){return(process.env.SUPERCLAWD_BACKEND||"real").toLowerCase()==="mock"?(await Promise.resolve().then(()=>($g(),xg))).mockBackend:(await Promise.resolve().then(()=>(zg(),Sg))).realBackend}Ws();import{homedir as nP}from"node:os";import{join as ao}from"node:path";import{readFileSync as Eg,writeFileSync as oP,mkdirSync as sP,chmodSync as YZ,existsSync as XZ}from"node:fs";var QZ=(process.env.SUPERCLAWD_BACKEND||"real").toLowerCase();var eO=process.env.SUPERCLAWD_MCP_API_URL||"https://mcp-api.superclawd.com",Tg=process.env.SUPERCLAWD_HOME||ao(nP(),".superclawd"),iP=ao(Tg,"sessions"),aP=ao(Tg,"config.json");function cP(t){if(!t||typeof t!="object")return{};let e=t,r=e.credentials??{...typeof e.keyId=="string"?{keyId:e.keyId}:{},...typeof e.secret=="string"?{secret:e.secret}:{},...typeof e.workspace=="string"?{workspace:e.workspace}:{}},n=e.preferences??{...typeof e.skipPermissions=="boolean"?{skipPermissions:e.skipPermissions}:{},...typeof e.notifications=="boolean"?{notifications:e.notifications}:{},...typeof e.chooseWorkspaceAtStartup=="boolean"?{chooseWorkspaceAtStartup:e.chooseWorkspaceAtStartup}:{}},o={};return Object.keys(r).length&&(o.credentials=r),Object.keys(n).length&&(o.preferences=n),o}function uP(){try{return cP(JSON.parse(Eg(aP,"utf8")))}catch{return null}}function lP(){return uP()?.preferences?.notifications===!0}function Rg(t){return ao(iP,t)}function Ig(t){return ao(t,"config.json")}function Zg(t){try{return JSON.parse(Eg(Ig(t),"utf8"))}catch{return null}}function dP(t,e){try{sP(t,{recursive:!0}),oP(Ig(t),`${JSON.stringify(e,null,2)}
|
|
75
|
-
`)}catch{}}function Og(t){let e=t?Zg(Rg(t)):null;return e&&typeof e.notifications=="boolean"?e.notifications:lP()}function Cg(t,e){if(!t)return e;let r=Rg(t),n=Zg(r)??{};return dP(r,{...n,notifications:e}),e}var
|
|
74
|
+
`}var Ks=class{constructor(e=mg.stdin,r=mg.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Hs,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{var o;(o=this.onerror)===null||o===void 0||o.call(this,n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(r=>{let n=fg(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};async function Pg(){return(process.env.SUPERCLAWD_BACKEND||"real").toLowerCase()==="mock"?(await Promise.resolve().then(()=>($g(),xg))).mockBackend:(await Promise.resolve().then(()=>(zg(),Sg))).realBackend}Ws();import{homedir as nP}from"node:os";import{join as ao}from"node:path";import{readFileSync as Eg,writeFileSync as oP,mkdirSync as sP,chmodSync as YZ,existsSync as XZ}from"node:fs";var QZ=(process.env.SUPERCLAWD_BACKEND||"real").toLowerCase();var eO=process.env.SUPERCLAWD_MCP_API_URL||"https://mcp-api.superclawd.com",tO=process.env.SUPERCLAWD_API_URL||"https://api.superclawd.com",Tg=process.env.SUPERCLAWD_HOME||ao(nP(),".superclawd"),iP=ao(Tg,"sessions"),aP=ao(Tg,"config.json");function cP(t){if(!t||typeof t!="object")return{};let e=t,r=e.credentials??{...typeof e.keyId=="string"?{keyId:e.keyId}:{},...typeof e.secret=="string"?{secret:e.secret}:{},...typeof e.workspace=="string"?{workspace:e.workspace}:{}},n=e.preferences??{...typeof e.skipPermissions=="boolean"?{skipPermissions:e.skipPermissions}:{},...typeof e.notifications=="boolean"?{notifications:e.notifications}:{},...typeof e.chooseWorkspaceAtStartup=="boolean"?{chooseWorkspaceAtStartup:e.chooseWorkspaceAtStartup}:{}},o={};return Object.keys(r).length&&(o.credentials=r),Object.keys(n).length&&(o.preferences=n),typeof e.machineId=="string"&&(o.machineId=e.machineId),o}function uP(){try{return cP(JSON.parse(Eg(aP,"utf8")))}catch{return null}}function lP(){return uP()?.preferences?.notifications===!0}function Rg(t){return ao(iP,t)}function Ig(t){return ao(t,"config.json")}function Zg(t){try{return JSON.parse(Eg(Ig(t),"utf8"))}catch{return null}}function dP(t,e){try{sP(t,{recursive:!0}),oP(Ig(t),`${JSON.stringify(e,null,2)}
|
|
75
|
+
`)}catch{}}function Og(t){let e=t?Zg(Rg(t)):null;return e&&typeof e.notifications=="boolean"?e.notifications:lP()}function Cg(t,e){if(!t)return e;let r=Rg(t),n=Zg(r)??{};return dP(r,{...n,notifications:e}),e}var rO=1e3*60*60*24*3;var Kt=await Pg(),Wt=new Bs({name:"superclawd",version:"0.1.0"});Wt.tool("get_directives","Fetch and apply the authoritative SuperClawd instructions for one or more skills. Call this whenever an SuperClawd skill activates, BEFORE acting, passing the skill's skillId. If several skills activate at the same time, pass them together in `skills` to fetch them in one (cheaper) call.",{skillId:Ve.string().optional().describe("A single activated skill's skillId."),action:Ve.string().optional().describe("Action context for `skillId`, e.g. code/test/review."),skills:Ve.array(Ve.object({skillId:Ve.string().describe("The activated skill's skillId."),action:Ve.string().optional().describe("Action context, e.g. code/test/review.")})).optional().describe("Batch form: multiple activated skills to fetch in a single call.")},async({skillId:t,action:e,skills:r})=>{let n=r?.length?r:t?[{skillId:t,action:e}]:[];if(n.length===0)return{isError:!0,content:[{type:"text",text:'<superclawd_error status="400">Provide a skillId, or a non-empty skills array.</superclawd_error>'}]};let o=await Kt.getDirectives(n);return o.ok?{content:[{type:"text",text:o.text??""}]}:{isError:!0,content:[{type:"text",text:`<superclawd_error status="${o.status}">${o.message}</superclawd_error>`}]}});function pP(){try{let t=JSON.parse(process.env.SUPERCLAWD_RESOURCES??"[]");return Array.isArray(t)?t:[]}catch{return[]}}var gl=pP();function fP(){return gl.length===0?"":`
|
|
76
76
|
|
|
77
77
|
Available resources (fetch by name when relevant to the task):
|
|
78
78
|
${gl.map(e=>` - ${e.name}${e.description?`: ${e.description}`:""}`).join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "superclawd",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Claude Code, supercharged — your team's standards, every session. The superclawd CLI loads your workspace's skills, agents, commands, workflows, and live directives into Claude Code as a plugin.",
|
|
5
5
|
"author": "SuperClawd <support@superclawd.com>",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE",
|
|
@@ -32,7 +32,11 @@
|
|
|
32
32
|
"bin": {
|
|
33
33
|
"superclawd": "dist/index.js"
|
|
34
34
|
},
|
|
35
|
-
"files": [
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"README.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
36
40
|
"scripts": {
|
|
37
41
|
"build": "node build.mjs",
|
|
38
42
|
"dev": "node build.mjs && tsx src/index.ts",
|