howtocode 0.7.75 → 0.7.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -154,7 +154,7 @@ nothing to remember.
154
154
  - **Tools** — `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`, plus `think` (private scratchpad), `ask` (multiple-choice question to the user), and `task` (background agents).
155
155
  - **Web search and fetch** — `web_search` and `web_fetch` read public http(s) URLs; local, loopback, and RFC1918 addresses are refused before any request is made. Search defaults to DuckDuckGo, with an optional `BRAVE_API_KEY` upgrade.
156
156
  - **Language server queries** — the read-only `lsp` tool asks a language server for definition, references, hover, symbols, or diagnostics. It needs the matching server on PATH (`typescript-language-server` for this repo); a missing binary comes back as a tool result that says so.
157
- - **Browser relay** — the `browser` tool drives the Chrome tabs you already have open, so signed-in sessions are reused instead of logging in again in a headless browser. Run `/browser-relay install` once, load the unpacked extension from `~/.howtocode/agent/browser-relay/extension` in `chrome://extensions`, set port `9224`, and paste the token from the file the command names into the extension options. The token is never printed. `/browser-relay status` reports the connection. The relay binds `127.0.0.1` only and requires that token; set `HOWTOCODE_BROWSER_RELAY_PORT` if the default port is taken. Actions: `status`, `tabs`, `open`, `activate`, `navigate`, `evaluate`, `screenshot`, `close`. The tier is `exec` — in `suggest` mode each call asks first. The extension ships under the MIT license; its license text is installed alongside the files.
157
+ - **Browser relay** — the `browser` tool drives the Chrome tabs you already have open, so signed-in sessions are reused instead of logging in again in a headless browser. Run `/browser-relay install` once, load the unpacked extension from `~/.howtocode/agent/browser-relay/extension` in `chrome://extensions`, and restart Chrome so it picks up the native messaging host. The extension prefers Chrome native messaging (`id.howtofix.howtocode`) and falls back to the loopback WebSocket (`127.0.0.1:9224`) when the host is not registered. The token is never printed. `/browser-relay status` reports the connection. The relay binds `127.0.0.1` only and requires that token; set `HOWTOCODE_BROWSER_RELAY_PORT` if the default port is taken. Actions: `status`, `tabs`, `open`, `activate`, `navigate`, `evaluate`, `screenshot`, `close`. The tier is `exec` — in `suggest` mode each call asks first. The extension ships under the MIT license; its license text is installed alongside the files.
158
158
  - **Discord Rich Presence** — shows the running session on your Discord profile: `HowToCode`, the model, and the project folder. It works with the bundled HowToCode application id; set `HOWTOCODE_DISCORD_CLIENT_ID=<id>` or `"discordClientId": "<id>"` in `~/.howtocode/agent/settings.json` to use your own Discord app, and `HOWTOCODE_DISCORD_DISABLE=1` to turn it off. Discord already shows the application icon, so set that icon to the howtofix.id logo; for a dedicated Rich Presence image, upload an asset under Rich Presence → Art Assets and set `HOWTOCODE_DISCORD_LARGE_IMAGE=<asset-key>`. The IPC client is dependency-free and picks the right socket on Windows (`\\?\\pipe\\discord-ipc-N`), Linux and macOS (`$XDG_RUNTIME_DIR` or `/tmp`); a missing Discord client is a silent no-op.
159
159
  - **Hooks** — `hooks.json` in the config root attaches shell commands to seven lifecycle points (`PreToolUse`, `PostToolUse`, `UserPromptSubmit`, `SessionStart`, `Stop`, `PreCompact`, `SessionEnd`). A hook reads a JSON payload on stdin and decides with its exit code: `0` allows, `2` blocks with its stderr as the reason. A `PreToolUse` hook can also **rewrite** a call's arguments with `updatedInput` — validated against the tool's own schema, so a hook cannot make the agent run something it never asked for. A `PreToolUse` hook outranks the approval mode, so it holds under `full-auto` too. `async` and `once` are supported. See `docs/hooks.md`.
