inspekdev 0.49.0 → 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.
@@ -1,3 +1,3 @@
1
1
  /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
2
- import{execFile as C,spawn as R}from"node:child_process";import b from"node:path";import{fileURLToPath as U}from"node:url";import S from"ws";import{nonce as H,proof as k,proofMatches as J}from"./token.mjs";const L=b.join(b.dirname(U(import.meta.url)),"daemon.mjs"),$=e=>new Promise(r=>setTimeout(r,e));function j(e=process.env){R(process.execPath,[L],{detached:!0,stdio:"ignore",env:e}).unref()}const N=(e,r)=>new Promise(n=>C(e,r,{timeout:2e3},(m,h)=>n(m?"":h.trim())));async function D(e){const r=(await N("lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"])).split(`
3
- `)[0];if(!/^\d+$/.test(r))return null;const n=await N("ps",["-o","command=","-p",r]);return{pid:Number(r),command:n}}async function x(e,r){const n=await D(e),m=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",c=n?` Stop it with: kill ${n.pid}`:` Find it with: lsof -nP -iTCP:${e} -sTCP:LISTEN`;return`Port ${e} is held by ${m} (${h}); it answered HTTP ${r}.${c}. Then call status again.`}function F({port:e,token:r,version:n,takeOver:m=!0}){return new Promise((h,c)=>{const t=new S(`ws://127.0.0.1:${e}`),o=H();let f=!1;const d=(i,l)=>{f||(f=!0,t.terminate(),c(Object.assign(new Error(i),{code:l})))},a=setTimeout(()=>d("The Inspek hub did not answer the handshake.","EAUTH"),5e3);t.once("error",i=>{clearTimeout(a),d(i.message,i.code)}),t.once("unexpected-response",(i,l)=>{clearTimeout(a),x(e,l.statusCode).then(w=>d(w,"EAUTH"))}),t.once("close",(i,l)=>{clearTimeout(a),d(`The hub closed the connection (${i} ${l}).`,i===4001?"EAUTH":"ECLOSED")}),t.once("message",i=>{let l;try{l=JSON.parse(i.toString())}catch{}if(l?.type!=="challenge"){clearTimeout(a),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:k(r,"agent",l.nonce),nonce:o,version:n})),t.once("message",w=>{clearTimeout(a);let p;try{p=JSON.parse(w.toString())}catch{}if(p?.type!=="welcome"||!J(k(r,"hub",o),p.proof)){d("The hub could not prove it knows the Inspek token.","EAUTH");return}if(p.version!==n&&m){t.send(JSON.stringify({type:"shutdown"})),d(`A hub of version ${p.version} was running; restarting it as ${n}.`,"EVERSION");return}f=!0,t.removeAllListeners("close"),t.removeAllListeners("error"),h({socket:t,welcome:p})})})})}async function V({port:e,token:r,version:n,startDaemon:m=!0,takeOver:h=!0,env:c=process.env}){for(let t=0;t<30;t+=1)try{const{socket:o,welcome:f}=await F({port:e,token:r,version:n,takeOver:h});return{socket:o,welcome:f,shutdown:()=>{o.send(JSON.stringify({type:"shutdown"})),o.close()}}}catch(o){const f=o.code==="ECONNREFUSED"||o.code==="EVERSION"||o.code==="ECLOSED";if(!m||!f)throw o;(t===0||o.code==="EVERSION")&&(o.code==="EVERSION"&&await $(400),j(c)),await $(200)}throw Object.assign(new Error(`Could not start or reach the Inspek hub on port ${e}.`),{code:"ECONNREFUSED"})}function G({port:e,version:r,getToken:n,env:m=process.env,log:h=()=>{}}){let c=null,t=null,o=null,f=1,d=!1;const a=new Map,i=new Set;function l(s){c=s,o=null,s.socket.on("message",g=>{let u;try{u=JSON.parse(g.toString())}catch{return}if(u.type==="event"){for(const y of i)y(u.event,u.data);return}const E=a.get(u.id);E&&(a.delete(u.id),clearTimeout(E.timer),u.error?E.reject(new Error(u.error)):E.resolve(u.result))}),s.socket.on("close",()=>{if(c===s){c=null;for(const g of a.values())clearTimeout(g.timer),g.reject(new Error("The Inspek hub connection closed."));a.clear(),!d&&i.size&&setTimeout(()=>{w().catch(()=>{})},500)}}),s.socket.on("error",()=>{})}async function w(){return c?.socket.readyState===S.OPEN?c:(t||(t=(async()=>{try{return l(await V({port:e,token:await n(),version:r,env:m})),h(`connected to hub ${c.welcome.pid} as ${c.welcome.id}`),c}catch(s){throw o=s,s}finally{t=null}})()),t)}async function p(s,g={},{timeoutMs:u=15e3}={}){const{socket:E}=await w(),y=f++;return new Promise((I,T)=>{const A=setTimeout(()=>{a.delete(y),T(new Error(`The browser did not answer "${s}" within ${u/1e3}s.`))},u);a.set(y,{resolve:I,reject:T,timer:A}),E.send(JSON.stringify({id:y,method:s,params:g}))})}async function O(){try{return await p("hub.status")}catch(s){return{listening:!1,error:(o??s).message}}}function P(s){return i.add(s),w().catch(()=>{}),()=>i.delete(s)}async function v(){d=!0,c?.socket.close()}return{ensure:w,request:p,status:O,onEvent:P,close:v}}export{V as connectAgent,G as createAgentClient,D as portHolder,j as startDaemonProcess};
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/hub.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
2
- import{WebSocketServer as J}from"ws";import{nonce as K,proof as N,proofMatches as W}from"./token.mjs";const j=47824,F=5e3;function L(l,g=""){return typeof l!="string"?!1:l.startsWith("chrome-extension://")?!g||l===`chrome-extension://${g}`:/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(l)}function G({port:l=j,host:g="127.0.0.1",token:v,version:b="0",extensionId:x=process.env.INSPEK_EXTENSION_ID||"",idleMs:O=600*1e3,heartbeatMs:A=30*1e3,onIdle:B=()=>{},onShutdown:E=()=>{},log:m=s=>process.stderr.write(`[inspek hub] ${s}
3
- `)}={}){if(!v)throw new Error("The hub needs a token.");let s=null,w=null,M=1,q=1;const d=new Map,a=new Map,u=new Map,c=(e,t)=>{e?.readyState===e?.OPEN&&e.send(JSON.stringify(t))};let $=null;function P(){for(const e of s?.clients??[]){if(e.missedBeats>=2){e.terminate();continue}e.missedBeats=(e.missedBeats??0)+1;try{e.ping()}catch{}}}let I=!1;function T(){clearTimeout(w),!(I||a.size>0)&&(w=setTimeout(()=>B(),O),w.unref?.())}function S(){return{listening:!!s,port:s?.address()?.port??l,version:b,pid:process.pid,agents:a.size,browsers:[...d].map(([e,t])=>({id:e,kind:t.kind,version:t.version,extensionId:t.extensionId,origin:t.origin,connectedAt:t.connectedAt})),extensionConnected:[...d.values()].some(e=>e.kind==="extension"),pinnedExtensionId:x||null}}function R(e){if(e)return d.has(e)?[e,d.get(e)]:null;const t=[...d].reverse();return t.find(([,n])=>n.kind==="extension")??t[0]??null}function H(e,t,n){if(n.type==="shutdown"){m(`shutdown requested by ${e}`),E();return}if(n.id===void 0||!n.method)return;const o=p=>c(t.socket,{id:n.id,...p});if(n.method==="hub.status"){o({result:S()});return}const h={...n.params??{}},i=R(h.client);if(delete h.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[y,f]=i,r=q++;u.set(r,{agent:t,agentRequestId:n.id,browserId:y}),c(f.socket,{id:r,method:n.method,params:h})}function C(e,t){if(t.type==="ping"){c(d.get(e)?.socket,{type:"pong"});return}if(t.type==="event"){for(const o of a.values())c(o.socket,{type:"event",event:t.event,data:t.data,from:e});return}const n=u.get(t.id);!n||n.browserId!==e||(u.delete(t.id),c(n.agent.socket,t.error?{id:n.agentRequestId,error:t.error}:{id:n.agentRequestId,result:t.result}))}function D(e,t){e.missedBeats=0,e.on("pong",()=>{e.missedBeats=0});const n=t.headers.origin,o=n?"browser":"agent",h=K();let i=null;const y=setTimeout(()=>e.close(4002,"Handshake timed out"),F);c(e,{type:"challenge",nonce:h,version:b}),e.on("message",f=>{let r;try{r=JSON.parse(f.toString())}catch{return}if(i){i.role==="agent"?H(i.id,a.get(i.id),r):C(i.id,r);return}if(r.type!=="hello"||r.role!==o||!W(N(v,o,h),r.proof)||!r.nonce){clearTimeout(y),m(`rejected ${o} client${n?` from ${n}`:""}: not paired`),e.close(4001,"Not paired: the token does not match");return}clearTimeout(y);const p=`${o==="agent"?"a":"b"}${M++}`;i={id:p,role:o};const k=new Date().toISOString();o==="agent"?(a.set(p,{socket:e,version:r.version??null,connectedAt:k}),clearTimeout(w)):d.set(p,{socket:e,kind:r.kind??"browser",version:r.version??null,extensionId:r.extensionId??null,origin:n,connectedAt:k}),c(e,{type:"welcome",id:p,version:b,pid:process.pid,proof:N(v,"hub",r.nonce)}),m(`${o} ${p} connected${n?` from ${n}`:""}`)}),e.on("close",()=>{if(clearTimeout(y),!!i){if(i.role==="agent"){a.delete(i.id);for(const[f,r]of u)r.agent.socket===e&&u.delete(f);T()}else{d.delete(i.id);for(const[f,r]of u)r.browserId===i.id&&(u.delete(f),c(r.agent.socket,{id:r.agentRequestId,error:"The browser disconnected before answering."}))}m(`${i.role} ${i.id} disconnected`)}}),e.on("error",()=>{})}function _(){return new Promise((e,t)=>{const n=new J({host:g,port:l,maxPayload:67108864,verifyClient:({origin:o})=>!o||L(o,x)});n.once("listening",()=>{s=n,s.on("connection",D),T(),$=setInterval(P,A),$.unref?.(),m(`listening on ws://${g}:${s.address().port}`),e(s.address().port)}),n.once("error",o=>{n.close(),t(o)})})}async function z(){I=!0,clearTimeout(w),clearInterval($);for(const e of[...a.values(),...d.values()])e.socket.close(1001,"Hub shutting down");await new Promise(e=>s?s.close(()=>e()):e()),s=null}return{listen:_,close:z,status:S}}export{j as DEFAULT_PORT,G as createHub,L as isAllowedOrigin};
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};
package/bridge/server.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /*! Inspek (c) 2026 Arsyad. All rights reserved. See LICENSE. */
3
- import{McpServer as A}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as W}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as t}from"zod";import{DEFAULT_PORT as N}from"./hub.mjs";import{createAgentClient as M}from"./agent-client.mjs";import{TOKEN_FILE as P,loadToken as R}from"./token.mjs";import{VERSION as x}from"./version.mjs";const O=`Inspek connects you to the user's browser, where they inspect and visually edit CSS with the Inspek extension.
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
4
  Typical workflows:
5
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
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.
@@ -13,8 +13,12 @@ Typical workflows:
13
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
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
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
- All tools act on the active tab of the focused browser window unless tabId is given.`,a=M({port:Number(process.env.INSPEK_PORT)||N,version:x,getToken:()=>R(),log:e=>process.stderr.write(`[inspek] ${e}
17
- `)}),d=new A({name:"inspek",version:x},{instructions:O,capabilities:{experimental:{"claude/channel":{}}}}),w=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 f(){try{const e=await a.request("unseen-annotations",{},{timeoutMs:1500});return Number.isInteger(e?.count)?e:null}catch{return null}}const $=new Set(["get_annotations","watch_annotations","update_annotation","add_annotation","status"]),_=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"}.`,S=new Set(["status","get_page","get_selection","inspect","get_changes","screenshot","get_annotations","watch_annotations","list_tabs","extract_design","page_outline","audit_page"]),U=new Set(["edit_structure","revert_change"]),j=new Set(["set_viewport","scroll_page","focus_element","edit_classes"]),L=e=>({readOnlyHint:S.has(e),destructiveHint:U.has(e),idempotentHint:S.has(e)||j.has(e),openWorldHint:!1}),D=Number(process.env.INSPEK_BROWSER_WAIT_MS??35e3);let I=!1;async function z(){if(I)return;const e=Date.now()+D;for(;;){const n=await a.status();if(n.browsers?.length){I=!0;return}if(!n.listening||Date.now()>=e)return;await new Promise(h=>setTimeout(h,500))}}function s(e,n,h,l){d.registerTool(e,{description:n,inputSchema:h,annotations:L(e)},async u=>{let r;try{e!=="status"&&await z(),r=await l(u??{})}catch(c){r={isError:!0,content:[{type:"text",text:c.message}]}}if(!$.has(e)){const c=await f();c?.count&&(r={...r,content:[...r.content,{type:"text",text:_(c.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 f():null;return n&&(e.unseenAnnotations=n.count),n?.count&&(e.hint=_(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 ${P} 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 T={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.",{...T,tabId:i},async e=>o(await a.request("selection",e))),s("inspect","Describe the elements matching a CSS selector: 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.",{selector:t.string().describe("CSS selector to look up."),limit:t.number().int().min(1).max(20).optional().describe("Maximum elements to describe (default 3)."),...T,tabId:i},async e=>o(await a.request("inspect",e))),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))),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.`,{selector:t.string().describe("CSS selector of the element to change (first match is used)."),css:t.string().describe('Declarations, e.g. "padding: 12px 16px; border-radius: 8px".'),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:w.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=>o(await a.request("apply",e))),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:w.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:w.optional().describe("Delete this variant. The only variant cannot be removed."),tabId:i},async e=>o(await a.request("variants",e))),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))),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))),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))),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))),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:4e4}))),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 G=t.enum(["pending","acknowledged","resolved","dismissed"]),F=12;function y(e,{includeImages:n=!0}={}){if(typeof e=="string")return o(e);const h=[],l=e.annotations.map((r,c)=>{if(!r.image)return r;const{image:p,...m}=r;return n&&h.length<F?(h.push({id:r.id,number:c+1,image:p}),{...m,image:`attached below as image ${h.length}`}):{...m,image:"available (call get_annotations with includeImages)"}}),u=[{type:"text",text:JSON.stringify({...e,annotations:l},null,2)}];for(const[r,{id:c,number:p,image:m}]of h.entries()){const[,E,k]=/^data:([^;]+);base64,(.*)$/s.exec(m)??[];k&&(u.push({type:"text",text:`Image ${r+1}: screenshot of annotation ${c} (#${p}), marked elements outlined.`}),u.push({type:"image",data:k,mimeType:E}))}return{content:u}}function C(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})=>y(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})=>{g+=1;try{return await H({timeoutSeconds:e,batchWindowSeconds:n})}finally{g-=1}});async function H({timeoutSeconds:e,batchWindowSeconds:n}){const h=()=>a.request("annotations",{status:"unseen",allPages:!0}),l=await h();return l.annotations.length?y(l):await new Promise(r=>{const c=setTimeout(()=>{p(),r(!1)},e*1e3),p=a.onEvent(m=>{m==="annotations-added"&&(clearTimeout(c),p(),r(!0))})})?(await new Promise(r=>setTimeout(r,n*1e3)),y(await h())):o({annotations:[],timedOut:!0,hint:"No new annotations yet. Call watch_annotations again to keep waiting."})}let g=0,b=null;a.onEvent(e=>{e!=="annotations-added"||g||b||(b=setTimeout(async()=>{if(b=null,g)return;const n=await f();if(!n?.count)return;const h=n.count===1?"1 new annotation":`${n.count} new annotations`;await d.server.notification({method:"notifications/claude/channel",params:{content:`The user sent ${h} 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";d.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:G.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(C(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(C(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 q=(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.
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.
18
22
 
19
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.
20
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.
@@ -24,9 +28,9 @@ All tools act on the active tab of the focused browser window unless tabId is gi
24
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.
25
29
  6. If a tool says I pressed Stop, stop at once.
26
30
 
27
- 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.`;d.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:`${q(e,Number(n)||8)}
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)}
28
32
 
29
- Do not change any code.`}}]})),d.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:`${q(e,Number(n)||6)}
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)}
30
34
 
31
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.
32
36
 
@@ -34,7 +38,7 @@ Then fix them (self-driving), only if the page is served from this project (for
34
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.
35
39
  9. If a tool says I pressed Stop, stop at once and summarize what is done and what is left.
36
40
 
37
- Finish with a summary: what you changed (files), which annotations are resolved, and anything left for me.`}}]})),d.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.
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.
38
42
 
39
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:
40
44
  - update_annotation status "acknowledged";
@@ -42,4 +46,4 @@ Loop: call watch_annotations (timeoutSeconds 300). When it times out with no ann
42
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;
43
47
  - if an annotation is unclear, ask in its thread with update_annotation message and leave it acknowledged.
44
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}
45
- `)),await d.connect(new W);const v=async()=>{await a.close(),process.exit(0)};process.stdin.on("close",v),process.on("SIGINT",v),process.on("SIGTERM",v);
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);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inspekdev",
3
- "version": "0.49.0",
3
+ "version": "0.50.0",
4
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
5
  "type": "module",
6
6
  "license": "PolyForm-Strict-1.0.0",