inspekdev 0.0.0-stage → 0.50.0

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/LICENSE ADDED
@@ -0,0 +1,70 @@
1
+ Copyright (c) 2026 Arsyad (https://github.com/arsyadcc). All rights reserved.
2
+
3
+ This package is licensed under the PolyForm Strict License 1.0.0 below: free to use for
4
+ noncommercial purposes; no changes, new works or redistribution.
5
+
6
+ Commercial use (for example in work for an employer or for clients, or in a commercial product
7
+ or service) requires a separate commercial license from Arsyad. Contact: [contact for commercial
8
+ licenses].
9
+
10
+ "Inspek" and the Inspek logo are trademarks of Arsyad and are not licensed under these terms.
11
+
12
+ # PolyForm Strict License 1.0.0
13
+
14
+ <https://polyformproject.org/licenses/strict/1.0.0>
15
+
16
+ ## Acceptance
17
+
18
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
19
+
20
+ ## Copyright License
21
+
22
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose, other than distributing the software or making changes or new works based on the software.
23
+
24
+ ## Patent License
25
+
26
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
27
+
28
+ ## Noncommercial Purposes
29
+
30
+ Any noncommercial purpose is a permitted purpose.
31
+
32
+ ## Personal Uses
33
+
34
+ Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
35
+
36
+ ## Noncommercial Organizations
37
+
38
+ Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
39
+
40
+ ## Fair Use
41
+
42
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
43
+
44
+ ## No Other Rights
45
+
46
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
47
+
48
+ ## Patent Defense
49
+
50
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
51
+
52
+ ## Violations
53
+
54
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
55
+
56
+ ## No Liability
57
+
58
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
59
+
60
+ ## Definitions
61
+
62
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
63
+
64
+ **You** refers to the individual or entity agreeing to these terms.
65
+
66
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
67
+
68
+ **Your licenses** are all the licenses granted to you for the software under these terms.
69
+
70
+ **Use** means anything you do with the software requiring one of your licenses.
package/README.md CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # inspekdev
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Connects the [Inspek](https://inspek.dev) browser extension to your coding agent, such as Claude Code. Inspek lets you inspect, edit and annotate any web page; your agent reads your edits and annotations, previews CSS in your browser and fixes the code.
4
+
5
+ ## Set up (once)
6
+
7
+ ```sh
8
+ npx inspekdev setup
9
+ ```
10
+
11
+ This:
12
+
13
+ 1. adds the Inspek MCP server to Claude Code, for all projects, when Claude Code is installed (otherwise it prints the command for your agent);
14
+ 2. installs a small native messaging host so the extension can pair itself with the Inspek hub on this computer, with no token to copy. It is set up for the Chromium browsers it finds: Chrome, Chromium, Brave, Edge, Vivaldi, Arc and Helium.
15
+
16
+ Then open the extension's options (right-click the Inspek icon → **Options**) and press **Connect to Claude Code**. Start Claude Code and ask it, for example, to *"watch my Inspek annotations"*.
17
+
18
+ ## Commands
19
+
20
+ | Command | |
21
+ |---|---|
22
+ | `npx inspekdev setup` | Set up or repair. `--force` replaces an existing `inspek` MCP server entry, `--no-mcp` skips Claude Code, `--all` writes the host for every known browser even if not installed yet |
23
+ | `npx inspekdev doctor` | Check each piece (Node, token, host, browsers, Claude Code, hub) and say what to fix |
24
+ | `npx inspekdev uninstall` | Remove the native messaging host. `--mcp` also removes the server from Claude Code |
25
+ | `inspekdev mcp` | The MCP server, for other agents: command `npx`, args `["-y", "inspekdev@latest", "mcp"]` |
26
+ | `inspekdev token` | Print the pairing token, to pair a browser by hand in the extension's options |
27
+ | `inspekdev stop` | Stop a running hub (agent sessions start it; it exits after 10 minutes without one) |
28
+
29
+ Everything stays on your computer: the hub listens on `127.0.0.1` only, and both sides prove they know the pairing token (`~/.inspek/token`) without sending it.
30
+
31
+ ## License
32
+
33
+ PolyForm Strict 1.0.0: free for noncommercial use. Commercial use needs an Inspek license. The Inspek extension is sold separately at inspek.dev.
@@ -0,0 +1,38 @@
1
+ # Third-party notices
2
+
3
+ ## Modern Web Guidance
4
+
5
+ Inspek links its page checks and design-study findings to guides from
6
+ [Modern Web Guidance](https://github.com/GoogleChrome/modern-web-guidance)
7
+ (Google Chrome, with the Microsoft Edge, Mozilla Firefox and MDN teams), and
8
+ ships a small index of guide ids and descriptions derived from it
9
+ (`src/guides.js`). The audit rules in `src/audit.js` paraphrase and quote short
10
+ passages of those guides.
11
+
12
+ Licensed under the Apache License, Version 2.0. You may obtain a copy of the
13
+ license at https://www.apache.org/licenses/LICENSE-2.0. Unless required by
14
+ applicable law or agreed to in writing, the material is distributed on an
15
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
16
+
17
+ ## Lucide
18
+
19
+ The icons of the overlay's buttons (`src/icons.js`) are from
20
+ [Lucide](https://lucide.dev).
21
+
22
+ ISC License
23
+
24
+ Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part
25
+ of Feather (MIT). All other copyright (c) for Lucide are held by Lucide
26
+ Contributors 2022.
27
+
28
+ Permission to use, copy, modify, and/or distribute this software for any
29
+ purpose with or without fee is hereby granted, provided that the above
30
+ copyright notice and this permission notice appear in all copies.
31
+
32
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
33
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
34
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
35
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
36
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
37
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
38
+ PERFORMANCE OF THIS SOFTWARE.
@@ -0,0 +1,3 @@
1
+ /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
2
+ import{execFile as U,spawn as j}from"node:child_process";import O from"node:path";import{fileURLToPath as D}from"node:url";import S from"ws";import{nonce as H,proof as N,proofMatches as L}from"./token.mjs";import{compareVersions as F}from"./hub.mjs";const V=O.join(O.dirname(D(import.meta.url)),"daemon.mjs"),$=e=>new Promise(s=>setTimeout(s,e));function x(e=process.env){j(process.execPath,[V],{detached:!0,stdio:"ignore",env:e}).unref()}const P=(e,s)=>new Promise(n=>U(e,s,{timeout:2e3},(f,h)=>n(f?"":h.trim())));async function M(e){const s=(await P("lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"])).split(`
3
+ `)[0];if(!/^\d+$/.test(s))return null;const n=await P("ps",["-o","command=","-p",s]);return{pid:Number(s),command:n}}async function q(e,s){const n=await M(e),f=n?`pid ${n.pid}${n.command?`: ${n.command}`:""}`:"an unknown process",h=/bridge[\\/]server\.mjs/.test(n?.command??"")?"an Edito bridge from before 0.15 (Inspek's former name), which does not use the shared hub":"not an Inspek hub",w=n?` Stop it with: kill ${n.pid}`:` Find it with: lsof -nP -iTCP:${e} -sTCP:LISTEN`;return`Port ${e} is held by ${f} (${h}); it answered HTTP ${s}.${w}. Then call status again.`}function z({port:e,token:s,version:n,takeOver:f=!0,name:h=null}){return new Promise((w,i)=>{const t=new S(`ws://127.0.0.1:${e}`),r=H();let p=!1;const d=(c,a)=>{p||(p=!0,t.terminate(),i(Object.assign(new Error(c),{code:a})))},l=setTimeout(()=>d("The Inspek hub did not answer the handshake.","EAUTH"),5e3);t.once("error",c=>{clearTimeout(l),d(c.message,c.code)}),t.once("unexpected-response",(c,a)=>{clearTimeout(l),q(e,a.statusCode).then(y=>d(y,"EAUTH"))}),t.once("close",(c,a)=>{if(clearTimeout(l),c===4007){d("The user disconnected this agent session in Inspek (Options \u2192 Connected agents). Tell the user; start a new agent session to connect again.","EREFUSED");return}d(`The hub closed the connection (${c} ${a}).`,c===4001?"EAUTH":"ECLOSED")}),t.once("message",c=>{let a;try{a=JSON.parse(c.toString())}catch{}if(a?.type!=="challenge"){clearTimeout(l),d(`Port ${e} is used by something that is not an Inspek hub (an older Inspek bridge?). Restart agent sessions that use Inspek.`,"EAUTH");return}t.send(JSON.stringify({type:"hello",role:"agent",proof:N(s,"agent",a.nonce),nonce:r,version:n,name:h,pid:process.pid})),t.once("message",y=>{clearTimeout(l);let m;try{m=JSON.parse(y.toString())}catch{}if(m?.type!=="welcome"||!L(N(s,"hub",r),m.proof)){d("The hub could not prove it knows the Inspek token.","EAUTH");return}if(f&&F(m.version,n)<0){t.send(JSON.stringify({type:"shutdown"})),d(`A hub of version ${m.version} was running; restarting it as ${n}.`,"EVERSION");return}p=!0,t.removeAllListeners("close"),t.removeAllListeners("error"),w({socket:t,welcome:m})})})})}async function W({port:e,token:s,version:n,startDaemon:f=!0,takeOver:h=!0,name:w=null,env:i=process.env}){for(let t=0;t<30;t+=1)try{const{socket:r,welcome:p}=await z({port:e,token:s,version:n,takeOver:h,name:w});return{socket:r,welcome:p,shutdown:()=>{r.send(JSON.stringify({type:"shutdown"})),r.close()}}}catch(r){const p=r.code==="ECONNREFUSED"||r.code==="EVERSION"||r.code==="ECLOSED";if(!f||!p)throw r;(t===0||r.code==="EVERSION")&&(r.code==="EVERSION"&&await $(400),x(i)),await $(200)}throw Object.assign(new Error(`Could not start or reach the Inspek hub on port ${e}.`),{code:"ECONNREFUSED"})}function Z({port:e,version:s,getToken:n,getName:f=()=>null,env:h=process.env,log:w=()=>{}}){let i=null,t=null,r=null,p=1,d=!1;const l=new Map,c=new Set;let a={};function y(o){i=o,r=null,o.socket.on("message",g=>{let u;try{u=JSON.parse(g.toString())}catch{return}if(u.type==="event"){for(const T of c)T(u.event,u.data);return}const E=l.get(u.id);E&&(l.delete(u.id),clearTimeout(E.timer),u.error?E.reject(new Error(u.error)):E.resolve(u.result))}),o.socket.on("close",()=>{if(i===o){i=null;for(const g of l.values())clearTimeout(g.timer),g.reject(new Error("The Inspek hub connection closed."));l.clear(),!d&&c.size&&setTimeout(()=>{m().catch(()=>{})},500)}}),o.socket.on("error",()=>{})}async function m(){return i?.socket.readyState===S.OPEN?i:(t||(t=(async()=>{try{return y(await W({port:e,token:await n(),version:s,name:f(),env:h})),Object.keys(a).length&&i.socket.send(JSON.stringify({type:"state",...a})),w(`connected to hub ${i.welcome.pid} as ${i.welcome.id}`),i}catch(o){throw r=o,o}finally{t=null}})()),t)}async function k(o,g={},{timeoutMs:u=15e3}={}){const{socket:E}=await m(),T=p++;return new Promise((J,b)=>{const R=setTimeout(()=>{l.delete(T),b(new Error(`The browser did not answer "${o}" within ${u/1e3}s.`))},u);l.set(T,{resolve:J,reject:b,timer:R}),E.send(JSON.stringify({id:T,method:o,params:g}))})}async function I(){try{return await k("hub.status")}catch(o){return{listening:!1,error:(r??o).message}}}function v(o){return c.add(o),m().catch(()=>{}),()=>c.delete(o)}function C(o){a={...a,...o},i?.socket.readyState===S.OPEN&&i.socket.send(JSON.stringify({type:"state",...a}))}async function A(){d=!0,i?.socket.close()}return{ensure:m,request:k,status:I,onEvent:v,setState:C,close:A}}export{W as connectAgent,Z as createAgentClient,M as portHolder,x as startDaemonProcess};
package/bridge/cli.mjs ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
3
+ import p from"node:path";import{fileURLToPath as k,pathToFileURL as g}from"node:url";const l=p.dirname(k(import.meta.url)),[e,...a]=process.argv.slice(2),i=t=>a.includes(t),v=t=>a.flatMap((s,n)=>a[n-1]===t?[s]:[]),o=t=>import(g(p.join(l,t)).href);if(e==="setup"){const{setup:t}=await o("setup.mjs"),s=v("--extension-id").filter(n=>/^[a-p]{32}$/.test(n));await t({force:i("--force"),mcp:!i("--no-mcp"),all:i("--all"),extensionIds:s})}else if(e==="doctor"){const[{doctor:t},{connectAgent:s},{DEFAULT_PORT:n},{loadToken:m},{VERSION:d}]=await Promise.all(["setup.mjs","agent-client.mjs","hub.mjs","token.mjs","version.mjs"].map(o)),u=async()=>{try{const c=await s({port:Number(process.env.INSPEK_PORT)||n,token:await m({create:!1}),version:d,startDaemon:!1,takeOver:!1}),h=await new Promise(r=>{c.socket.once("message",f=>{try{r(JSON.parse(f.toString()).result)}catch{r(null)}}),c.socket.send(JSON.stringify({id:1,method:"hub.status"})),setTimeout(()=>r(null),3e3)});return c.socket.close(),h??{listening:!1}}catch{return{listening:!1}}};process.exitCode=await t({hubStatus:u})?1:0}else if(e==="uninstall"){const{uninstall:t}=await o("setup.mjs");await t({mcp:i("--mcp")})}else e==="mcp"?await o("server.mjs"):e==="hub"||e==="token"||e==="stop"?(process.argv=[process.argv[0],p.join(l,"daemon.mjs"),...e==="hub"?[]:[e],...a],await o("daemon.mjs")):(console.log(`inspekdev: connect the Inspek browser extension to your coding agent.
4
+
5
+ npx inspekdev setup connect Inspek to Claude Code (run once)
6
+ npx inspekdev doctor check the connection and say what to fix
7
+ npx inspekdev uninstall remove the browser connection (--mcp: also from Claude Code)
8
+
9
+ inspekdev mcp the MCP server, for agents other than Claude Code:
10
+ command "npx", args ["-y", "inspekdev@latest", "mcp"]
11
+ inspekdev token print the pairing token (to pair a browser by hand)
12
+ inspekdev stop stop a running hub`),process.exitCode=e&&e!=="help"&&e!=="--help"?1:0);
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
3
+ import{appendFile as i}from"node:fs/promises";import a from"node:path";import{createHub as p,DEFAULT_PORT as l}from"./hub.mjs";import{INSPEK_HOME as m,TOKEN_FILE as d,loadToken as t}from"./token.mjs";import{connectAgent as g}from"./agent-client.mjs";import{VERSION as r}from"./version.mjs";const s=Number(process.env.INSPEK_PORT)||l,c=process.argv[2];if(c==="token"&&(console.log(await t()),console.error(`(stored in ${d})`),process.exit(0)),c==="stop"){try{(await g({port:s,version:r,token:await t(),startDaemon:!1})).shutdown(),console.log("Asked the Inspek hub to stop.")}catch(o){console.log(`No Inspek hub answered on port ${s} (${o.message}).`)}process.exit(0)}const h=a.join(m,"hub.log"),n=o=>{i(h,`${new Date().toISOString()} ${o}
4
+ `).catch(()=>{})},e=p({port:s,token:await t(),version:r,idleMs:Number(process.env.INSPEK_HUB_IDLE_MS)||600*1e3,onIdle:()=>{n("no agents for a while, exiting"),e.close().then(()=>process.exit(0))},onShutdown:()=>{e.close().then(()=>process.exit(0))},log:n});try{await e.listen()}catch(o){n(`not starting: ${o.code??o.message}`),process.exit(o.code==="EADDRINUSE"?0:1)}for(const o of["SIGINT","SIGTERM"])process.on(o,()=>{e.close().then(()=>process.exit(0))});
@@ -0,0 +1,2 @@
1
+ /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
2
+ const o="opgaejopkdnngnnplnhkfjmmcmgapoln",n="",E=[o,""].filter(Boolean),e="dev.inspek.bridge";export{o as DEV_EXTENSION_ID,E as EXTENSION_IDS,e as NATIVE_HOST,n as STORE_EXTENSION_ID};
package/bridge/hub.mjs ADDED
@@ -0,0 +1,3 @@
1
+ /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
2
+ import{WebSocketServer as W}from"ws";import{nonce as j,proof as E,proofMatches as F}from"./token.mjs";const U=47824,V=5e3;function X(l,h=""){return typeof l!="string"?!1:l.startsWith("chrome-extension://")?!h||l===`chrome-extension://${h}`:/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(l)}function G(l,h){const y=c=>String(c??"").split(".").map(S=>Number.parseInt(S,10)||0),[u,b]=[y(l),y(h)];for(let c=0;c<Math.max(u.length,b.length);c+=1)if((u[c]??0)!==(b[c]??0))return(u[c]??0)<(b[c]??0)?-1:1;return 0}function Z({port:l=U,host:h="127.0.0.1",token:y,version:u="0",extensionId:b=process.env.INSPEK_EXTENSION_ID||"",idleMs:c=600*1e3,heartbeatMs:S=30*1e3,onIdle:P=()=>{},onShutdown:q=()=>{},log:g=s=>process.stderr.write(`[inspek hub] ${s}
3
+ `)}={}){if(!y)throw new Error("The hub needs a token.");let s=null,$=null,D=1,R=1;const d=new Map,f=new Map,N=new Set,p=new Map,a=(e,n)=>{e?.readyState===e?.OPEN&&e.send(JSON.stringify(n))};let T=null;function H(){for(const e of s?.clients??[]){if(e.missedBeats>=2){e.terminate();continue}e.missedBeats=(e.missedBeats??0)+1;try{e.ping()}catch{}}}let A=!1;function B(){clearTimeout($),!(A||f.size>0)&&($=setTimeout(()=>P(),c),$.unref?.())}function k(){const e=new Map;for(const n of p.values())e.set(n.agent,(e.get(n.agent)??0)+1);return[...f].map(([n,t])=>({id:n,name:t.name,pid:t.pid,connectedAt:t.connectedAt,watching:t.watching,busy:(e.get(t)??0)>0}))}function x(){const e={type:"agents",agents:k()};for(const n of d.values())a(n.socket,e)}function M(){return{listening:!!s,port:s?.address()?.port??l,version:u,pid:process.pid,agents:f.size,agentList:k(),browsers:[...d].map(([e,n])=>({id:e,kind:n.kind,version:n.version,extensionId:n.extensionId,origin:n.origin,connectedAt:n.connectedAt})),extensionConnected:[...d.values()].some(e=>e.kind==="extension"),pinnedExtensionId:b||null}}function C(e){if(e)return d.has(e)?[e,d.get(e)]:null;const n=[...d].reverse();return n.find(([,t])=>t.kind==="extension")??n[0]??null}function _(e,n,t){if(t.type==="shutdown"){if(G(n.version,u)<0){g(`ignored shutdown from ${e} (version ${n.version}, hub ${u}): restart that agent session`);return}g(`shutdown requested by ${e}`),q();return}if(t.type==="state"){n.watching=!!t.watching,x();return}if(t.id===void 0||!t.method)return;const o=w=>a(n.socket,{id:t.id,...w});if(t.method==="hub.status"){o({result:M()});return}const v={...t.params??{}},i=C(v.client);if(delete v.client,!i){o({error:"No browser is connected to Inspek. Open a page with the Inspek extension installed and paired (Options \u2192 bridge token), or start a dev server with the Inspek plugin."});return}const[I,m]=i,r=R++;p.set(r,{agent:n,agentRequestId:t.id,browserId:I}),a(m.socket,{id:r,method:t.method,params:v}),x()}function L(e,n){if(n.type==="ping"){a(d.get(e)?.socket,{type:"pong"});return}if(n.type==="event"){for(const o of f.values())a(o.socket,{type:"event",event:n.event,data:n.data,from:e});return}if(n.type==="disconnect-agent"){const o=f.get(n.id);if(!o)return;Number.isInteger(o.pid)&&N.add(o.pid),g(`agent ${n.id} disconnected by the user`),o.socket.close(4007,"Disconnected by the user in Inspek");return}const t=p.get(n.id);!t||t.browserId!==e||(p.delete(n.id),x(),a(t.agent.socket,n.error?{id:t.agentRequestId,error:n.error}:{id:t.agentRequestId,result:n.result}))}function z(e,n){e.missedBeats=0,e.on("pong",()=>{e.missedBeats=0});const t=n.headers.origin,o=t?"browser":"agent",v=j();let i=null;const I=setTimeout(()=>e.close(4002,"Handshake timed out"),V);a(e,{type:"challenge",nonce:v,version:u}),e.on("message",m=>{let r;try{r=JSON.parse(m.toString())}catch{return}if(i){i.role==="agent"?_(i.id,f.get(i.id),r):L(i.id,r);return}if(r.type!=="hello"||r.role!==o||!F(E(y,o,v),r.proof)||!r.nonce){clearTimeout(I),g(`rejected ${o} client${t?` from ${t}`:""}: not paired`),e.close(4001,"Not paired: the token does not match");return}if(clearTimeout(I),o==="agent"&&N.has(r.pid)){e.close(4007,"Disconnected by the user in Inspek");return}const w=`${o==="agent"?"a":"b"}${D++}`;i={id:w,role:o};const O=new Date().toISOString();o==="agent"?(f.set(w,{socket:e,version:r.version??null,connectedAt:O,name:typeof r.name=="string"?r.name.slice(0,60):null,pid:Number.isInteger(r.pid)?r.pid:null,watching:!1}),clearTimeout($)):d.set(w,{socket:e,kind:r.kind??"browser",version:r.version??null,extensionId:r.extensionId??null,origin:t,connectedAt:O}),a(e,{type:"welcome",id:w,version:u,pid:process.pid,proof:E(y,"hub",r.nonce)}),o==="agent"?x():a(e,{type:"agents",agents:k()}),g(`${o} ${w} connected${t?` from ${t}`:""}`)}),e.on("close",()=>{if(clearTimeout(I),!!i){if(i.role==="agent"){f.delete(i.id);for(const[m,r]of p)r.agent.socket===e&&p.delete(m);B(),x()}else{d.delete(i.id);for(const[m,r]of p)r.browserId===i.id&&(p.delete(m),a(r.agent.socket,{id:r.agentRequestId,error:"The browser disconnected before answering."}))}g(`${i.role} ${i.id} disconnected`)}}),e.on("error",()=>{})}function J(){return new Promise((e,n)=>{const t=new W({host:h,port:l,maxPayload:67108864,verifyClient:({origin:o})=>!o||X(o,b)});t.once("listening",()=>{s=t,s.on("connection",z),B(),T=setInterval(H,S),T.unref?.(),g(`listening on ws://${h}:${s.address().port}`),e(s.address().port)}),t.once("error",o=>{t.close(),n(o)})})}async function K(){A=!0,clearTimeout($),clearInterval(T);for(const e of[...f.values(),...d.values()])e.socket.close(1001,"Hub shutting down");await new Promise(e=>s?s.close(()=>e()):e()),s=null}return{listen:J,close:K,status:M}}export{U as DEFAULT_PORT,G as compareVersions,Z as createHub,X as isAllowedOrigin};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
3
+ import{loadToken as a}from"./token.mjs";const s="__INSPEK_VERSION__".startsWith("__")?"dev":"__INSPEK_VERSION__",f=64*1024;function o(e){const t=Buffer.from(JSON.stringify(e),"utf8"),n=Buffer.alloc(4);n.writeUInt32LE(t.length,0),process.stdout.write(Buffer.concat([n,t]),()=>process.exit(0))}const c=process.argv.slice(2).find(e=>e.startsWith("chrome-extension://"));let r=Buffer.alloc(0);process.stdin.on("data",e=>{if(r=Buffer.concat([r,e]),r.length<4)return;const t=r.readUInt32LE(0);if(t>f){o({ok:!1,error:"Message too large."});return}if(r.length<4+t)return;let n;try{n=JSON.parse(r.subarray(4,4+t).toString("utf8"))}catch{o({ok:!1,error:"Not JSON."});return}l(n).then(o,i=>o({ok:!1,error:i.message}))}),process.stdin.on("end",()=>{r.length<4&&process.exit(0)});async function l(e){return c?e?.type==="ping"?{ok:!0,version:s}:e?.type==="pair"?{ok:!0,version:s,token:await a()}:{ok:!1,error:`Unknown message: ${String(e?.type).slice(0,40)}`}:{ok:!1,error:"Only the Inspek browser extension can use this program."}}
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+ /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
3
+ import{McpServer as A}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as P}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as t}from"zod";import{DEFAULT_PORT as N}from"./hub.mjs";import{createAgentClient as R}from"./agent-client.mjs";import{TOKEN_FILE as O,loadToken as $}from"./token.mjs";import{VERSION as _}from"./version.mjs";const U=`Inspek connects you to the user's browser, where they inspect and visually edit CSS with the Inspek extension.
4
+ Typical workflows:
5
+ - "Apply my browser edits to the code": call get_changes, then edit the source. The user makes these edits in Inspek's visual editor (Edit tab). Every change has a scope: "rule" means a stylesheet rule was changed, so every element matching its selector should change and the rule itself is what you edit; "element" means only that one element should change, so edit where its markup is written. kind "text" is a copy edit (before \u2192 after). When you have edited the source, call verify_changes: it clears each change the source now produces and returns the ones still pending with the value wanted and the value found. Repeat until nothing is pending. Each change lists the rules that currently set the property (sources, most specific last) with location.file/line when found via source maps, the component that renders the element (component.file/line), and on Tailwind pages the classes to replace and suggested classes. Edit there rather than adding inline styles. Locations are resolved from the dev server, so paths may be URL paths (e.g. /src/App.css) relative to the project root. After editing source and reloading, verify with screenshot or inspect.
6
+ - "Try a style change": call apply_css to preview it live in the browser (it is recorded in the change log with origin "agent"), screenshot to check it, and revert_change if it is wrong.
7
+ - "What is this element?": get_selection returns what the user is pointing at in the inspector.
8
+ - "Work through my annotations" / "watch for feedback": the user pins annotations to elements, groups of elements or page areas in the Inspek Annotate tab, usually writes several and sends them together as one batch. Each annotation comes with a screenshot of what was marked (outlined). Call watch_annotations in a loop: it returns annotations nobody has picked up yet (immediately if some are waiting, otherwise when new ones arrive). Read the whole batch first (annotations can relate), then for each annotation: update_annotation status "acknowledged", make the change (use component and selector to find the code), then update_annotation status "resolved" with a short summary. For intent "question", answer with update_annotation message instead of changing code. Many annotations have no intent: judge from the comment whether it asks something (answer it) or asks for a change, and ask in the thread when you cannot tell. If an annotation is unclear, reply with a question and leave it acknowledged. Never resolve an annotation the user rejected.
9
+ - You can leave annotations for the user with add_annotation (for example review findings or questions about a specific element).
10
+ - "Change this text": edit_text changes an element's text in the page and records it as a text change, so the user can check it before you edit the source.
11
+ - While annotations from the user are waiting, Inspek tool results end with a line saying how many; read them with watch_annotations.
12
+ - A <channel source="inspek" event="annotations_added"> message means the user just sent annotations from the browser: start on them right away without waiting to be asked. Call watch_annotations with batchWindowSeconds 0 and work through the batch as described above.
13
+ - When fixing code from Inspek findings or annotations, prefer current web platform practice: findings from audit_page and design features name Modern Web Guidance guide ids; retrieve them (\`npx -y modern-web-guidance@latest retrieve "<id>"\`, or the modern-web-guidance skill) before writing the fix.
14
+ - "Study this site's design" / "compare these sites": call extract_design (optionally per tabId from list_tabs). It measures the rendered page: palette with roles and coverage, type styles and scale, spacing values and base unit, radii, shadows, breakpoints, max widths, motion and the site's own CSS tokens. Use scope "selection" or a selector to study one component. When the user wants a design.md / DESIGN.md file, call it with format "design-md" and write the result to the file. Summarize patterns and reuse ideas, not brand assets.
15
+ - "Critique this page" / "self-driving mode": use the critique or self_driving prompt workflow. The user watches in their browser: focus_element moves a visible agent cursor with a short message, scroll_page scrolls so they can follow, and a banner shows what you are doing with a Stop button. If any tool says the user pressed Stop, stop immediately and summarize.
16
+ - Element refs: results carry a short ref ("e12") next to each selector; pass it wherever a selector is asked for. A stale ref says so: call page_outline or inspect again. Pass edits to apply_css and selectors to inspect to do several in one call.
17
+ - "Show me options" / a design choice the user should see first: propose_changes puts your edits in their own variant; the user compares it with the page before it and keeps or discards it, and the call returns that decision. Edit the source only for what was kept.
18
+ - On sites that are not local development servers the user may be asked before your first change; if they decline, or the site is read-only for agents, say what you would change instead of retrying. Password, payment and one-time-code fields are hidden from you in screenshots and markup.
19
+ - With Claude in Chrome available too: use it to interact with the page (click, type, navigate, log in) and Inspek to inspect and change the design. Both can work on the same tab.
20
+ All tools act on the active tab of the focused browser window unless tabId is given.`,a=R({port:Number(process.env.INSPEK_PORT)||N,version:_,getToken:()=>$(),getName:()=>l.server.getClientVersion()?.name??null,log:e=>process.stderr.write(`[inspek] ${e}
21
+ `)}),l=new A({name:"inspek",version:_},{instructions:U,capabilities:{experimental:{"claude/channel":{}}}}),d=75e3,f=t.string().regex(/^[\w .-]{1,40}$/,"1\u201340 letters, digits, spaces, dots, dashes or underscores."),i=t.number().int().optional().describe("Browser tab id. Defaults to the active tab."),o=e=>({content:[{type:"text",text:typeof e=="string"?e:JSON.stringify(e,null,2)}]});async function y(){try{const e=await a.request("unseen-annotations",{},{timeoutMs:1500});return Number.isInteger(e?.count)?e:null}catch{return null}}const j=new Set(["get_annotations","watch_annotations","update_annotation","add_annotation","status"]),S=e=>`${e} annotation${e===1?"":"s"} from the user ${e===1?"is":"are"} waiting in Inspek. Call watch_annotations (or get_annotations with status "unseen") to read ${e===1?"it":"them"}.`,T=new Set(["status","get_page","get_selection","inspect","get_changes","screenshot","get_annotations","watch_annotations","list_tabs","extract_design","page_outline","audit_page"]),L=new Set(["edit_structure","revert_change"]),D=new Set(["set_viewport","scroll_page","focus_element","edit_classes"]),z=e=>({readOnlyHint:T.has(e),destructiveHint:L.has(e),idempotentHint:T.has(e)||D.has(e),openWorldHint:!1}),G=Number(process.env.INSPEK_BROWSER_WAIT_MS??35e3);let I=!1;async function F(){if(I)return;const e=Date.now()+G;for(;;){const n=await a.status();if(n.browsers?.length){I=!0;return}if(!n.listening||Date.now()>=e)return;await new Promise(c=>setTimeout(c,500))}}function s(e,n,c,u){l.registerTool(e,{description:n,inputSchema:c,annotations:z(e)},async p=>{let r;try{e!=="status"&&await F(),r=await u(p??{})}catch(h){r={isError:!0,content:[{type:"text",text:h.message}]}}if(!j.has(e)){const h=await y();h?.count&&(r={...r,content:[...r.content,{type:"text",text:S(h.count)}]})}return r})}s("status","Check whether the bridge is listening and the browser extension is connected.",{},async()=>{const e=await a.status(),n=e.listening?await y():null;return n&&(e.unseenAnnotations=n.count),n?.count&&(e.hint=S(n.count)),e.listening&&!e.extensionConnected&&!e.browsers?.length&&(e.pairing=`No browser is connected. If the Inspek extension is installed: run "npx inspekdev setup" once, then open the extension's options (right-click the toolbar icon \u2192 Options) and press "Connect to Claude Code". Or paste the token from ${O} there (print it with: npx inspekdev token). A paired browser connects within 30 seconds, or at once when its Inspek icon is clicked. "npx inspekdev doctor" checks the setup.`),o(e)}),s("get_page","URL, title, viewport size, and whether the Inspek inspector is open in the tab.",{tabId:i},async e=>o(await a.request("page",e)));const C={properties:t.array(t.string()).max(40).optional().describe('Only these properties in computed, styles and inherited (a shorthand includes its longhands), e.g. ["padding", "color"]. Use it to ask which rule sets a property.'),html:t.boolean().optional().describe("Also return the element's HTML, pruned (scripts, styles and svg contents removed, long text and deep children cut, at most 4000 characters).")};s("get_selection","The element currently selected or hovered in the Inspek inspector: unique selector, text, box, classes, inline style, layout (display, position, the parent's flex or grid settings, children and their boxes, overflow), computed CSS, styles (the declarations that win in the cascade, as written, each with the selector and stylesheet it comes from), inherited (what it takes from ancestors), related (rules for other states such as :hover, for pseudo-elements, and for media queries that do not match now), notSet (asked-about properties no rule sets, so they have the browser default), and every matching rule with its stylesheet and source location. Opens the inspector if it is closed.",{...C,tabId:i},async e=>o(await a.request("selection",e))),s("inspect",'Describe the elements matching a CSS selector or element ref: box, classes, layout, computed CSS, styles (what wins in the cascade, as written, and where it comes from), inherited values and matching rules. See get_selection for the fields. Each element comes with a short ref ("e12") that any selector parameter accepts. Pass selectors to look up several at once (narrow them with properties).',{selector:t.string().optional().describe("CSS selector or element ref to look up."),selectors:t.array(t.string()).min(1).max(20).optional().describe("Several selectors or refs at once; one result per entry (limit applies to each, default 1)."),limit:t.number().int().min(1).max(20).optional().describe("Maximum elements to describe per selector (default 3, or 1 with selectors)."),...C,tabId:i},async e=>{if(!e.selector&&!e.selectors)throw new Error("Pass selector or selectors.");return o(await a.request("inspect",e,{timeoutMs:3e4}))}),s("get_changes","CSS edits made in the browser on this page (by the user or by apply_css), with before/after values, viewport, and the rules that currently set each property. Use this to apply visual edits to source code.",{format:t.enum(["json","markdown"]).optional().describe("json (default) or a markdown brief."),tabId:i},async e=>o(await a.request("changes",e)));const q=t.object({selector:t.string(),css:t.string(),scope:t.enum(["element","rule"]).optional(),state:t.enum(["hover","focus","active"]).optional(),pseudoElement:t.enum(["before","after","placeholder","marker","selection","first-line","first-letter"]).optional(),media:t.string().optional()});s("apply_css",`Preview CSS on the first element matching a selector. By default this sets inline declarations on that one element; with scope "rule" it changes the stylesheet rule that sets each property, so every element that rule matches changes. With state, pseudoElement or media the declarations go into a rule for that state, pseudo-element or media query (the page's own rule when it has one). The result says what the browser computes afterwards (computedAfter) and lists declarations that changed nothing (noEffect) with the reason when there is a usual one (an inline element ignoring width, a static element ignoring top, a stronger !important rule\u2026). The edit is recorded in the change log and can be undone with revert_change. Does not modify source files. Pass edits to make several changes in one call (one result each, in order).`,{selector:t.string().optional().describe("CSS selector or element ref of the element to change (first match is used)."),css:t.string().optional().describe('Declarations, e.g. "padding: 12px 16px; border-radius: 8px".'),edits:t.array(q).min(1).max(40).optional().describe("Several edits in one call, each with its own selector and css (and optionally scope, state, pseudoElement, media); the other parameters apply to all."),scope:t.enum(["element","rule"]).optional().describe('"element" (default): only this element. "rule": the rule that sets the property, for all elements it matches; falls back to the element when no rule sets it.'),state:t.enum(["hover","focus","active"]).optional().describe("Write the CSS for this state of the element (:hover, :focus/:focus-visible, :active)."),pseudoElement:t.enum(["before","after","placeholder","marker","selection","first-line","first-letter"]).optional().describe("Write the CSS for this pseudo-element of the element (an empty content is added to ::before/::after when they have none)."),media:t.string().optional().describe(`Write the CSS inside this media query, e.g. "(max-width: 640px)" or "@media (prefers-color-scheme: dark)". Prefer one of the page's own breakpoints.`),variant:f.optional().describe("Apply the CSS in this variant: the page switches to it first, creating it empty if it does not exist. See the variants tool."),tabId:i},async e=>{if(!e.edits&&!(e.selector&&e.css))throw new Error("Pass selector and css, or edits.");return o(await a.request("apply",e,{timeoutMs:d+(e.edits?45e3:0)}))}),s("propose_changes",`Show the user a set of CSS changes as a proposal before you touch the source. The edits go into a new variant copied from what the page shows now; the user sees your title and rationale in the browser, compares the proposal with the page before it, and keeps or discards it. The call waits for that answer (decision "keep", "discard" or "timeout") and returns each edit's result. Edit the source only for a kept proposal, then verify_changes. Prefer this over apply_css when the change is a design choice the user should see first.`,{title:t.string().min(1).max(80).describe('Short name of the proposal, e.g. "Roomier cards".'),rationale:t.string().max(240).optional().describe("One sentence: why this change."),edits:t.array(q).min(1).max(40).describe("The CSS changes, as for apply_css edits."),timeoutSeconds:t.number().int().min(10).max(1800).optional().describe("How long to wait for the user's answer (default 600)."),tabId:i},async e=>o(await a.request("propose",e,{timeoutMs:((e.timeoutSeconds??600)+90)*1e3}))),s("variants",'List, switch, create or remove design variants on this page. A variant is a separate set of browser edits; only the active one is shown and returned by get_changes. Use variants to show the user alternatives (for example "compact" and "roomy") and let them compare by switching. With no arguments, lists the variants.',{use:f.optional().describe("Show this variant, creating it if it does not exist."),from:t.enum(["current","empty"]).optional().describe('When use creates a variant: "current" starts from the changes shown now; "empty" (default) starts with none.'),remove:f.optional().describe("Delete this variant. The only variant cannot be removed."),tabId:i},async e=>o(await a.request("variants",e,{timeoutMs:d}))),s("edit_structure",'Move, duplicate or delete an element in the live page, recorded in the change log as kind "structure" so you can make the same change in the source. verify_changes does not check structure changes; they stay pending until reverted with revert_change.',{selector:t.string().describe("CSS selector of the element (first match is used)."),op:t.enum(["up","down","out","in","duplicate","delete"]).describe('"up"/"down": move before the previous / after the next sibling element. "out": move out of its parent, right after it (not out of body). "in": become the last child of the previous sibling element (refused when that sibling cannot hold children, such as img, input, button, a, p, headings, span, lists or tables, or has a shadow root). "duplicate": insert a copy without its id right after it. "delete": remove it. html, head and body cannot be changed.'),tabId:i},async e=>o(await a.request("structure",e,{timeoutMs:d}))),s("set_viewport","See the page at another width or with a user preference, to check a responsive or dark mode fix: width resizes the user's browser window so the page is that many CSS pixels wide (screenshot, inspect and verify_changes then see that width); prefers shows the page as if a preference held, using the page's own @media rules for it. Lists the page's width breakpoints and which hold. Always finish with restore: true, which puts the window and the preference back.",{width:t.number().int().min(240).max(3840).optional().describe("The page width wanted, in CSS pixels, e.g. 375 for a phone."),prefers:t.enum(["dark","reduced-motion","more-contrast"]).nullable().optional().describe("Show the page as if this preference held; null clears it."),restore:t.boolean().optional().describe("Put the window's width and the preference back as they were."),tabId:i},async e=>o(await a.request("viewport",e,{timeoutMs:d}))),s("edit_classes",`Change an element's classes in the live page (Tailwind utilities, BEM modifiers\u2026), recorded in the change log as kind "class" with the class attribute before and after, so the user can check it and you can make the same change in the source. Pass add and/or remove, or set to replace the whole list. Reports classes that no stylesheet on the page has rules for. Undo with revert_change; verify_changes checks the class list after a reload.`,{selector:t.string().describe("CSS selector of the element (first match is used)."),add:t.array(t.string()).max(40).optional().describe('Classes to add, e.g. ["px-4", "rounded-lg"].'),remove:t.array(t.string()).max(40).optional().describe("Classes to remove."),set:t.string().optional().describe("The whole class list, replacing what the element has (add and remove apply after it)."),tabId:i},async e=>o(await a.request("edit-classes",e,{timeoutMs:d}))),s("edit_text",'Change the text of an element in the live page (a heading, a label, a description), recorded in the change log as kind "text" with before and after, so the user can check it and you can make the same change in the source. The element must hold plain text only: pick the innermost element with the text. Undo with revert_change.',{selector:t.string().describe("CSS selector of the element (first match is used)."),text:t.string().describe("The new text."),tabId:i},async e=>o(await a.request("edit-text",e,{timeoutMs:d}))),s("verify_changes","After you edit the source for the changes from get_changes, check which of them the page now produces without the browser preview. Changes that match are cleared from the log (landed); the rest are returned as pending with the value wanted and the value found. Style changes are checked in place (a dev server's hot reload is enough); text changes and pages without hot reload need reload: true.",{reload:t.boolean().optional().describe("Reload the tab first (loses unsaved page state). Needed for text changes and when the dev server does not hot-reload."),tabId:i},async e=>o(await a.request("verify",e,{timeoutMs:d}))),s("revert_change","Undo one recorded change by id, or all changes on the page.",{id:t.string().optional().describe('Change id from get_changes, e.g. "c3".'),all:t.boolean().optional().describe("Undo every recorded change on the page."),tabId:i},async e=>{if(!e.id&&!e.all)throw new Error("Pass an id or all: true.");return o(await a.request("revert",e))}),s("screenshot",'Capture the visible part of the tab, optionally cropped to an element. The inspector overlay is hidden and password, payment and one-time-code fields are covered during capture. By default a JPEG at most 1280 px wide, kept under about 1 MB; use format "png" for exact colors and maxWidth 0 for full resolution.',{selector:t.string().optional().describe("Crop to the first element matching this selector."),padding:t.number().int().min(0).max(200).optional().describe("Extra pixels around the element (default 16)."),format:t.enum(["jpeg","png"]).optional().describe("jpeg (default, small) or png (lossless, larger)."),maxWidth:t.number().int().min(0).max(4096).optional().describe("Largest width in pixels (default 1280; 0 keeps the full device resolution)."),tabId:i},async e=>{const n=await a.request("screenshot",e,{timeoutMs:2e4});return{content:[{type:"image",data:n.data,mimeType:n.mimeType??"image/png"},{type:"text",text:JSON.stringify({url:n.url,size:n.size??null,crop:n.crop??null})}]}});const H=t.enum(["pending","acknowledged","resolved","dismissed"]),B=12;function b(e,{includeImages:n=!0}={}){if(typeof e=="string")return o(e);const c=[],u=e.annotations.map((r,h)=>{if(!r.image)return r;const{image:m,...g}=r;return n&&c.length<B?(c.push({id:r.id,number:h+1,image:m}),{...g,image:`attached below as image ${c.length}`}):{...g,image:"available (call get_annotations with includeImages)"}}),p=[{type:"text",text:JSON.stringify({...e,annotations:u},null,2)}];for(const[r,{id:h,number:m,image:g}]of c.entries()){const[,W,x]=/^data:([^;]+);base64,(.*)$/s.exec(g)??[];x&&(p.push({type:"text",text:`Image ${r+1}: screenshot of annotation ${h} (#${m}), marked elements outlined.`}),p.push({type:"image",data:x,mimeType:W}))}return{content:p}}function E(e){if(!e||typeof e!="object")return e;const n=e.thread?.at(-1);return{id:e.id,status:e.status,intent:e.intent??null,severity:e.severity??null,author:e.author,comment:e.comment,selector:e.selector??null,...n?{lastMessage:{role:n.role,content:n.content}}:{},...e.image?{image:"kept with the annotation (get_annotations returns it as an image)"}:{},updatedAt:e.updatedAt??e.createdAt}}s("get_annotations","Annotations the user pinned to elements (comment, intent, severity, status, thread, selector, component location, highlighted text).",{status:t.enum(["open","unseen","all","pending","acknowledged","resolved","dismissed"]).optional().describe('"open" (default: pending + acknowledged), "unseen" (pending annotations from the user that no agent picked up), or "all".'),allPages:t.boolean().optional().describe("Include annotations from every page instead of only the active tab's page."),format:t.enum(["json","markdown"]).optional(),includeImages:t.boolean().optional().describe("Attach each annotation's screenshot as an image (default true, up to 12)."),tabId:i},async({includeImages:e=!0,...n})=>b(await a.request("annotations",n),{includeImages:e})),s("watch_annotations","Wait for annotations the user sends from the browser and return them together (across all pages), each with a screenshot of what was marked. Returns immediately if unseen annotations are already waiting. Read the whole batch before changing code. Acknowledge each returned annotation with update_annotation, otherwise it is returned again. Call in a loop for hands-free feedback.",{timeoutSeconds:t.number().int().min(5).max(300).optional().describe("How long to wait for the first new annotation (default 120)."),batchWindowSeconds:t.number().int().min(0).max(60).optional().describe("After the first new annotation, wait this long to collect more (default 5).")},async({timeoutSeconds:e=120,batchWindowSeconds:n=5})=>{w+=1,a.setState({watching:!0});try{return await J({timeoutSeconds:e,batchWindowSeconds:n})}finally{w-=1,w||a.setState({watching:!1})}});async function J({timeoutSeconds:e,batchWindowSeconds:n}){const c=()=>a.request("annotations",{status:"unseen",allPages:!0}),u=await c();return u.annotations.length?b(u):await new Promise(r=>{const h=setTimeout(()=>{m(),r(!1)},e*1e3),m=a.onEvent(g=>{g==="annotations-added"&&(clearTimeout(h),m(),r(!0))})})?(await new Promise(r=>setTimeout(r,n*1e3)),b(await c())):o({annotations:[],timedOut:!0,hint:"No new annotations yet. Call watch_annotations again to keep waiting."})}let w=0,v=null;a.onEvent(e=>{e!=="annotations-added"||w||v||(v=setTimeout(async()=>{if(v=null,w)return;const n=await y();if(!n?.count)return;const c=n.count===1?"1 new annotation":`${n.count} new annotations`;await l.server.notification({method:"notifications/claude/channel",params:{content:`The user sent ${c} from Inspek in the browser (ids: ${n.ids.join(", ")}). Start on them now: call watch_annotations with batchWindowSeconds 0, look at each screenshot, acknowledge each annotation, then make the change, answer the question or ask in its thread, and resolve it with a summary.`,meta:{event:"annotations_added",count:String(n.count)}}}).catch(()=>{})},1500))}),a.onEvent(e=>{if(e!=="agent-stopped"&&e!=="agent-resumed")return;const n=e==="agent-stopped";l.server.notification({method:"notifications/claude/channel",params:{content:n?"The user pressed Stop in Inspek. Stop what you are doing in the browser now, make no further changes, and summarize what you did and what is left. Inspek refuses page actions until the user presses Resume.":"The user pressed Resume in Inspek. You may continue the browser work you were doing, if any is left.",meta:{event:n?"agent_stopped":"agent_resumed"}}}).catch(()=>{})}),s("update_annotation",'Update an annotation: set its status ("acknowledged" when you start, "resolved" when done, "dismissed" with a reason when you will not act) and/or add a message to its thread that the user sees in the browser.',{id:t.string().describe('Annotation id, e.g. "a1x2y3"'),status:H.optional(),message:t.string().optional().describe("A reply or question shown in the annotation's thread."),summary:t.string().optional().describe("What you changed (use with status resolved).")},async e=>{if(!e.status&&!e.message&&!e.summary)throw new Error("Pass status, message or summary.");return o(E(await a.request("update-annotation",e)))}),s("add_annotation","Pin an annotation from the agent to an element on the page, e.g. a review finding or a question for the user.",{selector:t.string().describe("CSS selector of the element (first match is used)."),comment:t.string(),intent:t.enum(["change","fix","question","approve"]).optional(),severity:t.enum(["blocking","important","suggestion"]).optional(),tabId:i},async e=>o(E(await a.request("annotate",e)))),s("list_tabs","Open browser tabs with their ids, titles and URLs (to inspect or compare a tab other than the active one).",{},async()=>o(await a.request("tabs"))),s("extract_design","Measure the design system of a page or one component from its rendered styles: colors (with role and coverage), typography (families, loaded fonts, type styles, size scale), spacing values and base unit, radii, shadows, breakpoints, max widths, motion, the site's CSS custom-property tokens, and the modern platform features it uses (container queries, :has(), anchor positioning, view transitions, \u2026) linked to Modern Web Guidance guides.",{scope:t.enum(["page","selection"]).optional().describe('"page" (default) or the element selected in the inspector.'),selector:t.string().optional().describe("Study only this element and its descendants."),format:t.enum(["json","css","markdown","design-md"]).optional().describe("json (default), css (variables), markdown (brief with JSON), or design-md: a readable DESIGN.md spec (overview, color and type tables, spacing, radii, shadows, layout, motion, tokens, CSS variables) to save in a repo."),tabId:i},async e=>o(await a.request("design",e,{timeoutMs:45e3}))),s("page_outline","A compact map of the visible page: landmarks, headings (with level), interactive elements, media (with alt) and text blocks, each with selector, accessible name and document box, plus scroll position and page height. Use it to plan a walk through the page.",{limit:t.number().int().min(20).max(400).optional().describe("Maximum items (default 150)."),tabId:i},async e=>o(await a.request("outline",e))),s("audit_page","Heuristic checks on the rendered page, grounded in Modern Web Guidance: accessibility (contrast, names, focus order and outlines, lang, zoom, headings, iframes, landmarks), forms (autocomplete tokens, password tokens, visible labels, credential forms, code inputs, validation styling), performance (LCP image priority, preloads, image and video dimensions, srcset sizes, lazy loading, render-blocking scripts, content-visibility), text scaling, reduced motion, dialogs and scroll regions. Each finding lists `guides` (ids, with URLs in `guides` at the top) and a `quote` of the rule. Findings are candidates: confirm each visually before reporting it.",{limit:t.number().int().min(5).max(200).optional().describe("Maximum findings (default 60)."),tabId:i},async e=>o(await a.request("audit",e,{timeoutMs:3e4}))),s("scroll_page","Scroll the page so the user can follow along: to an element, to the top or bottom, or by a fraction of the viewport. Returns the new scroll position and whether the bottom was reached.",{selector:t.string().optional().describe("Scroll this element to the top of the viewport."),to:t.enum(["top","bottom"]).optional(),by:t.number().min(-5).max(5).optional().describe("Viewport heights to scroll (default 0.8)."),message:t.string().optional().describe("Shown to the user in the agent banner."),tabId:i},async e=>o(await a.request("scroll",e))),s("focus_element","Point the visible agent cursor at an element (scrolling it into view) with a short message about what you are checking, so the user can watch you work.",{selector:t.string(),message:t.string().optional().describe('Short, e.g. "Checking the CTA contrast".'),tabId:i},async e=>o(await a.request("focus",e)));const M=(e,n)=>`Review the page open in my browser's active tab as a senior product designer, using the inspek tools. I am watching in the browser.
22
+
23
+ 1. Call status (stop if the extension is not connected), then get_page, screenshot, page_outline, audit_page and extract_design (json) to understand the page and its design system.
24
+ 2. Walk the page from top to bottom. For each region: scroll_page so I can follow, focus_element with a short message about what you are checking, and take a screenshot of the region when you need to see it.
25
+ 3. Judge what matters: visual hierarchy, alignment and spacing consistency (against the measured spacing scale), typography and readability, color and contrast, affordance and states of interactive elements, content and copy, and anything that looks broken.${e?`
26
+ Pay particular attention to: ${e}.`:""}
27
+ 4. Treat audit_page findings as leads: confirm each one visually and drop false positives. When an annotation comes from a finding, end it with "Guide: <id>" using the finding's guide id, so the fix can follow that guide.
28
+ 5. Leave at most ${n} annotations with add_annotation, one issue per annotation: specific, saying what you see and what you expect, with intent (fix for bugs and accessibility, change for design improvements, question when you are unsure) and severity (blocking, important or suggestion). Prefer fewer, higher-value annotations over many small ones.
29
+ 6. If a tool says I pressed Stop, stop at once.
30
+
31
+ Finish with a short summary: the annotations you left (id, severity, one line each) and the two or three changes that would improve the page most.`;l.registerPrompt("critique",{title:"Critique this page",description:"The agent walks the page in your browser like a designer, checks it, and leaves annotations on the issues it finds (no code changes).",argsSchema:{focus:t.string().optional().describe("What to pay particular attention to, e.g. 'mobile spacing' or 'the pricing table'."),maxAnnotations:t.string().optional().describe("Maximum number of annotations (default 8).")}},({focus:e,maxAnnotations:n})=>({messages:[{role:"user",content:{type:"text",text:`${M(e,Number(n)||8)}
32
+
33
+ Do not change any code.`}}]})),l.registerPrompt("self_driving",{title:"Self-driving: critique, fix and verify",description:"The agent critiques the page, leaves annotations, then fixes them in this codebase, verifies each fix in the browser and resolves the annotations, while you watch.",argsSchema:{focus:t.string().optional().describe("What to pay particular attention to."),maxAnnotations:t.string().optional().describe("Maximum number of annotations to fix (default 6).")}},({focus:e,maxAnnotations:n})=>({messages:[{role:"user",content:{type:"text",text:`${M(e,Number(n)||6)}
34
+
35
+ Then fix them (self-driving), only if the page is served from this project (for example a local dev server). Otherwise stop after the critique and say so.
36
+
37
+ 7. Work through your annotations from highest severity down. For each: update_annotation status "acknowledged"; find the code using the annotation's component (file and line), the CSS sources from inspect, and the selector. Before writing the fix, get the current best practice from Modern Web Guidance: retrieve the guide named in the annotation ("Guide: <id>") with \`npx -y modern-web-guidance@latest retrieve "<id>"\`, or search with \`npx -y modern-web-guidance@latest search "<2-5 word capability>"\` (use the modern-web-guidance skill instead if it is installed). Make the smallest change that follows the guide and the existing design system (use its tokens and spacing scale).
38
+ 8. Wait for the dev server to reload the page (call get_page; if the change is not visible, reload is up to the dev server, so check again), then verify with focus_element and a screenshot of the element. If it looks right, update_annotation status "resolved" with a one-line summary of the change. If you cannot fix it, reply in the annotation explaining why and leave it acknowledged.
39
+ 9. If a tool says I pressed Stop, stop at once and summarize what is done and what is left.
40
+
41
+ Finish with a summary: what you changed (files), which annotations are resolved, and anything left for me.`}}]})),l.registerPrompt("watch",{title:"Watch my annotations",description:"Hands-free: the agent waits for annotations you send from the browser, works through each batch and resolves them.",argsSchema:{}},()=>({messages:[{role:"user",content:{type:"text",text:`Work through the annotations I send from Inspek in my browser, hands-free.
42
+
43
+ Loop: call watch_annotations (timeoutSeconds 300). When it times out with no annotations, call it again. When annotations arrive, read the whole batch and look at each screenshot first, since annotations can relate to each other. Then for each annotation, highest severity first:
44
+ - update_annotation status "acknowledged";
45
+ - intent "question": answer with update_annotation message, do not change code; intent "approve": resolve it with a short acknowledgement; no intent: judge from the comment whether it is a question or a request;
46
+ - otherwise find the code (component file and line, selector, CSS sources from inspect). For anything beyond a simple value change (forms, dialogs, popovers, images, motion, accessibility, layout techniques), first get the current best practice with \`npx -y modern-web-guidance@latest search "<2-5 word capability>"\` and \`retrieve "<id>"\` (or the modern-web-guidance skill if installed). Make the change, verify it in the browser (focus_element and screenshot), then update_annotation status "resolved" with a one-line summary;
47
+ - if an annotation is unclear, ask in its thread with update_annotation message and leave it acknowledged.
48
+ Never resolve an annotation I reopened or rejected without changing something. Keep looping until I tell you to stop.`}}]})),a.ensure().catch(e=>process.stderr.write(`[inspek] ${e.message}
49
+ `)),await l.connect(new P);const k=async()=>{await a.close(),process.exit(0)};process.stdin.on("close",k),process.on("SIGINT",k),process.on("SIGTERM",k);
@@ -0,0 +1,17 @@
1
+ /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
2
+ import{execFile as E,spawn as x}from"node:child_process";import{existsSync as h}from"node:fs";import{chmod as B,mkdir as I,readFile as C,rm as N,writeFile as w}from"node:fs/promises";import M from"node:os";import r from"node:path";import{fileURLToPath as O}from"node:url";import{EXTENSION_IDS as $,NATIVE_HOST as g}from"./extension-ids.mjs";import{INSPEK_HOME as v,TOKEN_FILE as b,loadToken as T}from"./token.mjs";import{VERSION as _}from"./version.mjs";const S=r.dirname(O(import.meta.url)),l=r.join(v,"native"),u=process.platform==="win32",m=r.join(l,u?"inspek-native-host.bat":"inspek-native-host"),k=r.join(l,`${g}.json`);function y({platform:s=process.platform,home:n=M.homedir()}={}){if(s==="darwin"){const o=r.join(n,"Library","Application Support");return[["Google Chrome","Google/Chrome"],["Chrome Beta","Google/Chrome Beta"],["Chrome Dev","Google/Chrome Dev"],["Chrome Canary","Google/Chrome Canary"],["Chromium","Chromium"],["Brave","BraveSoftware/Brave-Browser"],["Microsoft Edge","Microsoft Edge"],["Vivaldi","Vivaldi"],["Arc","Arc/User Data"],["Helium","net.imput.helium"]].map(([e,t])=>({name:e,profile:r.join(o,t),hosts:r.join(o,t,"NativeMessagingHosts")}))}if(s==="linux"){const o=process.env.XDG_CONFIG_HOME||r.join(n,".config");return[["Google Chrome","google-chrome"],["Chrome Beta","google-chrome-beta"],["Chromium","chromium"],["Brave","BraveSoftware/Brave-Browser"],["Microsoft Edge","microsoft-edge"],["Vivaldi","vivaldi"],["Helium","net.imput.helium"]].map(([e,t])=>({name:e,profile:r.join(o,t),hosts:r.join(o,t,"NativeMessagingHosts")}))}return[]}const j=[["Google Chrome","Software\\Google\\Chrome"],["Chromium","Software\\Chromium"],["Microsoft Edge","Software\\Microsoft\\Edge"],["Brave","Software\\BraveSoftware\\Brave-Browser"],["Vivaldi","Software\\Vivaldi"]].map(([s,n])=>({name:s,key:`HKCU\\${n}\\NativeMessagingHosts\\${g}`}));function P({launcher:s=m,extensionIds:n=$}={}){return{name:g,description:"Inspek: pairs the browser extension with the Inspek hub for coding agents",path:s,type:"stdio",allowed_origins:[...new Set(n)].map(o=>`chrome-extension://${o}/`)}}const f=(s,n)=>new Promise(o=>{E(s,n,{timeout:2e4,windowsHide:!0,shell:u},(e,t,p)=>o({ok:!e,stdout:String(t).trim(),stderr:String(p).trim()}))});function H(){return S.includes(`${r.sep}_npx${r.sep}`)||process.env.npm_command==="exec"?["npx","-y","inspekdev@latest","mcp"]:[process.execPath,r.join(S,"server.mjs")]}async function G(s){await I(l,{recursive:!0,mode:448});for(const e of["native-host.mjs","token.mjs"]){const t=await C(r.join(S,e),"utf8");await w(r.join(l,e),t.replaceAll("__INSPEK_VERSION__",_))}await w(r.join(l,"package.json"),`${JSON.stringify({type:"module",private:!0})}
3
+ `);const n=r.join(l,"native-host.mjs"),o=process.env.INSPEK_HOME?u?`set "INSPEK_HOME=${v}"\r
4
+ `:`export INSPEK_HOME="${v}"
5
+ `:"";u?await w(m,`@echo off\r
6
+ ${o}"${process.execPath}" "${n}" %*\r
7
+ `):(await w(m,`#!/bin/sh
8
+ ${o}exec "${process.execPath}" "${n}" "$@"
9
+ `),await B(m,493)),await w(k,`${JSON.stringify(P({extensionIds:s}),null,2)}
10
+ `)}async function A({all:s=!1}={}){const n=[];if(u){for(const e of j)(await f("reg",["add",e.key,"/ve","/t","REG_SZ","/d",k,"/f"])).ok&&n.push(e.name);return n}const o=await C(k,"utf8");for(const e of y())!s&&!h(e.profile)||(await I(e.hosts,{recursive:!0}),await w(r.join(e.hosts,`${g}.json`),o),n.push(e.name));return n}async function Y({extensionIds:s=[],mcp:n=!0,force:o=!1,all:e=!1,log:t=console.log}={}){await T();const p=[...$,...s];await G(p);const i=await A({all:e});if(t(i.length?`\u2713 Browser connection installed for ${i.join(", ")}.`:"\u2717 No Chromium browser profile found. Open your browser once, then run setup again (or pass --all)."),n){const a=H();if(!(await f("claude",["--version"])).ok)t(`\u2022 Claude Code's CLI was not found. Add the MCP server to your agent yourself:
11
+ claude mcp add -s user inspek -- ${a.join(" ")}`);else{const c=await f("claude",["mcp","get","inspek"]);if(c.ok&&!o)t("\u2713 Claude Code already has the inspek MCP server (pass --force to replace it).");else{c.ok&&await f("claude",["mcp","remove","-s","user","inspek"]);const d=await f("claude",["mcp","add","-s","user","inspek","--",...a]);t(d.ok?"\u2713 Added the inspek MCP server to Claude Code (all projects).":`\u2717 Could not add the MCP server: ${d.stderr||d.stdout}
12
+ claude mcp add -s user inspek -- ${a.join(" ")}`)}}}t(`
13
+ Next: in the browser, open Inspek's options (right-click the Inspek icon \u2192 Options) and press
14
+ "Connect to Claude Code". Then start Claude Code and ask it to use Inspek, for example
15
+ "watch my Inspek annotations".`)}function D(s=m,n=$[0]){return new Promise(o=>{let e=Buffer.alloc(0);const t=x(s,[`chrome-extension://${n}/`],{stdio:["pipe","pipe","ignore"],shell:u,windowsHide:!0}),p=setTimeout(()=>{t.kill(),o({ok:!1,error:"The host did not answer within 5 s."})},5e3);t.on("error",c=>{clearTimeout(p),o({ok:!1,error:c.message})}),t.stdout.on("data",c=>{if(e=Buffer.concat([e,c]),!(e.length<4||e.length<4+e.readUInt32LE(0))){clearTimeout(p);try{o(JSON.parse(e.subarray(4,4+e.readUInt32LE(0)).toString("utf8")))}catch(d){o({ok:!1,error:d.message})}}});const i=Buffer.from(JSON.stringify({type:"ping"})),a=Buffer.alloc(4);a.writeUInt32LE(i.length,0),t.stdin.end(Buffer.concat([a,i]))})}async function Z({log:s=console.log,hubStatus:n=null}={}){let o=0;const e=(i,a,c)=>{i||(o+=1),s(`${i?"\u2713":"\u2717"} ${i?a:c}`)},t=Number(process.versions.node.split(".")[0]);if(e(t>=20,`Node ${process.versions.node}`,`Node ${process.versions.node} is too old: Inspek needs Node 20 or newer.`),e(h(b),`Pairing token in ${b}`,'No pairing token yet: run "npx inspekdev setup".'),e(h(k)&&h(m),`Browser connection installed in ${l}`,'The browser connection is not installed: run "npx inspekdev setup".'),h(m)){const i=await D();e(i.ok,`The browser connection answers (Inspek ${i.version})`,`The browser connection does not start: ${i.error}. Run "npx inspekdev setup" again.`)}if(!u){const i=y().filter(a=>h(a.profile));for(const a of i){const c=r.join(a.hosts,`${g}.json`);let d=null;try{d=JSON.parse(await C(c,"utf8"))}catch{}e(d?.path===m,`${a.name} knows the browser connection`,`${a.name} does not know the browser connection yet: run "npx inspekdev setup".`)}}const p=await f("claude",["mcp","get","inspek"]);if(e(p.ok,"Claude Code has the inspek MCP server",`Claude Code has no inspek MCP server${p.stderr?"":" (or its CLI is not installed)"}: run "npx inspekdev setup".`),n){const i=await n();if(!i.listening)s("\u2022 No hub is running. That is normal: an agent session starts it when it first uses Inspek.");else{const a=i.browsers?.filter(c=>c.kind==="extension")??[];e(a.length>0,`The hub (Inspek ${i.version}) has ${a.length} browser${a.length===1?"":"s"} connected`,`The hub is running but no browser is connected: in Inspek's options press "Connect to Claude Code".`)}}return s(o?`
16
+ ${o} problem${o===1?"":"s"} found.`:`
17
+ Everything is set up.`),o}async function q({mcp:s=!1,log:n=console.log}={}){if(u)for(const o of j)await f("reg",["delete",o.key,"/f"]);else for(const o of y())await N(r.join(o.hosts,`${g}.json`),{force:!0});if(await N(l,{recursive:!0,force:!0}),n("\u2713 Removed the browser connection."),s){const o=await f("claude",["mcp","remove","-s","user","inspek"]);n(o.ok?"\u2713 Removed the inspek MCP server from Claude Code.":"\u2022 Claude Code had no inspek MCP server to remove.")}n(`The pairing token stays in ${b}; delete ${v} to remove everything.`)}export{y as browserDirs,Z as doctor,P as hostManifest,D as pingHost,Y as setup,q as uninstall};
@@ -0,0 +1,3 @@
1
+ /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
2
+ import{createHmac as s,randomBytes as a,timingSafeEqual as u}from"node:crypto";import{chmod as p,copyFile as d,mkdir as h,readFile as c,writeFile as E}from"node:fs/promises";import f from"node:os";import i from"node:path";const m=process.env.INSPEK_HOME||i.join(f.homedir(),".inspek"),o=i.join(m,"token");async function x({create:t=!0}={}){try{return(await c(o,"utf8")).trim()}catch(r){if(r.code!=="ENOENT"||!t)throw r}if(await h(m,{recursive:!0,mode:448}),!process.env.INSPEK_HOME)try{await d(i.join(f.homedir(),".edito","token"),o,1),await p(o,384)}catch{}try{await E(o,`${a(24).toString("base64url")}
3
+ `,{mode:384,flag:"wx"})}catch(r){if(r.code!=="EEXIST")throw r}return(await c(o,"utf8")).trim()}const y=()=>a(18).toString("base64url");function N(t,r,e){return s("sha256",t).update(`${r}:${e}`).digest("base64url")}function k(t,r){const e=Buffer.from(String(t)),n=Buffer.from(String(r??""));return e.length===n.length&&u(e,n)}export{m as INSPEK_HOME,o as TOKEN_FILE,x as loadToken,y as nonce,N as proof,k as proofMatches};
@@ -0,0 +1,2 @@
1
+ /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
2
+ import{readFileSync as e}from"node:fs";const o=JSON.parse(e(new URL("../package.json",import.meta.url),"utf8")).version;export{o as VERSION};
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "inspekdev",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.50.0",
4
+ "description": "Connect the Inspek browser extension to Claude Code and other coding agents: one-step setup, the Inspek MCP server and its local hub.",
5
+ "type": "module",
6
+ "license": "PolyForm-Strict-1.0.0",
7
+ "author": "Arsyad",
8
+ "homepage": "https://inspek.dev",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/arsyadcc/inspek.git"
12
+ },
13
+ "keywords": [
14
+ "inspek",
15
+ "css",
16
+ "inspector",
17
+ "mcp",
18
+ "claude-code",
19
+ "coding-agent",
20
+ "browser-extension"
21
+ ],
22
+ "bin": {
23
+ "inspekdev": "bridge/cli.mjs"
24
+ },
25
+ "files": [
26
+ "bridge",
27
+ "README.md",
28
+ "LICENSE",
29
+ "THIRD_PARTY_NOTICES.md"
30
+ ],
31
+ "engines": {
32
+ "node": ">=20"
33
+ },
34
+ "dependencies": {
35
+ "@modelcontextprotocol/sdk": "1.32.2",
36
+ "ws": "8.22.1",
37
+ "zod": "4.6.7"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
42
+ }