160
160
  - **Sessions** — stored as JSONL under `~/.howtocode/agent/sessions/<project>/`. `-c` continues the latest; `/resume` picks any of them. On startup, transcripts idle for more than 30 days are swept across every project — the session just opened is kept whatever its age — so the store does not grow for the life of the machine (the same window rewind's snapshots use).
@@ -138,8 +138,13 @@ var RECONNECT_MIN_MS = 1000;
138
138
  var RECONNECT_MAX_MS = 1e4;
139
139
  var REMOVE_TAB_ATTEMPTS = 3;
140
140
  var REMOVE_TAB_RETRY_MS = 500;
141
+ var NATIVE_HOST = "id.howtofix.howtocode";
141
142
  var ws = null;
143
+ var nativePort = null;
144
+ var nativeChunks = new Map;
145
+ var nativeAttempts = 0;
142
146
  var reconnectDelay = RECONNECT_MIN_MS;
147
+ var reconnectTimer = null;
143
148
  var pingTimer = null;
144
149
  var relayInitiatedDetachTabs = new Set;
145
150
  var instanceId = null;
@@ -248,6 +253,12 @@ async function restoreGroups() {
248
253
  }
249
254
  }
250
255
  function post(msg) {
256
+ if (nativePort) {
257
+ try {
258
+ nativePort.postMessage(msg);
259
+ return;
260
+ } catch {}
261
+ }
251
262
  if (ws?.readyState === WebSocket.OPEN)
252
263
  ws.send(JSON.stringify(msg));
253
264
  }
@@ -359,6 +370,20 @@ function handleRelayMessage(socket, raw) {
359
370
  }
360
371
  if (msg.t === "pong")
361
372
  return;
373
+ if (msg.t === "linked") {
374
+ reconnectDelay = RECONNECT_MIN_MS;
375
+ nativeAttempts = 0;
376
+ setBadge(true);
377
+ buildHello().then((hello) => post(hello));
378
+ clearInterval(pingTimer ?? undefined);
379
+ pingTimer = setInterval(() => post({ t: "ping" }), PING_INTERVAL_MS);
380
+ return;
381
+ }
382
+ if (msg.t === "unlinked") {
383
+ setBadge(false);
384
+ restoreGroups();
385
+ return;
386
+ }
362
387
  if (msg.t === "reload") {
363
388
  chrome.runtime.reload();
364
389
  return;
@@ -371,12 +396,69 @@ function handleRelayMessage(socket, raw) {
371
396
  answer({ t: "rpcResult", id: msg.id, ok: false, error: err instanceof Error ? err.message : String(err) });
372
397
  });
373
398
  }
399
+ function clearTransport() {
400
+ clearTimeout(reconnectTimer ?? undefined);
401
+ clearInterval(pingTimer ?? undefined);
402
+ pingTimer = null;
403
+ nativeChunks.clear();
404
+ }
374
405
  function scheduleReconnect() {
406
+ clearTransport();
375
407
  const delay = reconnectDelay;
376
408
  reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
377
- setTimeout(() => void connect(), delay);
409
+ reconnectTimer = setTimeout(() => void connect(), delay);
378
410
  }
379
- async function connect() {
411
+ function nativeSocket() {
412
+ return {
413
+ readyState: 1,
414
+ send: (raw) => {
415
+ try {
416
+ post(JSON.parse(raw));
417
+ } catch {}
418
+ }
419
+ };
420
+ }
421
+ function connectNative() {
422
+ if (nativePort)
423
+ return true;
424
+ try {
425
+ const port = chrome.runtime.connectNative(NATIVE_HOST);
426
+ nativePort = port;
427
+ port.onMessage.addListener((message) => {
428
+ if (!message || typeof message !== "object")
429
+ return;
430
+ if (message.t === "chunk") {
431
+ const bucket = nativeChunks.get(message.id) ?? [];
432
+ bucket[message.index] = message.data;
433
+ nativeChunks.set(message.id, bucket);
434
+ if (!message.last)
435
+ return;
436
+ nativeChunks.delete(message.id);
437
+ handleRelayMessage(nativeSocket(), bucket.join(""));
438
+ return;
439
+ }
440
+ handleRelayMessage(nativeSocket(), JSON.stringify(message));
441
+ });
442
+ port.onDisconnect.addListener(() => {
443
+ nativePort = null;
444
+ clearTransport();
445
+ setBadge(false);
446
+ restoreGroups();
447
+ nativeAttempts += 1;
448
+ if (nativeAttempts <= 3) {
449
+ reconnectTimer = setTimeout(() => void connect(), reconnectDelay);
450
+ reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
451
+ } else {
452
+ void connectWs();
453
+ }
454
+ });
455
+ return true;
456
+ } catch {
457
+ nativeAttempts += 1;
458
+ return false;
459
+ }
460
+ }
461
+ async function connectWs() {
380
462
  if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING))
381
463
  return;
