howtocode 0.7.74 → 0.7.76

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 +1 @@
1
- import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i}from"./chunk-XDOA2DID.js";import"./chunk-CPGMEFX5.js";import"./chunk-TPAFM3UD.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";export{b as CLI_REFRESH_SKEW_MS,c as accessTokenIsFresh,g as clearCliCredential,a as cliCredentialsPath,e as readCliCredential,h as refreshCliCredential,d as refreshTokenIsUsable,i as renewCliCredentialIfNeeded,f as writeCliCredential};
1
+ import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i}from"./chunk-AMYTGLTF.js";import"./chunk-DQZCH2E4.js";import"./chunk-SBWZZCV5.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";export{b as CLI_REFRESH_SKEW_MS,c as accessTokenIsFresh,g as clearCliCredential,a as cliCredentialsPath,e as readCliCredential,h as refreshCliCredential,d as refreshTokenIsUsable,i as renewCliCredentialIfNeeded,f as writeCliCredential};
@@ -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-ZXU4RS2P.js";import"./chunk-7LA2AMZB.js";import"./chunk-CPGMEFX5.js";import"./chunk-TPAFM3UD.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-XZBFNLPM.js";import"./chunk-7LA2AMZB.js";import"./chunk-DQZCH2E4.js";import"./chunk-SBWZZCV5.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,2 +1,2 @@
1
- import{g as T,j as R}from"./chunk-CPGMEFX5.js";import{a as P}from"./chunk-UTYFLLSM.js";import{existsSync as z,readFileSync as ye,rmSync as xe}from"node:fs";import{join as ve}from"node:path";import{createHash as q,randomBytes as J}from"node:crypto";import{createServer as ne}from"node:http";import{execFileSync as X}from"node:child_process";import{createHmac as Q}from"node:crypto";import{readFileSync as ee}from"node:fs";import{arch as F,cpus as M,hostname as N,platform as v,userInfo as O}from"node:os";var te="howtocode-cli-hwid-v1";function x(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function $(e,t){try{let r=X(e,t,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});return r.trim().length>0?r.trim():void 0}catch{return}}function re(){let e=v();if(e==="linux"){let t=x("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=x("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let o=x("/sys/class/dmi/id/product_uuid");return o?{value:o,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=$("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"])?.match(/MachineGuid\s+REG_SZ\s+(\S+)/i);return r?.[1]?{value:r[1],source:"windows-machine-guid",strong:!0}:void 0}if(e==="darwin"){let r=$("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function H(){let e=re(),t=e?.value??[N(),v(),F(),O().username].join("\0"),r=e?.source??"hostname";return{id:Q("sha256",te).update(t).digest("hex").slice(0,32),source:r,strong:e?.strong??!1}}function U(e){return[e.id,e.source,N(),v(),F(),O().username,String(M().length),M()[0]?.model??""]}var _="https://howtofix.id",se=300*1e3,G=3e3,K="/callback";function I(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return I(J(32))}function ie(e){return I(q("sha256").update(e).digest())}function ae(){return I(J(16))}var ce="howtocode-cli-",ue="x-howtocode-client",le="cli";function L(e){let t=e??U(H());return ce+q("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function de(){return{"content-type":"application/json",[ue]:le}}var fe=()=>new Promise((e,t)=>{let r=ne();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let{port:o}=r.address();e({port:o,close:()=>r.close(),waitForCode:(n,s)=>new Promise((i,a)=>{let c=(l,f)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){f.writeHead(404).end("not found");return}let y=(V,Z)=>f.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),S=h.searchParams.get("error")??"",E=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(S){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${S}`));return}if(!E||Y!==n){y("This callback did not belong to the login","You can close this tab."),u(new Error("the callback carried the wrong state"));return}y("Signed in","You can close this tab and go back to HowToCode."),u(void 0,E)},u=(l,f)=>{r.off("request",c),s?.removeEventListener("abort",g),l?a(l):i(f)},g=()=>u(new Error("cancelled"));s?.addEventListener("abort",g,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function p(e,t,r,o){let n=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:o}),s={};try{s=await n.json()}catch{}let i=Number(n.headers?.get?.("retry-after"));return{status:n.status,body:s,retryAfterSeconds:Number.isFinite(i)&&i>0?i:void 0}}function d(...e){for(let t of e)if(typeof t=="string"&&t.trim()!=="")return t.trim()}function j(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}function me(e){try{let t=new URL(e).searchParams.get("code");return t&&t.trim()!==""?t.trim():void 0}catch{return}}async function ge(e,t,r){let o=await e(t,{headers:de(),signal:r}),n={};try{n=await o.json()}catch{}let s=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(s)&&s>0?s:void 0}}function A(e){let t=e.data,r=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let o of r)if(typeof o=="string"&&o.trim().startsWith("sk-"))return o.trim()}function pe(e){let t=e.data,r=d(e.token,t?.token),o=d(e.refresh_token,t?.refresh_token),n=d(e.device_id,t?.device_id);if(!r||!o||!n)return;let s=j(e.access_expires_at,t?.access_expires_at),i=j(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:s,refreshToken:o,deviceId:n,refreshExpiresAt:i}}function m(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function He(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??_).replace(/\/+$/,""),o=e.timeoutMs??se,n={...e,panel:r,fetchImpl:t,timeoutMs:o},s=await ke(n);if(s.ok||s.terminal)return s.result;let i=await he(n);if(i.ok||i.terminal)return i.result;let a=await we(n);return a.ok?a:{ok:!1,message:`${s.result.ok?"":s.result.message}; ${i.result.ok?"":i.result.message}; ${a.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${r}/keys instead.`}}async function he(e){let t=oe(),r=ae(),o;try{o=await(e.loopback??fe)();let n=`http://127.0.0.1:${o.port}${K}`,s=await p(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:n,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(s.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(s.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(s.body,`the panel refused the login (${s.status})`)}};let i=typeof s.body.authorize_url=="string"?s.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};k(e,{kind:"browser",url:i});let a=await be(o.waitForCode(r,e.signal),e.timeoutMs),c=await p(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:s.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(c.body,`the panel refused the exchange (${c.status})`)}};let u=A(c.body);return u?{ok:!0,result:{ok:!0,token:u}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}finally{o?.close()}}async function ke(e){let t=e.fingerprintId??L(),r=e.clientInfo??T(),o=R(t,r);try{let n=await p(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:t,clientInfo:r,...o},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(n.status===401)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not recognise this build as the HowToCode CLI \u2014 update it with `npm install -g howtocode@latest`"}};if(n.status===429)return{ok:!1,terminal:!0,result:{ok:!1,message:`too many sign-in attempts from this machine right now.${n.retryAfterSeconds?` Try again in ${Math.ceil(n.retryAfterSeconds/60)} minute(s).`:""}`}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(n.body,`the panel refused the login (${n.status})`)}};let s=n.body.data??{},i=d(n.body.login_url,s.login_url),a=d(n.body.code,s.code)??(i?me(i):void 0),c=d(n.body.secret,s.secret);return!i||!a?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:c?(k(e,{kind:"browser",url:i}),await D(e,a,c)):(k(e,{kind:"browser",url:i}),await D(e,a,void 0))}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}}async function D(e,t,r){let o=e.pollIntervalMs??G,n=Date.now()+e.timeoutMs;for(;Date.now()<n;){await w(o,e.signal);let s=new URLSearchParams(r?{code:t,secret:r}:{code:t});s.set("capability","device-refresh");let i=await ge(e.fetchImpl,`${e.panel}/api/auth/cli/status?${s}`,e.signal);if(i.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};if(i.status===403)return{ok:!1,terminal:!0,result:{ok:!1,message:"the panel rejected this poll \u2014 run /connect again"}};if(i.status===429){let u=Math.min(Math.max(i.retryAfterSeconds??5,1)*1e3,3e4);await w(u,e.signal);continue}let a=A(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:pe(i.body)}};if(d(i.body.data?.status,i.body.status)==="expired")return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in link expired before it was approved"}};if(i.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(i.body,`the panel refused the poll (${i.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}async function we(e){let t=e.pollIntervalMs??G;try{let r=await p(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(r.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(r.status>=400)return{ok:!1,message:m(r.body,`the panel refused the request (${r.status})`)};let o=typeof r.body.device_code=="string"?r.body.device_code:"",n=typeof r.body.user_code=="string"?r.body.user_code:"",s=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!o||!n)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:n,url:s});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await p(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:o},e.signal);if(a.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let c=typeof a.body.status=="string"?a.body.status:"";if(c==="pending")continue;if(c==="slow_down"){await w(t,e.signal);continue}if(c==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(c==="expired")return{ok:!1,message:"the code expired; run /connect again"};let u=A(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:m(a.body,`the panel refused the poll (${a.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}}function be(e,t){return new Promise((r,o)=>{let n=setTimeout(()=>o(new Error("the sign-in was not finished in time")),t);e.then(s=>{clearTimeout(n),r(s)},s=>{clearTimeout(n),o(s)})})}function w(e,t){return new Promise((r,o)=>{let n=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(n),o(new Error("cancelled"))},{once:!0})})}function b(e){return ve(e,"cli-credentials.json")}var _e=300*1e3;function Ie(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-_e>t:!1}function Le(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Ge(e){let t=b(e);if(!z(t))return;let r;try{r=JSON.parse(ye(t,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let o=r,n=typeof o.accessToken=="string"?o.accessToken.trim():"",s=typeof o.refreshToken=="string"?o.refreshToken.trim():"",i=typeof o.deviceId=="string"?o.deviceId.trim():"";if(!(!n||!s||!i))return{accessToken:n,accessExpiresAt:W(o.accessExpiresAt),refreshToken:s,deviceId:i,refreshExpiresAt:W(o.refreshExpiresAt)}}function Ae(e,t){try{return P(b(e),`${JSON.stringify(t,null,2)}
1
+ import{g as T,j as R}from"./chunk-DQZCH2E4.js";import{a as P}from"./chunk-UTYFLLSM.js";import{existsSync as z,readFileSync as ye,rmSync as xe}from"node:fs";import{join as ve}from"node:path";import{createHash as q,randomBytes as J}from"node:crypto";import{createServer as ne}from"node:http";import{execFileSync as X}from"node:child_process";import{createHmac as Q}from"node:crypto";import{readFileSync as ee}from"node:fs";import{arch as F,cpus as M,hostname as N,platform as v,userInfo as O}from"node:os";var te="howtocode-cli-hwid-v1";function x(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function $(e,t){try{let r=X(e,t,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});return r.trim().length>0?r.trim():void 0}catch{return}}function re(){let e=v();if(e==="linux"){let t=x("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=x("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let o=x("/sys/class/dmi/id/product_uuid");return o?{value:o,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=$("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"])?.match(/MachineGuid\s+REG_SZ\s+(\S+)/i);return r?.[1]?{value:r[1],source:"windows-machine-guid",strong:!0}:void 0}if(e==="darwin"){let r=$("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function H(){let e=re(),t=e?.value??[N(),v(),F(),O().username].join("\0"),r=e?.source??"hostname";return{id:Q("sha256",te).update(t).digest("hex").slice(0,32),source:r,strong:e?.strong??!1}}function U(e){return[e.id,e.source,N(),v(),F(),O().username,String(M().length),M()[0]?.model??""]}var _="https://howtofix.id",se=300*1e3,G=3e3,K="/callback";function I(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return I(J(32))}function ie(e){return I(q("sha256").update(e).digest())}function ae(){return I(J(16))}var ce="howtocode-cli-",ue="x-howtocode-client",le="cli";function L(e){let t=e??U(H());return ce+q("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function de(){return{"content-type":"application/json",[ue]:le}}var fe=()=>new Promise((e,t)=>{let r=ne();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let{port:o}=r.address();e({port:o,close:()=>r.close(),waitForCode:(n,s)=>new Promise((i,a)=>{let c=(l,f)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){f.writeHead(404).end("not found");return}let y=(V,Z)=>f.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),S=h.searchParams.get("error")??"",E=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(S){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${S}`));return}if(!E||Y!==n){y("This callback did not belong to the login","You can close this tab."),u(new Error("the callback carried the wrong state"));return}y("Signed in","You can close this tab and go back to HowToCode."),u(void 0,E)},u=(l,f)=>{r.off("request",c),s?.removeEventListener("abort",g),l?a(l):i(f)},g=()=>u(new Error("cancelled"));s?.addEventListener("abort",g,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function p(e,t,r,o){let n=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:o}),s={};try{s=await n.json()}catch{}let i=Number(n.headers?.get?.("retry-after"));return{status:n.status,body:s,retryAfterSeconds:Number.isFinite(i)&&i>0?i:void 0}}function d(...e){for(let t of e)if(typeof t=="string"&&t.trim()!=="")return t.trim()}function j(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}function me(e){try{let t=new URL(e).searchParams.get("code");return t&&t.trim()!==""?t.trim():void 0}catch{return}}async function ge(e,t,r){let o=await e(t,{headers:de(),signal:r}),n={};try{n=await o.json()}catch{}let s=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(s)&&s>0?s:void 0}}function A(e){let t=e.data,r=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let o of r)if(typeof o=="string"&&o.trim().startsWith("sk-"))return o.trim()}function pe(e){let t=e.data,r=d(e.token,t?.token),o=d(e.refresh_token,t?.refresh_token),n=d(e.device_id,t?.device_id);if(!r||!o||!n)return;let s=j(e.access_expires_at,t?.access_expires_at),i=j(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:s,refreshToken:o,deviceId:n,refreshExpiresAt:i}}function m(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function He(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??_).replace(/\/+$/,""),o=e.timeoutMs??se,n={...e,panel:r,fetchImpl:t,timeoutMs:o},s=await ke(n);if(s.ok||s.terminal)return s.result;let i=await he(n);if(i.ok||i.terminal)return i.result;let a=await we(n);return a.ok?a:{ok:!1,message:`${s.result.ok?"":s.result.message}; ${i.result.ok?"":i.result.message}; ${a.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${r}/keys instead.`}}async function he(e){let t=oe(),r=ae(),o;try{o=await(e.loopback??fe)();let n=`http://127.0.0.1:${o.port}${K}`,s=await p(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:n,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(s.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(s.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(s.body,`the panel refused the login (${s.status})`)}};let i=typeof s.body.authorize_url=="string"?s.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};k(e,{kind:"browser",url:i});let a=await be(o.waitForCode(r,e.signal),e.timeoutMs),c=await p(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:s.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(c.body,`the panel refused the exchange (${c.status})`)}};let u=A(c.body);return u?{ok:!0,result:{ok:!0,token:u}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}finally{o?.close()}}async function ke(e){let t=e.fingerprintId??L(),r=e.clientInfo??T(),o=R(t,r);try{let n=await p(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:t,clientInfo:r,...o},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(n.status===401)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not recognise this build as the HowToCode CLI \u2014 update it with `npm install -g howtocode@latest`"}};if(n.status===429)return{ok:!1,terminal:!0,result:{ok:!1,message:`too many sign-in attempts from this machine right now.${n.retryAfterSeconds?` Try again in ${Math.ceil(n.retryAfterSeconds/60)} minute(s).`:""}`}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(n.body,`the panel refused the login (${n.status})`)}};let s=n.body.data??{},i=d(n.body.login_url,s.login_url),a=d(n.body.code,s.code)??(i?me(i):void 0),c=d(n.body.secret,s.secret);return!i||!a?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:c?(k(e,{kind:"browser",url:i}),await D(e,a,c)):(k(e,{kind:"browser",url:i}),await D(e,a,void 0))}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}}async function D(e,t,r){let o=e.pollIntervalMs??G,n=Date.now()+e.timeoutMs;for(;Date.now()<n;){await w(o,e.signal);let s=new URLSearchParams(r?{code:t,secret:r}:{code:t});s.set("capability","device-refresh");let i=await ge(e.fetchImpl,`${e.panel}/api/auth/cli/status?${s}`,e.signal);if(i.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};if(i.status===403)return{ok:!1,terminal:!0,result:{ok:!1,message:"the panel rejected this poll \u2014 run /connect again"}};if(i.status===429){let u=Math.min(Math.max(i.retryAfterSeconds??5,1)*1e3,3e4);await w(u,e.signal);continue}let a=A(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:pe(i.body)}};if(d(i.body.data?.status,i.body.status)==="expired")return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in link expired before it was approved"}};if(i.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(i.body,`the panel refused the poll (${i.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}async function we(e){let t=e.pollIntervalMs??G;try{let r=await p(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(r.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(r.status>=400)return{ok:!1,message:m(r.body,`the panel refused the request (${r.status})`)};let o=typeof r.body.device_code=="string"?r.body.device_code:"",n=typeof r.body.user_code=="string"?r.body.user_code:"",s=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!o||!n)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:n,url:s});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await p(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:o},e.signal);if(a.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let c=typeof a.body.status=="string"?a.body.status:"";if(c==="pending")continue;if(c==="slow_down"){await w(t,e.signal);continue}if(c==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(c==="expired")return{ok:!1,message:"the code expired; run /connect again"};let u=A(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:m(a.body,`the panel refused the poll (${a.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}}function be(e,t){return new Promise((r,o)=>{let n=setTimeout(()=>o(new Error("the sign-in was not finished in time")),t);e.then(s=>{clearTimeout(n),r(s)},s=>{clearTimeout(n),o(s)})})}function w(e,t){return new Promise((r,o)=>{let n=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(n),o(new Error("cancelled"))},{once:!0})})}function b(e){return ve(e,"cli-credentials.json")}var _e=300*1e3;function Ie(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-_e>t:!1}function Le(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Ge(e){let t=b(e);if(!z(t))return;let r;try{r=JSON.parse(ye(t,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let o=r,n=typeof o.accessToken=="string"?o.accessToken.trim():"",s=typeof o.refreshToken=="string"?o.refreshToken.trim():"",i=typeof o.deviceId=="string"?o.deviceId.trim():"";if(!(!n||!s||!i))return{accessToken:n,accessExpiresAt:W(o.accessExpiresAt),refreshToken:s,deviceId:i,refreshExpiresAt:W(o.refreshExpiresAt)}}function Ae(e,t){try{return P(b(e),`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384}),!0}catch{return!1}}function Ce(e){try{let t=b(e);z(t)&&xe(t,{force:!0})}catch{}}function W(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function Se(e,t){let r=(t?.panelUrl??_).replace(/\/+$/,""),o=t?.fetchImpl??fetch,n=t?.timeoutMs??15e3,s=new AbortController,i=setTimeout(()=>s.abort(),n);try{let a=await o(`${r}/api/auth/cli/refresh`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({device_id:e.deviceId,refresh_token:e.refreshToken,fingerprint_id:L()}),signal:s.signal}),c=await a.json().catch(()=>({}));if(a.status===401||a.status===403)return{ok:!1,terminal:!0,message:"this sign-in is no longer valid; run /connect to sign in again"};if(!a.ok)return{ok:!1,terminal:!1,message:`the panel refused the renewal (${a.status})`};let u=c.data??{},g=C(c.token,u.token),l=C(c.refresh_token,u.refresh_token),f=C(c.device_id,u.device_id)??e.deviceId;return!g||!l?{ok:!1,terminal:!1,message:"the panel did not return a renewed credential"}:{ok:!0,terminal:!1,credential:{accessToken:g,accessExpiresAt:B(c.access_expires_at,u.access_expires_at),refreshToken:l,deviceId:f,refreshExpiresAt:B(c.refresh_expires_at,u.refresh_expires_at)}}}catch(a){return{ok:!1,terminal:!1,message:a instanceof Error&&a.name==="AbortError"?`the panel did not answer within ${Math.round(n/1e3)}s`:"could not reach the panel"}}finally{clearTimeout(i)}}function C(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim()}function B(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}async function Ke(e,t,r){let o=r?.now??Date.now();if(Ie(t,o)||!Le(t,o))return{credential:t,renewed:!1,terminal:!1};let n=await Se(t,r);if(!n.ok||!n.credential)return n.terminal&&Ce(e),{credential:t,renewed:!1,terminal:n.terminal,message:n.message};let s=Ae(e,n.credential);return{credential:n.credential,renewed:!0,terminal:!1,message:s?void 0:`the renewed sign-in could not be saved to ${b(e)}`}}export{H as a,_ as b,He as c,b as d,_e as e,Ie as f,Le as g,Ge as h,Ae as i,Ce as j,Se as k,Ke as l};
@@ -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,2 +1,2 @@
1
- import{b as o}from"./chunk-TPAFM3UD.js";import{createPrivateKey as p,createPublicKey as f,createHash as l,randomBytes as d,sign as y}from"node:crypto";import{arch as c,cpus as m,hostname as I,platform as s}from"node:os";var a="hf-cli-1",C="MC4CAQAwBQYDK2VwBCIEIDmKoNgInS7oDpncee1d1+Mnci1R/q4aE5xxHeCKq4Dc",x="howtocode-cli-auth-v1",i;function u(){return i||(i=p({key:Buffer.from(C,"base64"),format:"der",type:"pkcs8"})),i}function g(){return f(u())}function K(t,e,n,r){return Buffer.from([x,t,e,n,r].join(`
1
+ import{b as o}from"./chunk-SBWZZCV5.js";import{createPrivateKey as p,createPublicKey as f,createHash as l,randomBytes as d,sign as y}from"node:crypto";import{arch as c,cpus as m,hostname as I,platform as s}from"node:os";var a="hf-cli-1",C="MC4CAQAwBQYDK2VwBCIEIDmKoNgInS7oDpncee1d1+Mnci1R/q4aE5xxHeCKq4Dc",x="howtocode-cli-auth-v1",i;function u(){return i||(i=p({key:Buffer.from(C,"base64"),format:"der",type:"pkcs8"})),i}function g(){return f(u())}function K(t,e,n,r){return Buffer.from([x,t,e,n,r].join(`
2
2
  `),"utf8")}function h(){return d(16).toString("hex")}var E="tQ91uspGl0sw5Y8x+soLYnFNX6a9vEzSzCuuvalzdKk=";function P(){let t=g().export({format:"der",type:"spki"});return t.subarray(t.length-32).toString("base64")===E}function N(){let t=g().export({format:"der",type:"spki"});return l("sha256").update(t).digest("hex").slice(0,16)}function $(){let e=(m()[0]?.model??"").replace(/\s+/g," ").trim(),n=I(),r=e?`${n} (${s()}/${c()}, ${e})`:`${n} (${s()}/${c()})`;return`CLI (${o}, ${r})`}var k="X-HowToCode-Client";function A(){return`CLI (${o})`}function B(t,e){let n=h(),r=y(null,K(a,t,e,n),u());return{keyId:a,nonce:n,signature:r.toString("base64")}}export{a,g as b,K as c,h as d,P as e,N as f,$ as g,k as h,A as i,B as j};
@@ -1,47 +1,47 @@
1
- import{$ as We,B as De,C as Ce,E as R,F as H,Fa as ot,H as B,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 N,b as M,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 q,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 x,u as Re,ua as Qe,va as et,w as Oe,x as W,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-ZXU4RS2P.js";import{h as pe,l as fe}from"./chunk-XDOA2DID.js";import{t as me}from"./chunk-ZJL4OEXX.js";import"./chunk-7LA2AMZB.js";import"./chunk-CPGMEFX5.js";import{b as G,c as ie,d as ae}from"./chunk-TPAFM3UD.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 io}from"node:os";import{createAgentSession as ao,createCodemodeExtension as co,createMcpExtension as lo,createToolSearchExtension as uo,DefaultResourceLoader as po,ProjectTrustStore as fo,SessionManager as Z,SettingsManager as mo}from"@netrodev/hxf-coding-agent";import{existsSync as Ft,readFileSync as Lt}from"node:fs";import{join as Bt}from"node:path";var it=Bt(S,"APPEND_SYSTEM.md"),Ut=["<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
- `),Gt=16*1024;function Wt(e){try{if(!Ft(e))return;let t=Lt(e,"utf8").trim();return!t||Buffer.byteLength(t,"utf8")>Gt?void 0:t}catch{return}}function at(e,t){let s=[t?e:`${e}
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-G3RLGCT7.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-XZBFNLPM.js";import{h as pe,l as fe}from"./chunk-AMYTGLTF.js";import"./chunk-7LA2AMZB.js";import"./chunk-DQZCH2E4.js";import{b as W,c as ie,d as ae}from"./chunk-SBWZZCV5.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
+ `),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
- ${Ut}`],n=Wt(it);return n&&s.push(`# Standing instructions from ${it}
5
- ${n}`),s}function Ht(e){return e.replace(/operating inside hxf, a coding agent harness/gi,"operating as HowToCode, a coding agent harness").replace(/^HowToFix documentation \(read only when the user asks about[^\n]*\):?$/gim,"Harness documentation (internal reference; the user is never told the harness name):").replace(/\bhxf itself\b/gi,"the harness itself").replace(/^- When reading hxf docs or examples/m,"- When reading harness docs or examples").replace(/^- When working on hxf topics/m,"- When working on harness topics").replace(/^- Always read hxf \.md files/m,"- Always read the harness .md files").replace(/\bhxf packages\b/gi,"harness packages").replace(/\bhxf \.md files\b/gi,"harness .md files").replace(/\bhxf docs\b/gi,"harness docs").replace(/^-\s*You can inspect HXF_\* environment variables/m,"- You can inspect the harness's environment variables")}var qt=["preamble","rules","docs","addendum"];function zt(e){if(!e)return;let t=!1,s={...e};for(let n of qt){let o=s[n];if(typeof o!="string")continue;let r=Ht(o);r!==o&&(s[n]=r,t=!0)}return t?s:void 0}function ct(){return e=>{e.on("context_with_system",async t=>{let s=t.messages[0];if(!s||s.role!=="system")return;let n=zt(s.sections);return n?{messages:t.messages.map(r=>r===s?{...s,sections:n}:r)}:void 0})}}var _={hooks:{}},F;function lt(){return e=>{let t=we(ge);_=t.config,F=void 0,be(),e.on("session_start",async(s,n)=>{for(let a of t.diagnostics)n.ui.notify(`hooks.json: ${a.message}`,"warning");let{outcome:o,ran:r}=await A(_,"SessionStart",{hook_event_name:"SessionStart",cwd:n.cwd},{cwd:n.cwd});o.context&&(F=o.context),o.error&&n.ui.notify(`SessionStart hook: ${o.error}`,"warning"),r&&F&&n.ui.notify(`SessionStart hooks added ${F.length} characters of context`,"info")}),e.on("input",async(s,n)=>{if(!_.hooks.UserPromptSubmit)return;let o={hook_event_name:"UserPromptSubmit",cwd:n.cwd,prompt:s.text},{outcome:r}=await A(_,"UserPromptSubmit",o,{cwd:n.cwd});if(r.error&&n.ui.notify(`UserPromptSubmit hook: ${r.error}`,"warning"),r.block)return n.ui.notify(r.reason??"blocked by a hook","warning"),{action:"handled"};if(r.context)return{action:"transform",text:`${s.text}
4
+ ${Gt}`],n=Ht(it);return n&&s.push(`# Standing instructions from ${it}
5
+ ${n}`),s}function qt(e){return e.replace(/operating inside hxf, a coding agent harness/gi,"operating as HowToCode, a coding agent harness").replace(/^HowToFix documentation \(read only when the user asks about[^\n]*\):?$/gim,"Harness documentation (internal reference; the user is never told the harness name):").replace(/\bhxf itself\b/gi,"the harness itself").replace(/^- When reading hxf docs or examples/m,"- When reading harness docs or examples").replace(/^- When working on hxf topics/m,"- When working on harness topics").replace(/^- Always read hxf \.md files/m,"- Always read the harness .md files").replace(/\bhxf packages\b/gi,"harness packages").replace(/\bhxf \.md files\b/gi,"harness .md files").replace(/\bhxf docs\b/gi,"harness docs").replace(/^-\s*You can inspect HXF_\* environment variables/m,"- You can inspect the harness's environment variables")}var zt=["preamble","rules","docs","addendum"];function Zt(e){if(!e)return;let t=!1,s={...e};for(let n of zt){let o=s[n];if(typeof o!="string")continue;let r=qt(o);r!==o&&(s[n]=r,t=!0)}return t?s:void 0}function ct(){return e=>{e.on("context_with_system",async t=>{let s=t.messages[0];if(!s||s.role!=="system")return;let n=Zt(s.sections);return n?{messages:t.messages.map(r=>r===s?{...s,sections:n}:r)}:void 0})}}var _={hooks:{}},L;function lt(){return e=>{let t=we(ge);_=t.config,L=void 0,be(),e.on("session_start",async(s,n)=>{for(let a of t.diagnostics)n.ui.notify(`hooks.json: ${a.message}`,"warning");let{outcome:o,ran:r}=await A(_,"SessionStart",{hook_event_name:"SessionStart",cwd:n.cwd},{cwd:n.cwd});o.context&&(L=o.context),o.error&&n.ui.notify(`SessionStart hook: ${o.error}`,"warning"),r&&L&&n.ui.notify(`SessionStart hooks added ${L.length} characters of context`,"info")}),e.on("input",async(s,n)=>{if(!_.hooks.UserPromptSubmit)return;let o={hook_event_name:"UserPromptSubmit",cwd:n.cwd,prompt:s.text},{outcome:r}=await A(_,"UserPromptSubmit",o,{cwd:n.cwd});if(r.error&&n.ui.notify(`UserPromptSubmit hook: ${r.error}`,"warning"),r.block)return n.ui.notify(r.reason??"blocked by a hook","warning"),{action:"handled"};if(r.context)return{action:"transform",text:`${s.text}
6
6
 
7
7
  ${r.context}`}}),e.on("tool_call",async(s,n)=>{if(!_.hooks.PreToolUse)return;let o={hook_event_name:"PreToolUse",cwd:n.cwd,tool_name:s.toolName,tool_input:s.input},{outcome:r}=await A(_,"PreToolUse",o,{cwd:n.cwd});if(r.error&&n.ui.notify(`PreToolUse hook: ${r.error}`,"warning"),r.block)return{block:!0,reason:r.reason??"blocked by a hook"};if(r.updatedInput){let i=e.getAllTools().find(u=>u.name===s.toolName)?.parameters;if(!i)n.ui.notify(`PreToolUse hook rewrote \`${s.toolName}\`, but no schema is known for that tool \u2014 the rewrite was ignored`,"warning");else{let u=he(i,r.updatedInput);u?n.ui.notify(`PreToolUse hook rewrite ignored \u2014 ${u}`,"warning"):Object.assign(s.input,r.updatedInput)}}}),e.on("tool_result",async(s,n)=>{if(!_.hooks.PostToolUse)return;let o=s.content.map(i=>i.type==="text"?i.text:"").join(`
8
8
  `),r={hook_event_name:"PostToolUse",cwd:n.cwd,tool_name:s.toolName,tool_input:s.input,tool_result:o,tool_is_error:s.isError},{outcome:a}=await A(_,"PostToolUse",r,{cwd:n.cwd});if(a.error&&n.ui.notify(`PostToolUse hook: ${a.error}`,"warning"),!!a.context)return{content:[...s.content,{type:"text",text:`
9
- [hook] ${a.context}`}],structuredContent:s.structuredContent}}),e.on("context_with_system",async s=>{if(!F)return;let n=s.messages[0];if(!n||n.role!=="system")return;let o=`${N(n.content)}
9
+ [hook] ${a.context}`}],structuredContent:s.structuredContent}}),e.on("context_with_system",async s=>{if(!L)return;let n=s.messages[0];if(!n||n.role!=="system")return;let o=`${M(n.content)}
10
10
 
11
- ${F}`;return{messages:s.messages.map(a=>a===n?{...n,content:M(n.content,o)}:a)}}),e.on("session_before_compact",async(s,n)=>{if(!_.hooks.PreCompact)return;let{outcome:o}=await A(_,"PreCompact",{hook_event_name:"PreCompact",cwd:n.cwd,compact_reason:s.reason},{cwd:n.cwd});o.error&&n.ui.notify(`PreCompact hook: ${o.error}`,"warning")}),e.on("session_shutdown",async(s,n)=>{if(!_.hooks.SessionEnd)return;let{outcome:o}=await A(_,"SessionEnd",{hook_event_name:"SessionEnd",cwd:n.cwd,reason:s.reason},{cwd:n.cwd});o.error&&n.ui.notify(`SessionEnd hook: ${o.error}`,"warning")}),e.on("agent_settled",async(s,n)=>{if(!_.hooks.Stop)return;let{outcome:o}=await A(_,"Stop",{hook_event_name:"Stop",cwd:n.cwd},{cwd:n.cwd});o.error&&n.ui.notify(`Stop hook: ${o.error}`,"warning")})}}var Zt=new Set(["bash","grep","find","ls","bash_output","powershell"]),Kt=new Set(["bash","bash_output","powershell"]),Xt=40,Yt=12,Vt=8,ut=6;function Jt(e,t){let s=e.trim();return!!(s===""||/^[-=*_~+#]{3,}$/.test(s)||t!==void 0&&e===t)}function dt(e){return e.replace(/\d+/g,"#").trimEnd()}function Qt(e){let t=[],s=0,n=0;for(;n<e.length;){let o=dt(e[n]);if(o===""||!/\d/.test(e[n])){t.push(e[n]),n+=1;continue}let r=n+1;for(;r<e.length&&dt(e[r])===o&&/\d/.test(e[r]);)r+=1;let a=r-n;if(a>=ut)t.push(e[n]),t.push(` \u2026 ${a-2} more line${a-2===1?"":"s"} of the same shape \u2026`),t.push(e[r-1]),s+=1;else for(let i=n;i<r;i+=1)t.push(e[i]);n=r}return{out:t,collapsed:s}}function en(e,t,s={}){if(t?.truncated)return;let n=e.split(`
12
- `);if(n.length<Xt)return;let o=[],r=0;for(let g=0;g<n.length;g+=1){if(Jt(n[g],o[o.length-1])){if(n[g].trim()===""&&o[o.length-1]?.trim()!==""){o.push("");continue}r+=1;continue}o.push(n[g])}let a=s.toolName===void 0||Kt.has(s.toolName),{out:i,collapsed:u}=a?Qt(o):{out:o,collapsed:0},p=s.head??Yt,f=s.tail??Vt,c=i,d=0;if(i.length>p+f+ut&&(d=i.length-p-f,c=[...i.slice(0,p),` \u2026 ${d} line${d===1?"":"s"} omitted (${p} kept from the top, ${f} from the end) \u2026`,...i.slice(i.length-f)]),!(r+u===0&&d===0))return{text:c.join(`
13
- `),stats:{before:n.length,after:c.length,collapsed:u}}}function pt(e){return t=>{t.on("tool_result",s=>{if(!e.enabled()||s.isError||!Zt.has(s.toolName))return;let n=s.content.find(i=>i.type==="text");if(!n||n.type!=="text")return;let o=s.details,r=en(n.text,o,{toolName:s.toolName});return r?{content:s.content.map(i=>i===n?{type:"text",text:r.text}:i)}:void 0})}}import{readdirSync as tn,readFileSync as nn,statSync as on}from"node:fs";import{extname as sn,join as ft,relative as rn,resolve as an,sep as mt}from"node:path";import{Type as P}from"@netrodev/hxf-ai";import{defineTool as cn}from"@netrodev/hxf-coding-agent";var ln=new Set(["node_modules",".git","dist","build","out","coverage","vendor","target","__pycache__",".venv","venv",".next",".turbo",".cache"]),O={".ts":{kind:"ts",patterns:[/^\s*export\s+(?:default\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/gm,/^\s*export\s+(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/gm,/^\s*export\s+(?:interface|type)\s+([A-Za-z_$][\w$]*)/gm,/^\s*export\s+const\s+([A-Za-z_$][\w$]*)/gm,/^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/gm,/^\s*(?:export\s+)?class\s+([A-Za-z_$][\w$]*)/gm]},".tsx":{kind:"tsx",patterns:[]},".js":{kind:"js",patterns:[]},".mjs":{kind:"js",patterns:[]},".go":{kind:"go",patterns:[/^func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/gm,/^type\s+([A-Za-z_]\w*)\s+(?:struct|interface)/gm]},".py":{kind:"py",patterns:[/^(?:async\s+)?def\s+([A-Za-z_]\w*)/gm,/^class\s+([A-Za-z_]\w*)/gm]},".rs":{kind:"rs",patterns:[/^\s*(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)/gm,/^\s*(?:pub\s+)?(?:struct|enum|trait)\s+([A-Za-z_]\w*)/gm]}};O[".tsx"].patterns=O[".ts"].patterns;O[".js"].patterns=O[".ts"].patterns;O[".mjs"].patterns=O[".ts"].patterns;var dn=512*1024,un=12;function pn(e,t){let s=O[t];if(!s)return[];let n=new Set,o=[];for(let r of s.patterns){r.lastIndex=0;for(let a of e.matchAll(r)){let i=a[1];i&&!n.has(i)&&(n.add(i),o.push(i))}}return o}function fn(e,t){let s=new Set,n=o=>{o&&(o.startsWith("./")||o.startsWith("../"))&&s.add(o)};if(t===".ts"||t===".tsx"||t===".js"||t===".mjs"){for(let o of e.matchAll(/(?:from|require\()\s*["']([^"']+)["']/g))n(o[1]);for(let o of e.matchAll(/^\s*import\s+["']([^"']+)["']/gm))n(o[1])}else if(t===".go")for(let o of e.matchAll(/^\s*(?:[\w.]+\s+)?"([^"]+)"/gm))n(o[1]);else if(t===".py")for(let o of e.matchAll(/^\s*from\s+(\.+[\w.]*)\s+import/gm)){let r=o[1].replace(/\./g,"/");n(r.startsWith("/")?`.${r}`:`./${r}`)}else if(t===".rs")for(let o of e.matchAll(/^\s*use\s+(?:crate|super|self)::([\w:]+)/gm))n(`./${o[1].split("::").join("/")}`);return[...s]}function mn(e,t,s){let n=e.split("/").slice(0,-1).join("/"),o=ft(n,t).split(mt).join("/").replace(/^\.\//,"");return[o,`${o}.ts`,`${o}.tsx`,`${o}.js`,`${o}.mjs`,`${o}.go`,`${o}.py`,`${o}.rs`,`${o}/index.ts`,`${o}/index.tsx`,`${o}/index.js`,`${o}/mod.rs`,`${o}.py`].find(a=>s.has(a))}function gn(e,t="."){let s=[],n=(o,r)=>{if(r>un)return;let a;try{a=tn(o,{withFileTypes:!0})}catch{return}for(let i of a){let u=ft(o,i.name);if(i.isDirectory()){if(ln.has(i.name)||i.name.startsWith("."))continue;n(u,r+1);continue}let p=sn(i.name);if(O[p])try{if(on(u).size>dn)continue;let f=nn(u,"utf8"),c=rn(e,u).split(mt).join("/");s.push({path:c,symbols:pn(f,p),imports:fn(f,p)})}catch{}}};return n(an(e,t),0),s}function hn(e,t){if(e.length===0)return[];let s=new Set(e.map(c=>c.path)),n=new Map(e.map((c,d)=>[c.path,d])),o=e.map(()=>[]),r=e.map(()=>[]);e.forEach((c,d)=>{for(let l of c.imports){let g=mn(c.path,l,s);if(!g||g===c.path)continue;let y=n.get(g);y!==void 0&&(o[d].push(y),r[y].push(d))}});let a=e.length,i=t?.trim().toLowerCase(),u=e.map(c=>i&&`${c.path} ${c.symbols.join(" ")}`.toLowerCase().includes(i)?4/a:1/a),p=u.reduce((c,d)=>c+d,0),f=e.map((c,d)=>u[d]/p);for(let c=0;c<20;c++){let d=e.map((l,g)=>.15*(u[g]/p));for(let l=0;l<a;l++){if(o[l].length===0){for(let g=0;g<a;g++)d[g]+=.85*f[l]/a;continue}for(let g of o[l])d[g]+=.85*f[l]/o[l].length}f=d}return e.map((c,d)=>({file:c,score:f[d],match:i?`${c.path} ${c.symbols.join(" ")}`.toLowerCase().includes(i):!1})).sort((c,d)=>Number(d.match)-Number(c.match)||d.score-c.score||c.file.path.localeCompare(d.file.path)).map(c=>c.file)}function wn(e,t={}){let n=Math.max(200,Math.min(8e3,t.budget??1200))*4,o=hn(e,t.query),r=[],a=0;for(let u of o){let p=u.symbols.slice(0,8).join(", "),f=p?`${u.path}: ${p}`:`${u.path}`;if(a+f.length+1>n)break;r.push(f),a+=f.length+1}if(r.length===0)return"(no source files found)";let i=o.length-r.length;return i>0&&r.push(`\u2026 ${i} more file${i===1?"":"s"} not shown`),r.join(`
14
- `)}var gt;function ht(e){gt=e}var wt=cn({name:"repo_map",label:"repo_map",description:"A ranked outline of the repository: files by importance with their top declarations. Use it to find where something lives before reading files, instead of listing directories.",promptSnippet:"repo_map: ranked file outline of the project",parameters:P.Object({path:P.Optional(P.String({description:"Subdirectory to map, relative to the project root"})),query:P.Optional(P.String({description:"Keyword to bias the ranking, e.g. 'billing'"})),budget:P.Optional(P.Number({description:"Token budget, default 1200"}))}),async execute(e,t){let s=gt?.()??process.cwd(),n=gn(s,t.path??".");return{content:[{type:"text",text:wn(n,{budget:t.budget,query:t.query})}],details:{files:n.length}}}});function ee(){return{consecutiveFailures:0,tripped:!1}}function bn(e,t){return t==="manual"?!1:e.consecutiveFailures>=3}function yn(e,t){if(t)return e;let s=e.consecutiveFailures+1;return{consecutiveFailures:s,tripped:e.tripped||s>=3}}function xn(){return ee()}function kn(e){return[`Auto-compaction failed ${e.consecutiveFailures} times in a row, so it is switched off for this session.`,"The context is over the limit and compaction cannot recover it. Start a new session, or switch to a model with a larger context window.","Manual /compact is still allowed."].join(" ")}var I=ee();function bt(){return e=>{e.on("session_start",async()=>{I=ee()}),e.on("session_compact",async()=>{I=xn()}),e.on("session_compact_failed",async(t,s)=>{let n=I;I=yn(I,t.aborted),!n.tripped&&I.tripped&&s?.ui&&s.ui.notify(kn(I),"warning")}),e.on("session_before_compact",async t=>{if(bn(I,t.reason))return{cancel:!0}})}}function Sn(e){R(B(e))}function yt(e){return`budget exhausted (${e.budget??"default"} continuations)`}function xt(){return e=>{e.on("session_start",async(t,s)=>{Sn(s)}),e.on("context_with_system",async(t,s)=>{let n=B(s);if(R(n),!n||n.status!=="active")return;let o=t.messages[0];if(!o||o.role!=="system")return;let r=`${N(o.content)}
11
+ ${L}`;return{messages:s.messages.map(a=>a===n?{...n,content:F(n.content,o)}:a)}}),e.on("session_before_compact",async(s,n)=>{if(!_.hooks.PreCompact)return;let{outcome:o}=await A(_,"PreCompact",{hook_event_name:"PreCompact",cwd:n.cwd,compact_reason:s.reason},{cwd:n.cwd});o.error&&n.ui.notify(`PreCompact hook: ${o.error}`,"warning")}),e.on("session_shutdown",async(s,n)=>{if(!_.hooks.SessionEnd)return;let{outcome:o}=await A(_,"SessionEnd",{hook_event_name:"SessionEnd",cwd:n.cwd,reason:s.reason},{cwd:n.cwd});o.error&&n.ui.notify(`SessionEnd hook: ${o.error}`,"warning")}),e.on("agent_settled",async(s,n)=>{if(!_.hooks.Stop)return;let{outcome:o}=await A(_,"Stop",{hook_event_name:"Stop",cwd:n.cwd},{cwd:n.cwd});o.error&&n.ui.notify(`Stop hook: ${o.error}`,"warning")})}}var Kt=new Set(["bash","grep","find","ls","bash_output","powershell"]),Xt=new Set(["bash","bash_output","powershell"]),Yt=40,Vt=12,Jt=8,ut=6;function Qt(e,t){let s=e.trim();return!!(s===""||/^[-=*_~+#]{3,}$/.test(s)||t!==void 0&&e===t)}function dt(e){return e.replace(/\d+/g,"#").trimEnd()}function en(e){let t=[],s=0,n=0;for(;n<e.length;){let o=dt(e[n]);if(o===""||!/\d/.test(e[n])){t.push(e[n]),n+=1;continue}let r=n+1;for(;r<e.length&&dt(e[r])===o&&/\d/.test(e[r]);)r+=1;let a=r-n;if(a>=ut)t.push(e[n]),t.push(` \u2026 ${a-2} more line${a-2===1?"":"s"} of the same shape \u2026`),t.push(e[r-1]),s+=1;else for(let i=n;i<r;i+=1)t.push(e[i]);n=r}return{out:t,collapsed:s}}function tn(e,t,s={}){if(t?.truncated)return;let n=e.split(`
12
+ `);if(n.length<Yt)return;let o=[],r=0;for(let g=0;g<n.length;g+=1){if(Qt(n[g],o[o.length-1])){if(n[g].trim()===""&&o[o.length-1]?.trim()!==""){o.push("");continue}r+=1;continue}o.push(n[g])}let a=s.toolName===void 0||Xt.has(s.toolName),{out:i,collapsed:u}=a?en(o):{out:o,collapsed:0},p=s.head??Vt,f=s.tail??Jt,c=i,d=0;if(i.length>p+f+ut&&(d=i.length-p-f,c=[...i.slice(0,p),` \u2026 ${d} line${d===1?"":"s"} omitted (${p} kept from the top, ${f} from the end) \u2026`,...i.slice(i.length-f)]),!(r+u===0&&d===0))return{text:c.join(`
13
+ `),stats:{before:n.length,after:c.length,collapsed:u}}}function pt(e){return t=>{t.on("tool_result",s=>{if(!e.enabled()||s.isError||!Kt.has(s.toolName))return;let n=s.content.find(i=>i.type==="text");if(!n||n.type!=="text")return;let o=s.details,r=tn(n.text,o,{toolName:s.toolName});return r?{content:s.content.map(i=>i===n?{type:"text",text:r.text}:i)}:void 0})}}import{readdirSync as nn,readFileSync as on,statSync as sn}from"node:fs";import{extname as rn,join as ft,relative as an,resolve as cn,sep as mt}from"node:path";import{Type as j}from"@netrodev/hxf-ai";import{defineTool as ln}from"@netrodev/hxf-coding-agent";var dn=new Set(["node_modules",".git","dist","build","out","coverage","vendor","target","__pycache__",".venv","venv",".next",".turbo",".cache"]),O={".ts":{kind:"ts",patterns:[/^\s*export\s+(?:default\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/gm,/^\s*export\s+(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/gm,/^\s*export\s+(?:interface|type)\s+([A-Za-z_$][\w$]*)/gm,/^\s*export\s+const\s+([A-Za-z_$][\w$]*)/gm,/^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/gm,/^\s*(?:export\s+)?class\s+([A-Za-z_$][\w$]*)/gm]},".tsx":{kind:"tsx",patterns:[]},".js":{kind:"js",patterns:[]},".mjs":{kind:"js",patterns:[]},".go":{kind:"go",patterns:[/^func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/gm,/^type\s+([A-Za-z_]\w*)\s+(?:struct|interface)/gm]},".py":{kind:"py",patterns:[/^(?:async\s+)?def\s+([A-Za-z_]\w*)/gm,/^class\s+([A-Za-z_]\w*)/gm]},".rs":{kind:"rs",patterns:[/^\s*(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)/gm,/^\s*(?:pub\s+)?(?:struct|enum|trait)\s+([A-Za-z_]\w*)/gm]}};O[".tsx"].patterns=O[".ts"].patterns;O[".js"].patterns=O[".ts"].patterns;O[".mjs"].patterns=O[".ts"].patterns;var un=512*1024,pn=12;function fn(e,t){let s=O[t];if(!s)return[];let n=new Set,o=[];for(let r of s.patterns){r.lastIndex=0;for(let a of e.matchAll(r)){let i=a[1];i&&!n.has(i)&&(n.add(i),o.push(i))}}return o}function mn(e,t){let s=new Set,n=o=>{o&&(o.startsWith("./")||o.startsWith("../"))&&s.add(o)};if(t===".ts"||t===".tsx"||t===".js"||t===".mjs"){for(let o of e.matchAll(/(?:from|require\()\s*["']([^"']+)["']/g))n(o[1]);for(let o of e.matchAll(/^\s*import\s+["']([^"']+)["']/gm))n(o[1])}else if(t===".go")for(let o of e.matchAll(/^\s*(?:[\w.]+\s+)?"([^"]+)"/gm))n(o[1]);else if(t===".py")for(let o of e.matchAll(/^\s*from\s+(\.+[\w.]*)\s+import/gm)){let r=o[1].replace(/\./g,"/");n(r.startsWith("/")?`.${r}`:`./${r}`)}else if(t===".rs")for(let o of e.matchAll(/^\s*use\s+(?:crate|super|self)::([\w:]+)/gm))n(`./${o[1].split("::").join("/")}`);return[...s]}function gn(e,t,s){let n=e.split("/").slice(0,-1).join("/"),o=ft(n,t).split(mt).join("/").replace(/^\.\//,"");return[o,`${o}.ts`,`${o}.tsx`,`${o}.js`,`${o}.mjs`,`${o}.go`,`${o}.py`,`${o}.rs`,`${o}/index.ts`,`${o}/index.tsx`,`${o}/index.js`,`${o}/mod.rs`,`${o}.py`].find(a=>s.has(a))}function hn(e,t="."){let s=[],n=(o,r)=>{if(r>pn)return;let a;try{a=nn(o,{withFileTypes:!0})}catch{return}for(let i of a){let u=ft(o,i.name);if(i.isDirectory()){if(dn.has(i.name)||i.name.startsWith("."))continue;n(u,r+1);continue}let p=rn(i.name);if(O[p])try{if(sn(u).size>un)continue;let f=on(u,"utf8"),c=an(e,u).split(mt).join("/");s.push({path:c,symbols:fn(f,p),imports:mn(f,p)})}catch{}}};return n(cn(e,t),0),s}function wn(e,t){if(e.length===0)return[];let s=new Set(e.map(c=>c.path)),n=new Map(e.map((c,d)=>[c.path,d])),o=e.map(()=>[]),r=e.map(()=>[]);e.forEach((c,d)=>{for(let l of c.imports){let g=gn(c.path,l,s);if(!g||g===c.path)continue;let x=n.get(g);x!==void 0&&(o[d].push(x),r[x].push(d))}});let a=e.length,i=t?.trim().toLowerCase(),u=e.map(c=>i&&`${c.path} ${c.symbols.join(" ")}`.toLowerCase().includes(i)?4/a:1/a),p=u.reduce((c,d)=>c+d,0),f=e.map((c,d)=>u[d]/p);for(let c=0;c<20;c++){let d=e.map((l,g)=>.15*(u[g]/p));for(let l=0;l<a;l++){if(o[l].length===0){for(let g=0;g<a;g++)d[g]+=.85*f[l]/a;continue}for(let g of o[l])d[g]+=.85*f[l]/o[l].length}f=d}return e.map((c,d)=>({file:c,score:f[d],match:i?`${c.path} ${c.symbols.join(" ")}`.toLowerCase().includes(i):!1})).sort((c,d)=>Number(d.match)-Number(c.match)||d.score-c.score||c.file.path.localeCompare(d.file.path)).map(c=>c.file)}function bn(e,t={}){let n=Math.max(200,Math.min(8e3,t.budget??1200))*4,o=wn(e,t.query),r=[],a=0;for(let u of o){let p=u.symbols.slice(0,8).join(", "),f=p?`${u.path}: ${p}`:`${u.path}`;if(a+f.length+1>n)break;r.push(f),a+=f.length+1}if(r.length===0)return"(no source files found)";let i=o.length-r.length;return i>0&&r.push(`\u2026 ${i} more file${i===1?"":"s"} not shown`),r.join(`
14
+ `)}var gt;function ht(e){gt=e}var wt=ln({name:"repo_map",label:"repo_map",description:"A ranked outline of the repository: files by importance with their top declarations. Use it to find where something lives before reading files, instead of listing directories.",promptSnippet:"repo_map: ranked file outline of the project",parameters:j.Object({path:j.Optional(j.String({description:"Subdirectory to map, relative to the project root"})),query:j.Optional(j.String({description:"Keyword to bias the ranking, e.g. 'billing'"})),budget:j.Optional(j.Number({description:"Token budget, default 1200"}))}),async execute(e,t){let s=gt?.()??process.cwd(),n=hn(s,t.path??".");return{content:[{type:"text",text:bn(n,{budget:t.budget,query:t.query})}],details:{files:n.length}}}});function ee(){return{consecutiveFailures:0,tripped:!1}}function yn(e,t){return t==="manual"?!1:e.consecutiveFailures>=3}function xn(e,t){if(t)return e;let s=e.consecutiveFailures+1;return{consecutiveFailures:s,tripped:e.tripped||s>=3}}function kn(){return ee()}function Sn(e){return[`Auto-compaction failed ${e.consecutiveFailures} times in a row, so it is switched off for this session.`,"The context is over the limit and compaction cannot recover it. Start a new session, or switch to a model with a larger context window.","Manual /compact is still allowed."].join(" ")}var I=ee();function bt(){return e=>{e.on("session_start",async()=>{I=ee()}),e.on("session_compact",async()=>{I=kn()}),e.on("session_compact_failed",async(t,s)=>{let n=I;I=xn(I,t.aborted),!n.tripped&&I.tripped&&s?.ui&&s.ui.notify(Sn(I),"warning")}),e.on("session_before_compact",async t=>{if(yn(I,t.reason))return{cancel:!0}})}}function _n(e){R(U(e))}function yt(e){return`budget exhausted (${e.budget??"default"} continuations)`}function xt(){return e=>{e.on("session_start",async(t,s)=>{_n(s)}),e.on("context_with_system",async(t,s)=>{let n=U(s);if(R(n),!n||n.status!=="active")return;let o=t.messages[0];if(!o||o.role!=="system")return;let r=`${M(o.content)}
15
15
 
16
- ${De(n)}`;return{messages:t.messages.map(i=>i===o?{...o,content:M(o.content,r)}:i)}}),e.on("agent_before_settle",async(t,s)=>{try{let n=B(s);if(R(n),H(n).action==="stop"||!n||t.continue||!t.context.canContinue)return;let o={...n,used:n.used+1};if(e.appendEntry(W,o),R(o),H(o).action==="stop"){let r={...o,status:"done",note:yt(o)};e.appendEntry(W,r),R(r);return}return{entries:[{type:"custom_message",customType:Ie,content:Ce(o),display:!0}],continue:!0}}catch{return}}),e.on("agent_settled",async(t,s)=>{try{let n=B(s),o=H(n);if(n&&o.action==="stop"&&o.close){let r={...n,status:"done",note:yt(n)};e.appendEntry(W,r),R(r)}else R(n)}catch{return}})}}function _n(e){let t=le(e);return t.length===0?"":["The user installed the following presets. Their rules apply to this session.","",...t.map(n=>`<preset name="${n.name}">
16
+ ${De(n)}`;return{messages:t.messages.map(i=>i===o?{...o,content:F(o.content,r)}:i)}}),e.on("agent_before_settle",async(t,s)=>{try{let n=U(s);if(R(n),q(n).action==="stop"||!n||t.continue||!t.context.canContinue)return;let o={...n,used:n.used+1};if(e.appendEntry(H,o),R(o),q(o).action==="stop"){let r={...o,status:"done",note:yt(o)};e.appendEntry(H,r),R(r);return}return{entries:[{type:"custom_message",customType:Ie,content:Ce(o),display:!0}],continue:!0}}catch{return}}),e.on("agent_settled",async(t,s)=>{try{let n=U(s),o=q(n);if(n&&o.action==="stop"&&o.close){let r={...n,status:"done",note:yt(n)};e.appendEntry(H,r),R(r)}else R(n)}catch{return}})}}function Tn(e){let t=le(e);return t.length===0?"":["The user installed the following presets. Their rules apply to this session.","",...t.map(n=>`<preset name="${n.name}">
17
17
  ${n.text}
18
18
  </preset>`)].join(`
19
- `)}function kt(e){return t=>{t.on("resources_discover",async()=>{let s=ce(e);return s.length>0?{skillPaths:s}:void 0}),t.on("context_with_system",async s=>{let n=_n(e);if(!n)return;let o=s.messages[0];if(!o||o.role!=="system")return;let r=`${N(o.content)}
19
+ `)}function kt(e){return t=>{t.on("resources_discover",async()=>{let s=ce(e);return s.length>0?{skillPaths:s}:void 0}),t.on("context_with_system",async s=>{let n=Tn(e);if(!n)return;let o=s.messages[0];if(!o||o.role!=="system")return;let r=`${M(o.content)}
20
20
 
21
- ${n}`;return{messages:s.messages.map(i=>i===o?{...o,content:M(o.content,r)}:i)}})}}import{Type as w}from"@netrodev/hxf-ai";import{defineTool as Tn}from"@netrodev/hxf-coding-agent";function En(){return[...q.values()].map(e=>`${e.name} (${e.description})`).join(", ")}function St(){return Tn({name:"task",label:"task",description:`Spawn subagents. Available: ${En()}. One call can carry tasks[]; each item may set agent, model, effort and isolation. Agents run concurrently, park when done, and can be resumed or messaged with /agents. Pass background: true to return as soon as they start instead of waiting for them. Use architect to design an approach before a large change. Set isolation: "worktree" on every task that writes files.`,promptSnippet:"task: spawn background agents",parameters:w.Object({agent:w.Optional(w.String()),effort:w.Optional(w.String()),model:w.Optional(w.String()),task:w.Optional(w.String()),isolation:w.Optional(w.String()),background:w.Optional(w.Boolean()),tasks:w.Optional(w.Array(w.Object({agent:w.Optional(w.String()),effort:w.Optional(w.String()),model:w.Optional(w.String()),task:w.String(),isolation:w.Optional(w.String())})))}),executionMode:"parallel",async execute(e,t,s,n,o){let r=t.tasks&&t.tasks.length>0?t.tasks.map(l=>({agent:l.agent??t.agent??"task",task:l.task,effort:l.effort??t.effort,model:l.model??t.model,isolation:l.isolation??t.isolation})):[{agent:t.agent??"task",task:t.task??"",effort:t.effort,model:t.model,isolation:t.isolation}],a=r.slice(0,J),i=r.length-a.length,u=!!t.background,p=[],f=[],c=[],d=[];try{for(let m of a){if(!m.task.trim())continue;let E;if(m.isolation==="worktree"){let $=await ot(o?.cwd??process.cwd(),m.agent);if($){f.push($),E=$.path;for(let U of $.skipped)d.push(`${m.agent}:${U}`)}else c.push(m.agent)}p.push(await et({...m,cwd:o?.cwd,background:u,parentModel:Qe(o?.model),worktree:E})),n?.({content:[],details:{agents:p.map($=>({id:$.id,agent:$.agent,status:$.status}))}})}if(p.length===0)throw new Error("task or tasks is required");let l=i>0?`(only the first ${J} of ${r.length} tasks ran)`:"",g=p.filter(m=>m.worktree).length,y=[l,c.length>0?`isolation: "worktree" was requested but not available for: ${c.join(", ")}. Those agents ran in the shared working tree \u2014 check their edits for collisions before trusting them.`:"",d.length>0?`too large to copy into the isolated worktree, so it was left out: ${d.join(", ")}. An agent that needs it cannot install or build \u2014 treat any "done" from those runs as unverified.`:""].filter(Boolean),b={agents:p.map(m=>({id:m.id,status:m.status,isolated:!!m.worktree}))};if(u){tt();let m=p.map(E=>`${E.agent}#${E.id}`).join(", ");return{content:[{type:"text",text:`started ${p.length} agent${p.length===1?"":"s"} in the background: ${m}.`+(g>0?` ${g} of them in their own worktree.`:"")+`
22
- Their results are not part of this turn \u2014 keep working. Read them with /agents, or message one with /agents <id> <text>.`+(y.length>0?`
23
- ${y.join(`
21
+ ${n}`;return{messages:s.messages.map(i=>i===o?{...o,content:F(o.content,r)}:i)}})}}import{Type as w}from"@netrodev/hxf-ai";import{defineTool as En}from"@netrodev/hxf-coding-agent";function $n(){return[...z.values()].map(e=>`${e.name} (${e.description})`).join(", ")}function St(){return En({name:"task",label:"task",description:`Spawn subagents. Available: ${$n()}. One call can carry tasks[]; each item may set agent, model, effort and isolation. Agents run concurrently, park when done, and can be resumed or messaged with /agents. Pass background: true to return as soon as they start instead of waiting for them. Use architect to design an approach before a large change. Set isolation: "worktree" on every task that writes files.`,promptSnippet:"task: spawn background agents",parameters:w.Object({agent:w.Optional(w.String()),effort:w.Optional(w.String()),model:w.Optional(w.String()),task:w.Optional(w.String()),isolation:w.Optional(w.String()),background:w.Optional(w.Boolean()),tasks:w.Optional(w.Array(w.Object({agent:w.Optional(w.String()),effort:w.Optional(w.String()),model:w.Optional(w.String()),task:w.String(),isolation:w.Optional(w.String())})))}),executionMode:"parallel",async execute(e,t,s,n,o){let r=t.tasks&&t.tasks.length>0?t.tasks.map(l=>({agent:l.agent??t.agent??"task",task:l.task,effort:l.effort??t.effort,model:l.model??t.model,isolation:l.isolation??t.isolation})):[{agent:t.agent??"task",task:t.task??"",effort:t.effort,model:t.model,isolation:t.isolation}],a=r.slice(0,J),i=r.length-a.length,u=!!t.background,p=[],f=[],c=[],d=[];try{for(let m of a){if(!m.task.trim())continue;let E;if(m.isolation==="worktree"){let $=await ot(o?.cwd??process.cwd(),m.agent);if($){f.push($),E=$.path;for(let G of $.skipped)d.push(`${m.agent}:${G}`)}else c.push(m.agent)}p.push(await et({...m,cwd:o?.cwd,background:u,parentModel:Qe(o?.model),worktree:E})),n?.({content:[],details:{agents:p.map($=>({id:$.id,agent:$.agent,status:$.status}))}})}if(p.length===0)throw new Error("task or tasks is required");let l=i>0?`(only the first ${J} of ${r.length} tasks ran)`:"",g=p.filter(m=>m.worktree).length,x=[l,c.length>0?`isolation: "worktree" was requested but not available for: ${c.join(", ")}. Those agents ran in the shared working tree \u2014 check their edits for collisions before trusting them.`:"",d.length>0?`too large to copy into the isolated worktree, so it was left out: ${d.join(", ")}. An agent that needs it cannot install or build \u2014 treat any "done" from those runs as unverified.`:""].filter(Boolean),b={agents:p.map(m=>({id:m.id,status:m.status,isolated:!!m.worktree}))};if(u){tt();let m=p.map(E=>`${E.agent}#${E.id}`).join(", ");return{content:[{type:"text",text:`started ${p.length} agent${p.length===1?"":"s"} in the background: ${m}.`+(g>0?` ${g} of them in their own worktree.`:"")+`
22
+ Their results are not part of this turn \u2014 keep working. Read them with /agents, or message one with /agents <id> <text>.`+(x.length>0?`
23
+ ${x.join(`
24
24
  `)}`:"")}],details:b}}await nt(s);let T=p.map(m=>`${Je(m)}${m.worktree?" [isolated]":""}
25
- ${m.result??""}`);return y.length>0&&T.push(y.join(`
25
+ ${m.result??""}`);return x.length>0&&T.push(x.join(`
26
26
  `)),{content:[{type:"text",text:T.join(`
27
27
 
28
- `)}],details:b}}finally{for(let l of f)try{await l.remove()}catch{}}}})}import{readFileSync as $n,readdirSync as vn,statSync as An}from"node:fs";import{dirname as Rn,join as te}from"node:path";import{getAgentDir as On,parseFrontmatter as In}from"@netrodev/hxf-coding-agent";var _t=["off","minimal","low","medium","high","xhigh","max"],Dn=["name","description","tools","model","effort"],Cn=["read","bash","edit","write","grep","find","ls","bash_output","kill_shell","todo","context","goal","task","workflow","web_search","web_fetch","lsp","quality","slop","claim","repo_map"],Pn=["read","bash","edit","write","grep","find","ls","context","todo","web_search","web_fetch","lsp","claim"];function jn(e){let s=(typeof e=="string"?e.split(","):Array.isArray(e)?e:[]).map(n=>String(n).trim().replace(/^["']|["']$/g,"")).filter(Boolean);return s.length>0?s:void 0}function Nn(e){try{return An(e).isDirectory()}catch{return!1}}function Mn(e){let t=e;for(;;){let s=te(t,".howtocode","agents");if(Nn(s))return s;let n=Rn(t);if(n===t)return;t=n}}function Fn(e){let t=[{scope:"user",dir:te(On(),"agents")}],s=Mn(e);return s&&t.push({scope:"project",dir:s}),t}function Ln(e,t){let s=[],n=[],o=e.replace(/^\uFEFF/,"");if(!/^---\r?\n/.test(o))return{notes:s,problems:[`${t}: no frontmatter \u2014 the file must start with --- and end the block with ---`]};let r={},a="";try{let m=In(o);r=m.frontmatter??{},a=(m.body??"").trim()}catch(m){return{notes:s,problems:[`${t}: the frontmatter is not readable YAML \u2014 ${m instanceof Error?m.message:String(m)}`]}}for(let m of Object.keys(r))Dn.includes(m)||s.push(`${t}: ignoring the unknown frontmatter key '${m}'`);let i=(t.split(/[\\/]/).pop()??t).replace(/\.md$/i,""),u=r.name,p=(typeof u=="string"&&u.trim()?u:i).trim();/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(p)||n.push(`${t}: '${p}' is not a usable agent name \u2014 letters, digits, dot, dash and underscore only`);let f=r.description,c=typeof f=="string"?f.trim():"";c||n.push(`${t}: a description is required \u2014 it is how the model decides to use this agent`),a||n.push(`${t}: no prompt body \u2014 the text below the frontmatter is the agent's standing instruction`);let d=r.effort,l=typeof d=="string"?d.trim().toLowerCase():"";l&&!_t.includes(l)&&n.push(`${t}: effort '${l}' is not one of ${_t.join(", ")}`);let g=jn(r.tools),y=g??[...Pn];if(g){let m=g.filter(E=>!Cn.includes(E)&&!E.startsWith("mcp__"));m.length>0&&s.push(`${t}: unknown tool${m.length===1?"":"s"} ${m.join(", ")} \u2014 kept, but nothing registers them yet`)}let b=r.model,T=typeof b=="string"&&b.trim()?b.trim():void 0;return n.length>0?{notes:s,problems:n}:{def:{name:p,description:c,tools:y,prompt:a,effort:l||"medium",model:T,source:t},notes:s,problems:n}}function Tt(e,t){let s=[],n=[],o=[],r=[];for(let{scope:a,dir:i}of Fn(e)){let u;try{u=vn(i)}catch{continue}for(let p of u.filter(f=>f.toLowerCase().endsWith(".md")).sort()){let f=te(i,p),c;try{c=$n(f,"utf8")}catch(g){o.push(`${f}: ${g instanceof Error?g.message:String(g)}`);continue}let d=Ln(c,f);n.push(...d.notes),o.push(...d.problems);let l=d.def;l&&(t.has(l.name)&&n.push(`${f}: replaces ${Ve.has(l.name)?"the built-in":"an earlier"} '${l.name}'`),t.set(l.name,l),s.push(l),r.includes(a)||r.push(a))}}if(s.length>0){let a=s.filter(i=>t.get(i.name)===i);n.unshift(`loaded ${a.length} subagent definition${a.length===1?"":"s"} (${r.join(" and ")}): ${a.map(i=>i.name).join(", ")}`)}return{loaded:s,notes:n,problems:o}}var Bn=["grep","find","ls","bash_output","kill_shell","tool_search"];async function Et(e,{timeoutMs:t=2e3,quietTicks:s=2}={}){let n=Date.now()+t,o=e.getActiveToolNames().length,r=0;for(;Date.now()<n&&r<s;){await new Promise(i=>setTimeout(i,50));let a=e.getActiveToolNames().length;a>o?(o=a,r=0):r+=1}}function $t(e){let t=new Set(e.getActiveToolNames()),s=new Set(e.getAllTools().map(o=>o.name)),n=[];for(let o of Bn)s.has(o)&&!t.has(o)&&(t.add(o),n.push(o));return n.length>0&&e.setActiveToolsByName([...t]),n}var Un=["quality","slop","workflow","compress","repo_map","sessions","claim","web_fetch","lsp_diagnostics"],Gn=new Set(Un);function vt(e){return e.exposure!==void 0||!Gn.has(e.name)?e:{...e,exposure:"deferred"}}import{Type as z}from"@netrodev/hxf-ai";import{defineTool as Wn}from"@netrodev/hxf-coding-agent";var Hn={edit:!0,write:!0},qn=/\.(ts|tsx|js|jsx|mts|cts|rs|go|py)$/;function At(e,t={}){return Wn({name:"lsp_diagnostics",label:"lsp_diagnostics",description:"Diagnostics for a file from its language server, as the editor would show them. Use after a change that the automatic check reported nothing about, or when a server was slow. Returns 'clean' when there is nothing to fix.",promptSnippet:"lsp_diagnostics: what the language server reports for a file",parameters:z.Object({file:z.String({description:"Path to the file, relative to the project root or absolute"}),waitMs:z.Optional(z.Number({description:"How long to wait for the server to publish (default 3000)"}))}),async execute(s,n){let o=await V(n.file,e(),{waitMs:n.waitMs??t.waitMs??3e3});return o.unavailable?{content:[{type:"text",text:`no diagnostics: ${o.unavailable}`}],details:{unavailable:o.unavailable}}:o.diagnostics.length===0?{content:[{type:"text",text:"clean: the language server reports nothing for this file"}],details:{count:0}}:{content:[{type:"text",text:o.diagnostics.join(`
29
- `)}],details:{count:o.diagnostics.length}}}})}function Rt(e={}){return t=>{t.on("tool_result",async(s,n)=>{if(e.enabled&&!e.enabled()||s.isError||!Hn[s.toolName])return;let o=s.input?.path;if(typeof o!="string"||!qn.test(o))return;let r=await V(o,n.cwd,{waitMs:e.waitMs});if(r.unavailable||r.diagnostics.length===0)return;let a=s.content.map(u=>u.type==="text"?u.text:"").join(`
28
+ `)}],details:b}}finally{for(let l of f)try{await l.remove()}catch{}}}})}import{readFileSync as vn,readdirSync as An,statSync as Rn}from"node:fs";import{dirname as On,join as te}from"node:path";import{getAgentDir as In,parseFrontmatter as Dn}from"@netrodev/hxf-coding-agent";var _t=["off","minimal","low","medium","high","xhigh","max"],Cn=["name","description","tools","model","effort"],Pn=["read","bash","edit","write","grep","find","ls","bash_output","kill_shell","todo","context","goal","task","workflow","web_search","web_fetch","lsp","quality","slop","claim","repo_map"],jn=["read","bash","edit","write","grep","find","ls","context","todo","web_search","web_fetch","lsp","claim"];function Nn(e){let s=(typeof e=="string"?e.split(","):Array.isArray(e)?e:[]).map(n=>String(n).trim().replace(/^["']|["']$/g,"")).filter(Boolean);return s.length>0?s:void 0}function Mn(e){try{return Rn(e).isDirectory()}catch{return!1}}function Fn(e){let t=e;for(;;){let s=te(t,".howtocode","agents");if(Mn(s))return s;let n=On(t);if(n===t)return;t=n}}function Ln(e){let t=[{scope:"user",dir:te(In(),"agents")}],s=Fn(e);return s&&t.push({scope:"project",dir:s}),t}function Bn(e,t){let s=[],n=[],o=e.replace(/^\uFEFF/,"");if(!/^---\r?\n/.test(o))return{notes:s,problems:[`${t}: no frontmatter \u2014 the file must start with --- and end the block with ---`]};let r={},a="";try{let m=Dn(o);r=m.frontmatter??{},a=(m.body??"").trim()}catch(m){return{notes:s,problems:[`${t}: the frontmatter is not readable YAML \u2014 ${m instanceof Error?m.message:String(m)}`]}}for(let m of Object.keys(r))Cn.includes(m)||s.push(`${t}: ignoring the unknown frontmatter key '${m}'`);let i=(t.split(/[\\/]/).pop()??t).replace(/\.md$/i,""),u=r.name,p=(typeof u=="string"&&u.trim()?u:i).trim();/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(p)||n.push(`${t}: '${p}' is not a usable agent name \u2014 letters, digits, dot, dash and underscore only`);let f=r.description,c=typeof f=="string"?f.trim():"";c||n.push(`${t}: a description is required \u2014 it is how the model decides to use this agent`),a||n.push(`${t}: no prompt body \u2014 the text below the frontmatter is the agent's standing instruction`);let d=r.effort,l=typeof d=="string"?d.trim().toLowerCase():"";l&&!_t.includes(l)&&n.push(`${t}: effort '${l}' is not one of ${_t.join(", ")}`);let g=Nn(r.tools),x=g??[...jn];if(g){let m=g.filter(E=>!Pn.includes(E)&&!E.startsWith("mcp__"));m.length>0&&s.push(`${t}: unknown tool${m.length===1?"":"s"} ${m.join(", ")} \u2014 kept, but nothing registers them yet`)}let b=r.model,T=typeof b=="string"&&b.trim()?b.trim():void 0;return n.length>0?{notes:s,problems:n}:{def:{name:p,description:c,tools:x,prompt:a,effort:l||"medium",model:T,source:t},notes:s,problems:n}}function Tt(e,t){let s=[],n=[],o=[],r=[];for(let{scope:a,dir:i}of Ln(e)){let u;try{u=An(i)}catch{continue}for(let p of u.filter(f=>f.toLowerCase().endsWith(".md")).sort()){let f=te(i,p),c;try{c=vn(f,"utf8")}catch(g){o.push(`${f}: ${g instanceof Error?g.message:String(g)}`);continue}let d=Bn(c,f);n.push(...d.notes),o.push(...d.problems);let l=d.def;l&&(t.has(l.name)&&n.push(`${f}: replaces ${Ve.has(l.name)?"the built-in":"an earlier"} '${l.name}'`),t.set(l.name,l),s.push(l),r.includes(a)||r.push(a))}}if(s.length>0){let a=s.filter(i=>t.get(i.name)===i);n.unshift(`loaded ${a.length} subagent definition${a.length===1?"":"s"} (${r.join(" and ")}): ${a.map(i=>i.name).join(", ")}`)}return{loaded:s,notes:n,problems:o}}var Un=["grep","find","ls","bash_output","kill_shell","tool_search"];async function Et(e,{timeoutMs:t=2e3,quietTicks:s=2}={}){let n=Date.now()+t,o=e.getActiveToolNames().length,r=0;for(;Date.now()<n&&r<s;){await new Promise(i=>setTimeout(i,50));let a=e.getActiveToolNames().length;a>o?(o=a,r=0):r+=1}}function $t(e){let t=new Set(e.getActiveToolNames()),s=new Set(e.getAllTools().map(o=>o.name)),n=[];for(let o of Un)s.has(o)&&!t.has(o)&&(t.add(o),n.push(o));return n.length>0&&e.setActiveToolsByName([...t]),n}var Gn=["quality","slop","workflow","compress","repo_map","sessions","claim","web_fetch","lsp_diagnostics"],Wn=new Set(Gn);function vt(e){return e.exposure!==void 0||!Wn.has(e.name)?e:{...e,exposure:"deferred"}}import{Type as Z}from"@netrodev/hxf-ai";import{defineTool as Hn}from"@netrodev/hxf-coding-agent";var qn={edit:!0,write:!0},zn=/\.(ts|tsx|js|jsx|mts|cts|rs|go|py)$/;function At(e,t={}){return Hn({name:"lsp_diagnostics",label:"lsp_diagnostics",description:"Diagnostics for a file from its language server, as the editor would show them. Use after a change that the automatic check reported nothing about, or when a server was slow. Returns 'clean' when there is nothing to fix.",promptSnippet:"lsp_diagnostics: what the language server reports for a file",parameters:Z.Object({file:Z.String({description:"Path to the file, relative to the project root or absolute"}),waitMs:Z.Optional(Z.Number({description:"How long to wait for the server to publish (default 3000)"}))}),async execute(s,n){let o=await V(n.file,e(),{waitMs:n.waitMs??t.waitMs??3e3});return o.unavailable?{content:[{type:"text",text:`no diagnostics: ${o.unavailable}`}],details:{unavailable:o.unavailable}}:o.diagnostics.length===0?{content:[{type:"text",text:"clean: the language server reports nothing for this file"}],details:{count:0}}:{content:[{type:"text",text:o.diagnostics.join(`
29
+ `)}],details:{count:o.diagnostics.length}}}})}function Rt(e={}){return t=>{t.on("tool_result",async(s,n)=>{if(e.enabled&&!e.enabled()||s.isError||!qn[s.toolName])return;let o=s.input?.path;if(typeof o!="string"||!zn.test(o))return;let r=await V(o,n.cwd,{waitMs:e.waitMs});if(r.unavailable||r.diagnostics.length===0)return;let a=s.content.map(u=>u.type==="text"?u.text:"").join(`
30
30
  `).trimEnd(),i=`
31
31
 
32
32
  ${o} now reports:
33
33
  ${r.diagnostics.join(`
34
- `)}`;return{content:[{type:"text",text:`${a}${i}`}],...s.structuredContent!==void 0?{structuredContent:s.structuredContent}:{}}})}}import{spawnSync as zn}from"node:child_process";import{join as Zn}from"node:path";import{defineTool as Kn}from"@netrodev/hxf-coding-agent";var Xn=6e3,Ot=Kn({name:"slop",label:"slop",description:"Check code against the project's slop gate: naming, comments, placeholder values, swallowed errors, and the LLM tells that appear in model-written code. Read-only. Use it before reporting a task finished; it returns each finding as a rule id, a line, and what is wrong, so a claim of clean code becomes something the user can verify. Defaults to the changed files; pass a path to narrow it.",promptSnippet:"slop: naming, comment and placeholder findings for changed code",parameters:x.Object({path:x.Optional(x.String({description:"One file or directory, relative to the project root. Omit to scan the changed set."})),changes:x.Optional(x.Boolean({description:"Scan only files changed against the base ref. Default true when path is omitted."})),base:x.Optional(x.String({description:"Git ref for `changes`. Defaults to HEAD."}))}),async execute(e,t,s,n,o){let r=o.cwd??process.cwd(),i=[Zn(r,"scripts","slop.mjs"),"--json"];t.path!==void 0?i.push(t.path):(t.changes??!0)&&i.push("--changes"),t.base!==void 0&&i.push("--base",t.base);let u=zn("node",i,{cwd:r,encoding:"utf8",timeout:12e4}),p;try{p=JSON.parse(u.stdout)}catch{p=void 0}if(!p){let y=(u.stderr||u.stdout||"").trim()||u.error?.message||(u.signal?`killed by ${u.signal} (timed out after 120 s?)`:"no output");return{content:[{type:"text",text:`slop gate produced no report: ${y.slice(0,400)}`}],details:{error:y.slice(0,400)}}}if(p.off)return{content:[{type:"text",text:"slop gate is off"}],details:{off:!0}};let f=p.files??{},c=[],d=0;for(let[y,b]of Object.entries(f)){c.push(`${y}`);for(let T of b)d+=1,c.push(` ${T.rule} L${T.line} ${T.message}`)}if(d===0)return{content:[{type:"text",text:"slop gate: no findings in the scanned files"}],details:{files:Object.keys(f).length,findings:0}};let l=c.join(`
35
- `).slice(0,Xn),g=l.length<c.join(`
34
+ `)}`;return{content:[{type:"text",text:`${a}${i}`}],...s.structuredContent!==void 0?{structuredContent:s.structuredContent}:{}}})}}import{spawnSync as Zn}from"node:child_process";import{join as Kn}from"node:path";import{defineTool as Xn}from"@netrodev/hxf-coding-agent";var Yn=6e3,Ot=Xn({name:"slop",label:"slop",description:"Check code against the project's slop gate: naming, comments, placeholder values, swallowed errors, and the LLM tells that appear in model-written code. Read-only. Use it before reporting a task finished; it returns each finding as a rule id, a line, and what is wrong, so a claim of clean code becomes something the user can verify. Defaults to the changed files; pass a path to narrow it.",promptSnippet:"slop: naming, comment and placeholder findings for changed code",parameters:k.Object({path:k.Optional(k.String({description:"One file or directory, relative to the project root. Omit to scan the changed set."})),changes:k.Optional(k.Boolean({description:"Scan only files changed against the base ref. Default true when path is omitted."})),base:k.Optional(k.String({description:"Git ref for `changes`. Defaults to HEAD."}))}),async execute(e,t,s,n,o){let r=o.cwd??process.cwd(),i=[Kn(r,"scripts","slop.mjs"),"--json"];t.path!==void 0?i.push(t.path):(t.changes??!0)&&i.push("--changes"),t.base!==void 0&&i.push("--base",t.base);let u=Zn("node",i,{cwd:r,encoding:"utf8",timeout:12e4}),p;try{p=JSON.parse(u.stdout)}catch{p=void 0}if(!p){let x=(u.stderr||u.stdout||"").trim()||u.error?.message||(u.signal?`killed by ${u.signal} (timed out after 120 s?)`:"no output");return{content:[{type:"text",text:`slop gate produced no report: ${x.slice(0,400)}`}],details:{error:x.slice(0,400)}}}if(p.off)return{content:[{type:"text",text:"slop gate is off"}],details:{off:!0}};let f=p.files??{},c=[],d=0;for(let[x,b]of Object.entries(f)){c.push(`${x}`);for(let T of b)d+=1,c.push(` ${T.rule} L${T.line} ${T.message}`)}if(d===0)return{content:[{type:"text",text:"slop gate: no findings in the scanned files"}],details:{files:Object.keys(f).length,findings:0}};let l=c.join(`
35
+ `).slice(0,Yn),g=l.length<c.join(`
36
36
  `).length?`
37
37
  \u2026 truncated`:"";return{content:[{type:"text",text:`${d} finding${d===1?"":"s"}:
38
38
 
39
- ${l}${g}`}],details:{files:Object.keys(f).length,findings:d}}}});import{StringEnum as Yn}from"@netrodev/hxf-ai";import{defineTool as Vn}from"@netrodev/hxf-coding-agent";var Jn=["status","tabs","open","activate","navigate","evaluate","screenshot","close"];function D(e,t){return{content:[{type:"text",text:t}],details:{...e,text:t}}}function v(e,t){let s=t instanceof Error?t.message:String(t);return{content:[{type:"text",text:s}],details:{action:e,error:s},isError:!0}}async function ne(e,t,s){let n=await Q();return await n.rpc({op:"attach",tabId:e}),n.rpc({op:"send",tabId:e,method:t,params:s})}function Qn(e){return e.length?e.map(t=>`${t.active?"*":" "} ${t.tabId} ${t.title||"(untitled)"} ${t.url}`).join(`
40
- `):"No tabs open."}var It=Vn({name:"browser",label:"browser",description:"Drive the user's own Chrome tabs (signed-in sessions are reused) through the local browser relay. Actions: status (relay + extension state), tabs (list), open (new tab), activate, navigate, evaluate (run JavaScript in the page), screenshot (base64 PNG), close (tab). Requires the HowToCode Browser Relay extension: run /browser-relay install once. Needs a tabId for activate/navigate/evaluate/screenshot/close; use tabs to get one.",promptSnippet:"browser: drive the user's Chrome tabs (status | tabs | open | activate | navigate | evaluate | screenshot | close)",parameters:x.Object({action:Yn(Jn,{description:"Which browser action to run"}),url:x.Optional(x.String({description:"URL for open/navigate"})),tabId:x.Optional(x.Number({description:"Chrome tab id from `tabs`"})),expression:x.Optional(x.String({description:"JavaScript for `evaluate`"}))}),async execute(e,t,s,n,o){let r=t.action;try{let a=await Q();switch(r){case"status":{let i=a.state();return D({action:r},`relay 127.0.0.1:${i.port}
39
+ ${l}${g}`}],details:{files:Object.keys(f).length,findings:d}}}});import{StringEnum as Vn}from"@netrodev/hxf-ai";import{defineTool as Jn}from"@netrodev/hxf-coding-agent";var Qn=["status","tabs","open","activate","navigate","evaluate","screenshot","close"];function D(e,t){return{content:[{type:"text",text:t}],details:{...e,text:t}}}function v(e,t){let s=t instanceof Error?t.message:String(t);return{content:[{type:"text",text:s}],details:{action:e,error:s},isError:!0}}async function ne(e,t,s){let n=await Q();return await n.rpc({op:"attach",tabId:e}),n.rpc({op:"send",tabId:e,method:t,params:s})}function eo(e){return e.length?e.map(t=>`${t.active?"*":" "} ${t.tabId} ${t.title||"(untitled)"} ${t.url}`).join(`
40
+ `):"No tabs open."}var It=Jn({name:"browser",label:"browser",description:"Drive the user's own Chrome tabs (signed-in sessions are reused) through the local browser relay. Actions: status (relay + extension state), tabs (list), open (new tab), activate, navigate, evaluate (run JavaScript in the page), screenshot (base64 PNG), close (tab). Requires the HowToCode Browser Relay extension: run /browser-relay install once. Needs a tabId for activate/navigate/evaluate/screenshot/close; use tabs to get one.",promptSnippet:"browser: drive the user's Chrome tabs (status | tabs | open | activate | navigate | evaluate | screenshot | close)",parameters:k.Object({action:Vn(Qn,{description:"Which browser action to run"}),url:k.Optional(k.String({description:"URL for open/navigate"})),tabId:k.Optional(k.Number({description:"Chrome tab id from `tabs`"})),expression:k.Optional(k.String({description:"JavaScript for `evaluate`"}))}),async execute(e,t,s,n,o){let r=t.action;try{let a=await Q();switch(r){case"status":{let i=a.state();return D({action:r},`relay 127.0.0.1:${i.port}
41
41
  extension: ${i.extensionConnected?"connected":"not connected"}
42
42
  browser: ${i.browserVersion||"unknown"}
43
43
  tabs: ${i.tabs.length}
44
- uptime: ${Math.round(i.uptimeMs/1e3)}s`)}case"tabs":return D({action:r,tabs:a.state().tabs},Qn(a.state().tabs));case"open":{if(!t.url)return v(r,"open needs a url");let i=await a.rpc({op:"createTab",url:t.url,active:!1});return D({action:r},`opened ${t.url}
44
+ uptime: ${Math.round(i.uptimeMs/1e3)}s`)}case"tabs":return D({action:r,tabs:a.state().tabs},eo(a.state().tabs));case"open":{if(!t.url)return v(r,"open needs a url");let i=await a.rpc({op:"createTab",url:t.url,active:!1});return D({action:r},`opened ${t.url}
45
45
  ${JSON.stringify(i)}`)}case"activate":{let i=t.tabId;return i===void 0?v(r,"activate needs a tabId"):(await a.rpc({op:"activateTab",tabId:i}),D({action:r,tabId:i},`activated tab ${i}`))}case"navigate":return t.tabId===void 0||!t.url?v(r,"navigate needs a tabId and url"):(await ne(t.tabId,"Page.navigate",{url:t.url}),D({action:r,tabId:t.tabId},`navigating tab ${t.tabId} to ${t.url}`));case"evaluate":{if(t.tabId===void 0||!t.expression)return v(r,"evaluate needs a tabId and expression");let i=await ne(t.tabId,"Runtime.evaluate",{expression:t.expression,returnByValue:!0,awaitPromise:!0});if(i.exceptionDetails)return v(r,i.exceptionDetails.text||"JavaScript threw an exception");let u=i.result?.value??i.result?.description??null;return D({action:r,tabId:t.tabId},JSON.stringify(u))}case"screenshot":{if(t.tabId===void 0)return v(r,"screenshot needs a tabId");let i=await ne(t.tabId,"Page.captureScreenshot",{format:"png"});return i.data?D({action:r,tabId:t.tabId},`base64 PNG (${i.data.length} chars):
46
- ${i.data}`):v(r,"Chrome returned no screenshot data")}case"close":return t.tabId===void 0?v(r,"close needs a tabId"):(await a.rpc({op:"removeTab",tabId:t.tabId}),D({action:r,tabId:t.tabId},`closed tab ${t.tabId}`))}}catch(a){return v(r,a)}}});function oe(e){return e.extensionRunner.emit({type:"session_shutdown",reason:"quit"}).catch(()=>{}).finally(()=>e.dispose())}import{readdir as Dt,rmdir as eo,stat as to,unlink as no}from"node:fs/promises";import{dirname as oo,join as se,resolve as Ct}from"node:path";async function Pt(e={}){let t={removed:[],failed:[],removedDirs:[]},s=se(e.agentDir??S,"sessions"),n=(e.now??Date.now())-rt*24*60*60*1e3,o=e.keep?Ct(e.keep):void 0,r;try{r=await Dt(s,{withFileTypes:!0})}catch{return t}for(let a of r){if(!a.isDirectory())continue;let i=se(s,a.name),u;try{u=await Dt(i)}catch{continue}let p=u.filter(f=>!f.endsWith(".jsonl"));for(let f of u){if(!f.endsWith(".jsonl"))continue;let c=se(i,f),d;try{o&&Ct(c)===o?d=!1:d=(await to(c)).mtimeMs<n}catch{d=!1}if(!d){p.push(f);continue}try{await no(c),t.removed.push(c)}catch{t.failed.push(c),p.push(f)}}if(p.length===0){if(o&&oo(o)===i)continue;try{await eo(i),t.removedDirs.push(i)}catch{}}}return t}var so=[/no available channel for model/i,/no live channel/i,/model_not_found/i,/model is not available for (this|your) (account|group|tier)/i,/insufficient_user_quota/i,/insufficient quota/i,/access code disabled/i,/\b401\b.*(unauthorized|invalid|missing)/i,/\b403\b.*forbidden/i,/\bmissing api key\b/i,/invalid api key/i,/authentication_error/i,/\b400\b.*(invalid_request|bad request)/i,/prompt is too long/i,/context (length|window) exceeded/i],ro=[/rate.?limit/i,/too many requests/i,/\b429\b/,/overloaded/i,/currently experiencing high demand/i,/model is at capacity/i,/service.?unavailable/i,/timed? ?out/i,/ECONNRESET|ETIMEDOUT|EPIPE|ENOTFOUND|EAI_AGAIN/,/stream (ended|closed|reset)/i,/empty response/i,/\b50[0-4]\b/];function jt(e){let t=(e??"").trim();if(t==="")return!1;for(let s of ro)if(s.test(t)){for(let n of so)if(n.test(t))return!1;return!0}return!1}var re="howtocode.build",dr=["read","tool_search","repo_map","bash","edit","write","grep","find","ls","bash_output","kill_shell","task","think","ask","claim","sessions","todo","context","goal","enter_plan_mode","exit_plan_mode","workflow","web_search","web_fetch","lsp","lsp_diagnostics","quality","compress","slop","browser"],go=()=>({exclude:process.platform==="win32"?[]:["powershell"]}),Mt=!1;async function ur(e){let t=new fo(S),s=mo.create(e.cwd,S,{projectTrusted:t.get(e.cwd)===!0}),n=xe(S).compressToolOutput,o=e.sessionPath?Z.open(e.sessionPath):e.noSession?Z.inMemory(e.cwd):e.continueSession?Z.continueRecent(e.cwd):Z.create(e.cwd),r=(()=>{try{let k=o.getEntries().find(L=>L.type==="custom"&&L.customType===re)?.data?.version;return!k||k===G?void 0:`this session was written by HowToCode ${k}; you are running ${G}`}catch{return}})(),a=new po({cwd:e.cwd,agentDir:S,settingsManager:s,appendSystemPrompt:at(ie,e.interactive??!0),additionalSkillPaths:de(e.cwd),extensionFactories:[je(),me(),ct(),lt(),We(),Le(),kt(e.cwd),xt(),Ne(),bt(),co(),Rt({waitMs:1500}),uo(),pt({enabled:()=>n}),lo({loadConfig:h=>ye({cwd:h.cwd,projectTrusted:h.isProjectTrusted?.()??!1})})]});await a.reload();let i=Tt(e.cwd,q),u=St(),p=o.getSessionId();ht(()=>e.cwd);let f=Nt(S,Se);$e({root:()=>e.cwd,holder:()=>`session:${p}`,presenceDir:()=>f,selfId:()=>p});let c=()=>{try{_e({dir:f},{id:p,cwd:e.cwd,host:io(),pid:process.pid,at:Date.now()})}catch{}};c();let d=setInterval(c,Math.max(5e3,Math.floor(ke/3)));d.unref?.();let l=await ao({cwd:e.cwd,agentDir:S,settingsManager:s,sessionManager:o,resourceLoader:a,excludeTools:go().exclude,customTools:[u,wt,Te,Ee,Ae,ve,Re,Oe,Pe,Me,Fe,st(),He,qe,Ze,Ke,Ot,It,At(()=>e.cwd),Be({state:()=>Ue(Y()??"dcp-sessionless"),messages:()=>Ge(Y()??"dcp-sessionless")})].map(h=>vt(h)),thinkingLevel:e.thinking});await l.session.bindExtensions({mode:"print",onError:()=>{}});let g=pe(S),y=[];if(g){let h=await fe(S,g);h.renewed?await l.session.modelRuntime.setRuntimeApiKey("howtocode",h.credential.accessToken):(h.terminal&&h.message||h.message)&&y.push(h.message)}await Et(l.session),$t(l.session);let b=l.session.model;if(e.model){let h=await l.session.modelRuntime.getAvailable(),k=Xe(h,e.model);if(!k)throw clearInterval(d),X({dir:f},p),await oe(l.session),new Error(`unknown model '${e.model}'`);(b?.id!==k.id||b.provider!==k.provider)&&(await l.session.setModel(k),b=l.session.model)}else{let h=await l.session.modelRuntime.getAvailable(),k=new Map,L=[];for(let C of h){let j=k.get(C.provider);j===void 0&&(j=!!(await l.session.modelRuntime.getAuth(C.provider))?.auth?.apiKey,k.set(C.provider,j)),j&&L.push(C)}let K=ue;if(!K.includes(b?.provider??"")){let C=Ye(L.filter(j=>K.includes(j.provider)),K);C&&(await l.session.setModel(C),b=l.session.model)}}let T=l.session,m=T._isRetryableError;if(typeof m=="function"&&(T._isRetryableError=function(h){let k=h&&typeof h=="object"&&"errorMessage"in h?h.errorMessage:void 0;return typeof k=="string"&&k.trim()!==""&&!jt(k)?!1:m.call(this,h)}),!e.noSession&&o.getEntries().every(h=>h.type!=="custom"||h.customType!==re))try{o.appendCustomEntry(re,{version:G})}catch{}Mt||(Mt=!0,Pt({keep:l.session.sessionFile}).catch(()=>{}));let E=b?`${b.provider}/${b.id}`:"no model",$=!!(b&&b.cost&&(b.cost.input>0||b.cost.output>0)),U=[ae(l.modelFallbackMessage),...y,...i.notes,...i.problems].filter(h=>!!h);return b||U.push(`no model configured. run \`howtocode\` and use /login, or edit ${Nt(S,"models.json")}`),{session:l.session,dispose:async()=>{ze(),await oe(l.session),clearInterval(d),X({dir:f},p)},modelLabel:E,priced:$,setCompressToolOutput:h=>{n=h},note:[r,...U].filter(Boolean).join(`
47
- `)||void 0}}export{re as BUILD_ENTRY,dr as MAIN_TOOLS,ur as openSession};
46
+ ${i.data}`):v(r,"Chrome returned no screenshot data")}case"close":return t.tabId===void 0?v(r,"close needs a tabId"):(await a.rpc({op:"removeTab",tabId:t.tabId}),D({action:r,tabId:t.tabId},`closed tab ${t.tabId}`))}}catch(a){return v(r,a)}}});function oe(e){return e.extensionRunner.emit({type:"session_shutdown",reason:"quit"}).catch(()=>{}).finally(()=>e.dispose())}import{readdir as Dt,rmdir as to,stat as no,unlink as oo}from"node:fs/promises";import{dirname as so,join as se,resolve as Ct}from"node:path";async function Pt(e={}){let t={removed:[],failed:[],removedDirs:[]},s=se(e.agentDir??S,"sessions"),n=(e.now??Date.now())-rt*24*60*60*1e3,o=e.keep?Ct(e.keep):void 0,r;try{r=await Dt(s,{withFileTypes:!0})}catch{return t}for(let a of r){if(!a.isDirectory())continue;let i=se(s,a.name),u;try{u=await Dt(i)}catch{continue}let p=u.filter(f=>!f.endsWith(".jsonl"));for(let f of u){if(!f.endsWith(".jsonl"))continue;let c=se(i,f),d;try{o&&Ct(c)===o?d=!1:d=(await no(c)).mtimeMs<n}catch{d=!1}if(!d){p.push(f);continue}try{await oo(c),t.removed.push(c)}catch{t.failed.push(c),p.push(f)}}if(p.length===0){if(o&&so(o)===i)continue;try{await to(i),t.removedDirs.push(i)}catch{}}}return t}var ro=[/no available channel for model/i,/no live channel/i,/model_not_found/i,/model is not available for (this|your) (account|group|tier)/i,/insufficient_user_quota/i,/insufficient quota/i,/access code disabled/i,/\b401\b.*(unauthorized|invalid|missing)/i,/\b403\b.*forbidden/i,/\bmissing api key\b/i,/invalid api key/i,/authentication_error/i,/\b400\b.*(invalid_request|bad request)/i,/prompt is too long/i,/context (length|window) exceeded/i],io=[/rate.?limit/i,/too many requests/i,/\b429\b/,/overloaded/i,/currently experiencing high demand/i,/model is at capacity/i,/service.?unavailable/i,/timed? ?out/i,/ECONNRESET|ETIMEDOUT|EPIPE|ENOTFOUND|EAI_AGAIN/,/stream (ended|closed|reset)/i,/empty response/i,/this operation was aborted/i,/socket hang up/i,/fetch failed/i,/\b50[0-4]\b/];function jt(e,t){if(e==="aborted")return!1;if(t!==void 0&&t.trim()!=="")return ao(t)}function ao(e){let t=(e??"").trim();if(t==="")return!1;for(let s of io)if(s.test(t)){for(let n of ro)if(n.test(t))return!1;return!0}return!1}var re="howtocode.build",ur=["read","tool_search","repo_map","bash","edit","write","grep","find","ls","bash_output","kill_shell","task","think","ask","claim","sessions","todo","context","goal","enter_plan_mode","exit_plan_mode","workflow","web_search","web_fetch","lsp","lsp_diagnostics","quality","compress","slop","browser"],wo=()=>({exclude:process.platform==="win32"?[]:["powershell"]}),Mt=!1;async function pr(e){let t=new go(S),s=ho.create(e.cwd,S,{projectTrusted:t.get(e.cwd)===!0}),n=xe(S).compressToolOutput,o=e.sessionPath?K.open(e.sessionPath):e.noSession?K.inMemory(e.cwd):e.continueSession?K.continueRecent(e.cwd):K.create(e.cwd),r=(()=>{try{let y=o.getEntries().find(C=>C.type==="custom"&&C.customType===re)?.data?.version;return!y||y===W?void 0:`this session was written by HowToCode ${y}; you are running ${W}`}catch{return}})(),a=new mo({cwd:e.cwd,agentDir:S,settingsManager:s,appendSystemPrompt:at(ie,e.interactive??!0),additionalSkillPaths:de(e.cwd),extensionFactories:[je(),me(),ct(),lt(),We(),Le(),kt(e.cwd),xt(),Ne(),bt(),uo(),Rt({waitMs:1500}),fo(),pt({enabled:()=>n}),po({loadConfig:h=>ye({cwd:h.cwd,projectTrusted:h.isProjectTrusted?.()??!1})})]});await a.reload();let i=Tt(e.cwd,z),u=St(),p=o.getSessionId();ht(()=>e.cwd);let f=Nt(S,Se);$e({root:()=>e.cwd,holder:()=>`session:${p}`,presenceDir:()=>f,selfId:()=>p});let c=()=>{try{_e({dir:f},{id:p,cwd:e.cwd,host:co(),pid:process.pid,at:Date.now()})}catch{}};c();let d=setInterval(c,Math.max(5e3,Math.floor(ke/3)));d.unref?.();let l=await lo({cwd:e.cwd,agentDir:S,settingsManager:s,sessionManager:o,resourceLoader:a,excludeTools:wo().exclude,customTools:[u,wt,Te,Ee,Ae,ve,Re,Oe,Pe,Me,Fe,st(),He,qe,Ze,Ke,Ot,It,At(()=>e.cwd),Be({state:()=>Ue(Y()??"dcp-sessionless"),messages:()=>Ge(Y()??"dcp-sessionless")})].map(h=>vt(h)),thinkingLevel:e.thinking});await l.session.bindExtensions({mode:"print",onError:()=>{}});let g=pe(S),x=[];if(g){let h=await fe(S,g);h.renewed?await l.session.modelRuntime.setRuntimeApiKey("howtocode",h.credential.accessToken):(h.terminal&&h.message||h.message)&&x.push(h.message)}await Et(l.session),$t(l.session);let b=l.session.model;if(e.model){let h=await l.session.modelRuntime.getAvailable(),y=Xe(h,e.model);if(!y)throw clearInterval(d),X({dir:f},p),await oe(l.session),new Error(`unknown model '${e.model}'`);(b?.id!==y.id||b.provider!==y.provider)&&(await l.session.setModel(y),b=l.session.model)}else{let h=await l.session.modelRuntime.getAvailable(),y=new Map,C=[];for(let P of h){let N=y.get(P.provider);N===void 0&&(N=!!(await l.session.modelRuntime.getAuth(P.provider))?.auth?.apiKey,y.set(P.provider,N)),N&&C.push(P)}let B=ue;if(!B.includes(b?.provider??"")){let P=Ye(C.filter(N=>B.includes(N.provider)),B);P&&(await l.session.setModel(P),b=l.session.model)}}let T=l.session,m=T._isRetryableError;if(typeof m=="function"&&(T._isRetryableError=function(h){let y=typeof h=="object"&&h!==null?h:void 0,C=y&&"errorMessage"in y&&typeof y.errorMessage=="string"?y.errorMessage:void 0,B=y&&"stopReason"in y&&typeof y.stopReason=="string"?y.stopReason:void 0;return jt(B,C)??m.call(this,h)}),!e.noSession&&o.getEntries().every(h=>h.type!=="custom"||h.customType!==re))try{o.appendCustomEntry(re,{version:W})}catch{}Mt||(Mt=!0,Pt({keep:l.session.sessionFile}).catch(()=>{}));let E=b?`${b.provider}/${b.id}`:"no model",$=!!(b&&b.cost&&(b.cost.input>0||b.cost.output>0)),G=[ae(l.modelFallbackMessage),...x,...i.notes,...i.problems].filter(h=>!!h);return b||G.push(`no model configured. run \`howtocode\` and use /login, or edit ${Nt(S,"models.json")}`),{session:l.session,dispose:async()=>{ze(),await oe(l.session),clearInterval(d),X({dir:f},p)},modelLabel:E,priced:$,setCompressToolOutput:h=>{n=h},note:[r,...G].filter(Boolean).join(`
47
+ `)||void 0}}export{re as BUILD_ENTRY,ur as MAIN_TOOLS,pr as openSession};