382
464
  const settings = await loadSettings();
@@ -398,10 +480,7 @@ async function connect() {
398
480
  if (ws !== socket)
399
481
  return;
400
482
  ws = null;
401
- if (pingTimer !== null) {
402
- clearInterval(pingTimer);
403
- pingTimer = null;
404
- }
483
+ clearTransport();
405
484
  setBadge(false);
406
485
  restoreGroups();
407
486
  scheduleReconnect();
@@ -410,6 +489,13 @@ async function connect() {
410
489
  socket.close();
411
490
  };
412
491
  }
492
+ async function connect() {
493
+ if (nativePort || ws)
494
+ return;
495
+ if (chrome.runtime.connectNative && nativeAttempts < 3 && connectNative())
496
+ return;
497
+ await connectWs();
498
+ }
413
499
  var downloads = new DownloadPairing;
414
500
  chrome.downloads.onCreated.addListener((item) => downloads.created(item.id, item.finalUrl));
415
501
  chrome.downloads.onChanged.addListener((delta) => {
@@ -3,9 +3,10 @@
3
3
  "name": "OMP Browser Relay",
4
4
  "version": "0.1.0",
5
5
  "description": "Lets the omp coding agent drive your existing tabs through a local CDP relay.",
6
+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqdTRDfm5+iPc+vFz00bc6BPmcS8HS/oit+ZeCgTZc1EmKvl7k09pzXiFwOA5vHUSubnxjfxhLxt6nhhZYh/wHCNeAjpZzt0AE7aclN1aaxCVuzYJNOL9RRMbcA8l4stC4kqhjdHdOW6Uqu7ErA1MO0XsAI5ELw/Tr0f8qTecO984pxFdZR3MtjrI09Gy3UKId/LsRs79ul3I0Yw5SG8gEbOF5/xoX/R3fxj2lT8bZkzBHUOiUtsz+ChwacIeFyrJpud45awbibrFmcZd7f9FhAMKjLd1izc+ZRoEolr4J1fCDCoIiSawEMTPx1n1TOY8MYBTKxFM6KVRheqQNrFUswIDAQAB",
6
7
  "author": "Stencil Labs, Inc.",
7
8
  "homepage_url": "https://omp.sh",
8
- "permissions": ["debugger", "tabs", "tabGroups", "storage", "alarms", "scripting", "downloads"],
9
+ "permissions": ["debugger", "tabs", "tabGroups", "storage", "alarms", "scripting", "downloads", "nativeMessaging"],
9
10
  "host_permissions": ["<all_urls>"],
10
11
  "background": {
11
12
  "service_worker": "background.js"
@@ -40,8 +40,8 @@
40
40
  <body>
41
41
  <h1>OMP Browser Relay</h1>
42
42
  <p class="hint">
43
- The extension connects to a local <code>omp-browser-relay</code> process. Values here must match the flags the
44
- relay was started with.
43
+ The extension prefers Chrome native messaging and falls back to this loopback WebSocket. The port and token
44
+ below only apply to the fallback; they must match the relay.
45
45
  </p>
46
46
  <label for="port">Relay port</label>
47
47
  <input id="port" type="number" min="1" max="65535" />
@@ -1,4 +1,4 @@
1
- import{$ as We,B as De,C as Ce,E as R,F as q,Fa as ot,H as U,I as Pe,Q as je,R as Ne,Ra as st,S as Me,T as Fe,U as Le,Ua as Q,V as Be,W as Ue,Wa as rt,Y as Ge,_ as Y,a as M,b as F,ba as He,c as ge,ca as qe,d as he,da as ze,e as we,ea as V,f as be,fa as Ze,g as A,ga as Ke,i as ye,j as ke,ja as Xe,k as Se,l as _e,la as Ye,m as X,ma as z,na as Ve,o as Te,oa as Je,p as Ee,q as $e,qa as J,r as ve,s as Ae,t as k,u as Re,ua as Qe,va as et,w as Oe,x as H,xa as tt,y as Ie,ya as nt}from"./chunk-AMHJO4G3.js";import{b as xe}from"./chunk-XODGJSB3.js";import{c as ue}from"./chunk-IM52NDS4.js";import{h as pe,l as fe}from"./chunk-L73LU5W5.js";import{t as me}from"./chunk-ZJL4OEXX.js";import"./chunk-7LA2AMZB.js";import"./chunk-QNBA2A2M.js";import{b as W,c as ie,d as ae}from"./chunk-NLV4AD4X.js";import{H as S,K as de,v as ce,w as le}from"./chunk-5FIFNXLT.js";import"./chunk-UTYFLLSM.js";import"./chunk-MVVEYKN6.js";import"./chunk-WOT6VMZA.js";import{join as Nt}from"node:path";import{hostname as co}from"node:os";import{createAgentSession as lo,createCodemodeExtension as uo,createMcpExtension as po,createToolSearchExtension as fo,DefaultResourceLoader as mo,ProjectTrustStore as go,SessionManager as K,SettingsManager as ho}from"@netrodev/hxf-coding-agent";import{existsSync as Lt,readFileSync as Bt}from"node:fs";import{join as Ut}from"node:path";var it=Ut(S,"APPEND_SYSTEM.md"),Gt=["<non-interactive>","This run has no user attached: it was started with --print, and there is nobody to answer a question. Anything that stops and waits for a reply \u2014 `ask`, a confirmation, a skill that resolves a mode by asking which mode to use \u2014 will simply end the run with the task unfinished.","So do not ask. Where an instruction tells you to ask the user and wait, take the default it describes and continue, and say which default you took and why in your final answer. The user reads that answer; they cannot answer mid-run.","Where a skill offers a choice of modes, prefer the one that applies the rules while you work over the one that audits afterwards: this is the mode for building something now, and the audit mode can still be run later by the same person who reads your answer.","</non-interactive>"].join(`
1
+ import{$ as We,B as De,C as Ce,E as R,F as q,Fa as ot,H as U,I as Pe,Q as je,R as Ne,Ra as st,S as Me,T as Fe,Ta as Q,U as Le,V as Be,Va as rt,W as Ue,Y as Ge,_ as Y,a as M,b as F,ba as He,c as ge,ca as qe,d as he,da as ze,e as we,ea as V,f as be,fa as Ze,g as A,ga as Ke,i as ye,j as ke,ja as Xe,k as Se,l as _e,la as Ye,m as X,ma as z,na as Ve,o as Te,oa as Je,p as Ee,q as $e,qa as J,r as ve,s as Ae,t as k,u as Re,ua as Qe,va as et,w as Oe,x as H,xa as tt,y as Ie,ya as nt}from"./chunk-GXO5FCZF.js";import{t as me}from"./chunk-ZJL4OEXX.js";import{b as xe}from"./chunk-XODGJSB3.js";import"./chunk-DBPJZUIT.js";import{c as ue}from"./chunk-UO2MJVH4.js";import{h as pe,l as fe}from"./chunk-UA2AUPJX.js";import"./chunk-7LA2AMZB.js";import"./chunk-Q2GQPEUC.js";import{b as W,c as ie,d as ae}from"./chunk-OUVT3E6S.js";import{H as S,K as de,v as ce,w as le}from"./chunk-5FIFNXLT.js";import"./chunk-UTYFLLSM.js";import"./chunk-MVVEYKN6.js";import"./chunk-WOT6VMZA.js";import{join as Nt}from"node:path";import{hostname as co}from"node:os";import{createAgentSession as lo,createCodemodeExtension as uo,createMcpExtension as po,createToolSearchExtension as fo,DefaultResourceLoader as mo,ProjectTrustStore as go,SessionManager as K,SettingsManager as ho}from"@netrodev/hxf-coding-agent";import{existsSync as Lt,readFileSync as Bt}from"node:fs";import{join as Ut}from"node:path";var it=Ut(S,"APPEND_SYSTEM.md"),Gt=["<non-interactive>","This run has no user attached: it was started with --print, and there is nobody to answer a question. Anything that stops and waits for a reply \u2014 `ask`, a confirmation, a skill that resolves a mode by asking which mode to use \u2014 will simply end the run with the task unfinished.","So do not ask. Where an instruction tells you to ask the user and wait, take the default it describes and continue, and say which default you took and why in your final answer. The user reads that answer; they cannot answer mid-run.","Where a skill offers a choice of modes, prefer the one that applies the rules while you work over the one that audits afterwards: this is the mode for building something now, and the audit mode can still be run later by the same person who reads your answer.","</non-interactive>"].join(`
2
2
  `),Wt=16*1024;function Ht(e){try{if(!Lt(e))return;let t=Bt(e,"utf8").trim();return!t||Buffer.byteLength(t,"utf8")>Wt?void 0:t}catch{return}}function at(e,t){let s=[t?e:`${e}
3
3
 
4
4
  ${Gt}`],n=Ht(it);return n&&s.push(`# Standing instructions from ${it}
@@ -0,0 +1,17 @@
1
+ import{H as L}from"./chunk-5FIFNXLT.js";import{randomBytes as ue}from"node:crypto";import{existsSync as z,mkdirSync as K,readFileSync as j,renameSync as ge,writeFileSync as pe}from"node:fs";import{dirname as Z,join as E}from"node:path";import{fileURLToPath as me}from"node:url";import{chmodSync as ne,existsSync as H,mkdirSync as W,readFileSync as oe,renameSync as se,writeFileSync as ae}from"node:fs";import{homedir as G,platform as Y}from"node:os";import{dirname as ie,join as b,resolve as de}from"node:path";import{fileURLToPath as ce}from"node:url";function U(a,s,l){let p=l?`void chrome.storage.local.get({ token: "" }).then((stored) => { if (!stored.token) return chrome.storage.local.set({ token: ${JSON.stringify(l)} }); });
2
+ `:"";return`const OMP_INSTALL_VERSION = ${JSON.stringify(s)};
3
+ ${p}${a}`}function J(a,s){let l=JSON.parse(a);return`${JSON.stringify({...l,name:"HowToCode Browser Relay",description:"Lets HowToCode CLI drive your existing tabs through a local CDP relay.",homepage_url:"https://howtofix.id",version_name:s,action:{default_title:"HowToCode Browser Relay (click for settings)"}},null," ")}
4
+ `}function $(a){return a.replaceAll("OMP Browser Relay","HowToCode Browser Relay").replaceAll("omp-browser-relay","howtocode-browser-relay").replaceAll("omp-relay-keepalive","howtocode-relay-keepalive")}var A="id.howtofix.howtocode",V="lejogbchopjpmgjcoelnnmnbeomcodkd";function X(a,s,l){let p=`${a}.${process.pid}.tmp`;ae(p,s,l===void 0?void 0:{mode:l}),se(p,a)}function _(a){return`'${a.replaceAll("'","'\\''")}'`}function le(){if(Y()==="darwin"){let s=b(G(),"Library","Application Support");return[b(s,"Google","Chrome"),b(s,"Chromium"),b(s,"BraveSoftware","Brave-Browser"),b(s,"Microsoft Edge")]}let a=process.env.XDG_CONFIG_HOME?.trim()||b(G(),".config");return[b(a,"google-chrome"),b(a,"chromium"),b(a,"BraveSoftware","Brave-Browser"),b(a,"microsoft-edge")]}function q(a=L){let s=b(a,"browser-relay");W(s,{recursive:!0,mode:448});let l=b(s,"native-host.sh"),p=process.argv[1]?de(process.argv[1]):"",w=p&&H(p)?p:ce(new URL("../../dist/main.js",import.meta.url)),u=["#!/bin/sh",`export HOWTOCODE_CODING_AGENT_DIR=${_(a)}`,`exec ${_(process.execPath)} ${_(w)} browser-relay native-host "$@"`,""].join(`
5
+ `);X(l,u,493),ne(l,493);let y=[];if(Y()==="win32")return{launcher:l,manifests:y};let T=`${JSON.stringify({name:A,description:"HowToCode browser relay native host",path:l,type:"stdio",allowed_origins:[`chrome-extension://${V}/`]},null," ")}
6
+ `;for(let h of le()){if(!H(h))continue;let d=b(h,"NativeMessagingHosts",`${A}.json`);W(ie(d),{recursive:!0}),(H(d)?oe(d,"utf8"):null)!==T&&X(d,T),y.push(d)}return{launcher:l,manifests:y}}var fe=E(Z(me(import.meta.url)),"assets");function be(a){let s=E(a,"browser-relay");return{extensionDir:E(s,"extension"),tokenPath:E(s,"token")}}function C(a){return j(E(fe,`${a}.txt`),"utf8")}function Q(a,s,l){let p=`${a}.${process.pid}.tmp`;pe(p,s,l===void 0?void 0:{mode:l}),ge(p,a)}function Be(a,s){let{extensionDir:l,tokenPath:p}=be(a);K(l,{recursive:!0,mode:448});let w="";z(p)?w=j(p,"utf8").trim():(w=ue(24).toString("hex"),K(Z(p),{recursive:!0}),Q(p,`${w}
7
+ `,384));let u={"manifest.json":J(C("manifest.json"),s),"options.html":$(C("options.html")),"options.js":$(C("options.js")),LICENSE:C("LICENSE"),"background.js":$(U(C("background.js"),s,w))},y=[];for(let[h,d]of Object.entries(u)){let v=E(l,h);(z(v)?j(v,"utf8"):null)!==d&&(Q(v,d,h==="background.js"?384:void 0),y.push(h))}let T=q(a);return{extensionDir:l,tokenPath:p,token:w,wrote:y,nativeLauncher:T.launcher,nativeManifests:T.manifests}}import{createServer as he}from"node:http";import{WebSocketServer as we}from"ws";import{randomBytes as ye,timingSafeEqual as Te}from"node:crypto";var Ie=9224,Se=3e4,ve=3e4;async function Je(a){let s=a.port??Ie,l=a.token??ye(16).toString("hex"),p=a.log??(()=>{}),w=Date.now(),u=null,y=!1,T="",h="",d=[],v=1,I=new Map,S=e=>{let{promise:o,resolve:r,reject:t}=Promise.withResolvers();if(!u||u.readyState!==u.OPEN)return t(new Error("Browser relay extension is not connected. Run /browser-relay install and check the toolbar badge.")),o;let n=v++,i=setTimeout(()=>{I.delete(n),t(new Error(`Browser relay RPC timed out: ${e.op}`))},Se);return I.set(n,{resolve:r,reject:t,timer:i}),u.send(JSON.stringify({t:"rpc",id:n,...e})),o},ee=(e,o)=>{let r;try{r=JSON.parse(o)}catch{return}switch(r.t){case"hello":y=!0,T=r.browserVersion,h=r.userAgent,d=r.tabs,p(`extension connected: ${r.tabs.length} tabs`);break;case"tabCreated":d=[...d.filter(t=>t.tabId!==r.tab.tabId),r.tab];break;case"tabUpdated":d=d.map(t=>t.tabId===r.tab.tabId?r.tab:t);break;case"tabRemoved":d=d.filter(t=>t.tabId!==r.tabId);break;case"rpcResult":{let t=I.get(r.id);if(!t)return;I.delete(r.id),clearTimeout(t.timer),r.ok?t.resolve(r.result):t.reject(new Error(r.error||`Browser relay RPC failed: ${r.id}`));break}case"cdpEvent":{for(let t of N.values()){let n=!1;for(let[i,c]of t.sessions)c===r.tabId&&(g(t,{method:r.method,params:r.params,sessionId:i}),n=!0);!n&&t.tabId===r.tabId&&g(t,{method:r.method,params:r.params})}break}case"detached":{for(let t of N.values()){let n=!1;for(let[i,c]of t.sessions)c===r.tabId&&(t.sessions.delete(i),g(t,{method:"Target.detachedFromTarget",params:{targetId:`tab:${r.tabId}`,sessionId:i,reason:r.reason}}),n=!0);!n&&t.tabId===r.tabId&&g(t,{method:"Target.detachedFromTarget",params:{targetId:`tab:${r.tabId}`,reason:r.reason}})}break}case"ping":e.send(JSON.stringify({t:"pong"}));break;default:break}},N=new Map,te=1,g=(e,o)=>{e.ws.readyState===e.ws.OPEN&&e.ws.send(JSON.stringify(o))},B=e=>{let o=typeof e=="string"?e:"",r=o.startsWith("tab:")?o.slice(4):o,t=Number(r);return Number.isInteger(t)&&t>0?t:void 0},k=e=>({targetId:`tab:${e.tabId}`,type:"page",title:e.title,url:e.url,attached:!1,canAccessOpener:!1}),M=async(e,o,r)=>{await S({op:"attach",tabId:o});let n=[...e.sessions.entries()].find(([,i])=>i===o)?.[0]??`cdp-${e.nextSession++}`;if(e.sessions.set(n,o),r){let i=d.find(c=>c.tabId===o);i&&g(e,{method:"Target.attachedToTarget",params:{sessionId:n,targetInfo:k(i),waitingForDebugger:!1}})}return n},F=(e,o)=>{let r;try{r=JSON.parse(o)}catch{return}if(typeof r.id!="number"||typeof r.method!="string")return;let t=r.id,n=r.method,i=r.params??{};(async()=>{try{if(n==="Browser.getVersion"){g(e,{id:t,result:{protocolVersion:"1.3",product:T||"HowToCode Browser Relay",revision:"",userAgent:h||"HowToCode",jsVersion:""}});return}if(n==="Target.getTargets"){g(e,{id:t,result:{targetInfos:d.map(k)}});return}if(n==="Target.getBrowserContexts"){g(e,{id:t,result:{browserContextIds:[]}});return}if(n==="Target.setDiscoverTargets"){g(e,{id:t,result:{}});for(let m of d)g(e,{method:"Target.targetCreated",params:{targetInfo:k(m)}});return}if(n==="Target.setAutoAttach"){e.autoAttach={flatten:i.flatten===!0},g(e,{id:t,result:{}});for(let m of d)await M(e,m.tabId,!0);return}if(n==="Target.getTargetInfo"){let m=B(i.targetId),x=m===void 0?void 0:d.find(re=>re.tabId===m);if(!x)throw new Error("Target.getTargetInfo needs a known targetId");g(e,{id:t,result:{targetInfo:k(x)}});return}if(n==="Target.createTarget"){let m=await S({op:"createTab",url:String(i.url??"about:blank"),active:!1});if(!m?.tab)throw new Error("Chrome created no tab");g(e,{id:t,result:{targetId:`tab:${m.tab.tabId}`}}),g(e,{method:"Target.targetCreated",params:{targetInfo:k(m.tab)}}),e.autoAttach&&await M(e,m.tab.tabId,!0);return}if(n==="Target.disposeBrowserContext"){g(e,{id:t,result:{}});return}if(n==="Target.attachToTarget"){let m=B(i.targetId);if(m===void 0)throw new Error("Target.attachToTarget needs a tab targetId");let x=await M(e,m,!1);g(e,{id:t,result:{sessionId:x}});return}if(n==="Target.detachFromTarget"){let m=typeof i.sessionId=="string"?i.sessionId:"";e.sessions.delete(m),g(e,{id:t,result:{}});return}if(n==="Target.sendMessageToTarget"){if(typeof i.message!="string")throw new Error("Target.sendMessageToTarget needs a message");F(e,i.message),g(e,{id:t,result:{}});return}let c=typeof r.sessionId=="string"?r.sessionId:void 0,f=c?e.sessions.get(c):e.tabId;if(f===void 0)throw new Error("CDP command has no attached tab session");if(n==="Target.activateTarget"){await S({op:"activateTab",tabId:f}),g(e,{id:t,result:{}});return}if(n==="Target.closeTarget"){await S({op:"removeTab",tabId:f}),g(e,{id:t,result:{success:!0}});return}await S({op:"attach",tabId:f});let O=await S({op:"send",tabId:f,method:n,params:i});g(e,{id:t,result:O??{}})}catch(c){g(e,{id:t,error:{code:-32e3,message:c instanceof Error?c.message:String(c)}})}})()},R=he((e,o)=>{let t=new URL(e.url??"/",`http://127.0.0.1:${s}`).pathname.replace(/\/+$/,"")||"/";if(e.headers.host!==`127.0.0.1:${s}`){o.writeHead(403).end("Forbidden");return}if(e.method!=="GET"){o.writeHead(405).end("Method not allowed");return}if(t==="/json/version"){let n=u!==null&&u.readyState===u.OPEN,i={Browser:T||"HowToCode Browser Relay","Protocol-Version":"1.3","User-Agent":h||"HowToCode",webSocketDebuggerUrl:`ws://127.0.0.1:${s}/cdp`,...n?{}:{error:"relay extension is not connected",extensionSeen:y,uptimeMs:Date.now()-w}};o.writeHead(n?200:503,{"content-type":"application/json"}).end(JSON.stringify(i));return}if(t==="/json"||t==="/json/list"){o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify(d.map(n=>({id:String(n.tabId),type:"page",title:n.title,url:n.url,webSocketDebuggerUrl:`ws://127.0.0.1:${s}/cdp?tab=${n.tabId}`}))));return}if(t==="/health"){o.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify({ok:!0,ready:u!==null,tabs:d.length}));return}o.writeHead(404).end("Not found")}),P=new we({noServer:!0});R.on("upgrade",(e,o,r)=>{let t=new URL(e.url??"/",`http://127.0.0.1:${s}`),n=t.pathname.replace(/\/+$/,"")||"/";if(e.headers.host!==`127.0.0.1:${s}`){o.write(`HTTP/1.1 403 Forbidden\r
8
+ \r
9
+ `),o.destroy();return}let i=e.headers.origin;if(n==="/ext"){if(i&&!i.startsWith("chrome-extension://")){o.write(`HTTP/1.1 403 Forbidden\r
10
+ \r
11
+ `),o.destroy();return}let c=Buffer.from(t.searchParams.get("token")??""),f=Buffer.from(l);if(c.length!==f.length||!Te(c,f)){o.write(`HTTP/1.1 401 Unauthorized\r
12
+ \r
13
+ `),o.destroy();return}}else if(n==="/cdp"){if(i){o.write(`HTTP/1.1 403 Forbidden\r
14
+ \r
15
+ `),o.destroy();return}}else{o.write(`HTTP/1.1 404 Not Found\r
16
+ \r
17
+ `),o.destroy();return}P.handleUpgrade(e,o,r,c=>{if(n==="/ext")u?.close(),u=c,c.on("message",f=>ee(c,f.toString())),c.on("close",()=>{u===c&&(u=null)});else if(n==="/cdp"){let f=Number(t.searchParams.get("tab")??""),O={ws:c,tabId:Number.isInteger(f)&&f>0?f:void 0,sessions:new Map,nextSession:1},m=te++;N.set(m,O),c.on("message",x=>F(O,x.toString())),c.on("close",()=>N.delete(m))}})}),await new Promise((e,o)=>{R.once("error",o),R.listen(s,"127.0.0.1",()=>{R.off("error",o);let r=R.address();r&&typeof r=="object"&&(s=r.port),e()})});let D=setInterval(()=>{for(let e of P.clients)e.readyState===e.OPEN&&e.ping()},ve);return D.unref?.(),p(`relay listening on 127.0.0.1:${s}`),{port:s,token:l,state:()=>({extensionConnected:u!==null&&u.readyState===u.OPEN,extensionSeen:y,browserVersion:T,userAgent:h,tabs:d,uptimeMs:Date.now()-w,port:s}),rpc:S,ready:()=>u!==null&&u.readyState===u.OPEN,stop:async()=>{clearInterval(D);for(let e of I.values())clearTimeout(e.timer),e.reject(new Error("Browser relay stopped"));I.clear();for(let e of P.clients)e.terminate();await new Promise(e=>P.close(()=>e())),await new Promise(e=>R.close(()=>e()))}}}export{be as a,Be as b,Ie as c,Je as d};
@@ -1 +1 @@
1
- import{A,B,C,D,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-IM52NDS4.js";import"./chunk-7LA2AMZB.js";import"./chunk-QNBA2A2M.js";import"./chunk-NLV4AD4X.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";export{g as CATALOG_CACHE_TTL_MS,m as DEFAULT_CONTEXT_WINDOW,a as HOWTOCODE_BASE_URL,b as HOWTOCODE_CONSOLE_URL,l as HOWTOCODE_MODEL_COMPAT,c as HOWTOCODE_PROVIDERS,j as HTTP_IDLE_TIMEOUT_MS,r as UNLIMITED_SENTINEL,w as applyCatalog,x as applyCompat,B as checkAccount,s as checkCreditPools,t as checkUsage,d as configuredProviderIds,y as countNewModels,k as ensureGatewaySettings,C as fetchGatewayPrices,A as findLiveModels,q as isHowtoCodeProvider,h as loadCatalog,o as looksLikeToken,n as maskToken,v as mergeModels,e as newProviderEntry,p as parseModelIds,z as probeModel,D as readProviderKey,f as repairGatewayModels,i as repairModelFacts,u as syncGatewayModelsOnStart};
1
+ import{A,B,C,D,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-UO2MJVH4.js";import"./chunk-7LA2AMZB.js";import"./chunk-Q2GQPEUC.js";import"./chunk-OUVT3E6S.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";export{g as CATALOG_CACHE_TTL_MS,m as DEFAULT_CONTEXT_WINDOW,a as HOWTOCODE_BASE_URL,b as HOWTOCODE_CONSOLE_URL,l as HOWTOCODE_MODEL_COMPAT,c as HOWTOCODE_PROVIDERS,j as HTTP_IDLE_TIMEOUT_MS,r as UNLIMITED_SENTINEL,w as applyCatalog,x as applyCompat,B as checkAccount,s as checkCreditPools,t as checkUsage,d as configuredProviderIds,y as countNewModels,k as ensureGatewaySettings,C as fetchGatewayPrices,A as findLiveModels,q as isHowtoCodeProvider,h as loadCatalog,o as looksLikeToken,n as maskToken,v as mergeModels,e as newProviderEntry,p as parseModelIds,z as probeModel,D as readProviderKey,f as repairGatewayModels,i as repairModelFacts,u as syncGatewayModelsOnStart};