howtocode 0.0.0-stage → 0.7.57

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.
Files changed (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +248 -2
  3. package/dist/chunk-27TRKD65.js +2 -0
  4. package/dist/chunk-3FYCFLNK.js +1 -0
  5. package/dist/chunk-3YOYZOXG.js +2 -0
  6. package/dist/chunk-3YSNDQVR.js +5 -0
  7. package/dist/chunk-43YCQFSH.js +1 -0
  8. package/dist/chunk-5X3PQ36J.js +2 -0
  9. package/dist/chunk-7LA2AMZB.js +1 -0
  10. package/dist/chunk-A3LZMZ3C.js +2 -0
  11. package/dist/chunk-ABDZXFNM.js +10 -0
  12. package/dist/chunk-ACBAN4MH.js +197 -0
  13. package/dist/chunk-AS4FUFAN.js +8 -0
  14. package/dist/chunk-BV6J5Q4T.js +1 -0
  15. package/dist/chunk-BZJSYOTO.js +1 -0
  16. package/dist/chunk-CCISJKGS.js +1 -0
  17. package/dist/chunk-DCFM67MM.js +140 -0
  18. package/dist/chunk-ELHK7EH4.js +1 -0
  19. package/dist/chunk-ELM3OMOE.js +1 -0
  20. package/dist/chunk-EZNNALD3.js +1 -0
  21. package/dist/chunk-FLP47RIR.js +5 -0
  22. package/dist/chunk-LYLJZVZ7.js +1 -0
  23. package/dist/chunk-MBVAG3VC.js +6 -0
  24. package/dist/chunk-MCAAX33K.js +2 -0
  25. package/dist/chunk-MCDEIIEN.js +1 -0
  26. package/dist/chunk-MVVEYKN6.js +6 -0
  27. package/dist/chunk-ORJ2QZBG.js +3 -0
  28. package/dist/chunk-PH72JBBL.js +4 -0
  29. package/dist/chunk-PVFHAKN6.js +1 -0
  30. package/dist/chunk-QBHBECIB.js +47 -0
  31. package/dist/chunk-QEPPIFSI.js +6 -0
  32. package/dist/chunk-QOYTPACU.js +3 -0
  33. package/dist/chunk-SDO33XPR.js +4 -0
  34. package/dist/chunk-TOV557ET.js +12 -0
  35. package/dist/chunk-TSEKPGK4.js +1 -0
  36. package/dist/chunk-TUXY64DT.js +2 -0
  37. package/dist/chunk-U3GZBLTM.js +2 -0
  38. package/dist/chunk-UTYFLLSM.js +1 -0
  39. package/dist/chunk-V3R4FYTJ.js +1 -0
  40. package/dist/chunk-VUQVLOAD.js +1 -0
  41. package/dist/chunk-WKUJ7CFO.js +1 -0
  42. package/dist/chunk-WOT6VMZA.js +1 -0
  43. package/dist/chunk-XBVWQC7P.js +1 -0
  44. package/dist/chunk-YN3H6RHD.js +2 -0
  45. package/dist/chunk-YNMLRZJK.js +2 -0
  46. package/dist/chunk-YX2QDCVK.js +1 -0
  47. package/dist/main.js +102 -0
  48. package/dist/presets/backend/api/preset.json +17 -0
  49. package/dist/presets/backend/api/prompt.md +9 -0
  50. package/dist/presets/backend/api/skills/api-contract/SKILL.md +35 -0
  51. package/dist/presets/data/sql/preset.json +17 -0
  52. package/dist/presets/data/sql/prompt.md +9 -0
  53. package/dist/presets/data/sql/skills/query-hygiene/SKILL.md +48 -0
  54. package/dist/presets/devops/containers/preset.json +17 -0
  55. package/dist/presets/devops/containers/prompt.md +9 -0
  56. package/dist/presets/devops/containers/skills/image-discipline/SKILL.md +59 -0
  57. package/dist/presets/frontend/web-ui/preset.json +17 -0
  58. package/dist/presets/frontend/web-ui/prompt.md +11 -0
  59. package/dist/presets/frontend/web-ui/skills/responsive-check/SKILL.md +46 -0
  60. package/dist/presets/gamedev/rotoolbox/preset.json +31 -0
  61. package/dist/presets/gamedev/rotoolbox/prompt.md +34 -0
  62. package/dist/presets/gamedev/rotoolbox/skills/rotoolbox/SKILL.md +129 -0
  63. package/dist/presets/hub.json +14582 -0
  64. package/dist/presets/lang/typescript/preset.json +16 -0
  65. package/dist/presets/lang/typescript/prompt.md +5 -0
  66. package/dist/presets/lang/typescript/skills/ts-strict/SKILL.md +48 -0
  67. package/dist/presets/mcp/filesystem/preset.json +27 -0
  68. package/dist/presets/mcp/filesystem/prompt.md +8 -0
  69. package/dist/presets/mcp/filesystem/skills/mcp-files/SKILL.md +27 -0
  70. package/dist/presets/mcp/memory/preset.json +25 -0
  71. package/dist/presets/mcp/memory/skills/mcp-memory/SKILL.md +31 -0
  72. package/dist/presets/mcp/rea/preset.json +28 -0
  73. package/dist/presets/mcp/rea/prompt.md +5 -0
  74. package/dist/presets/mcp/rea/skills/mcp-rea/SKILL.md +6 -0
  75. package/dist/presets/mcp/remotion/preset.json +27 -0
  76. package/dist/presets/mcp/remotion/prompt.md +7 -0
  77. package/dist/presets/mcp/remotion/skills/mcp-remotion/SKILL.md +6 -0
  78. package/dist/presets/mcp-hub.json +157 -0
  79. package/dist/presets/mobile/app/preset.json +17 -0
  80. package/dist/presets/mobile/app/prompt.md +7 -0
  81. package/dist/presets/mobile/app/skills/touch-targets/SKILL.md +47 -0
  82. package/dist/presets/quality/antislop/preset.json +25 -0
  83. package/dist/presets/quality/antislop/prompt.md +16 -0
  84. package/dist/presets/quality/antislop/skills/antislop/SKILL.md +595 -0
  85. package/dist/presets/quality/antislop/skills/antislop/references/gate.md +84 -0
  86. package/dist/presets/quality/antislop/skills/antislop-code/SKILL.md +128 -0
  87. package/dist/presets/quality/antislop/skills/antislop-copywriting/SKILL.md +413 -0
  88. package/dist/presets/quality/antislop/skills/antislop-human/SKILL.md +147 -0
  89. package/dist/presets/quality/antislop/skills/antislop-human/contrast-check.py +165 -0
  90. package/dist/presets/quality/antislop/skills/antislop-layoutmobile/SKILL.md +170 -0
  91. package/dist/presets/quality/antislop/skills/antislop-ui/SKILL.md +313 -0
  92. package/dist/presets/quality/antislop/skills/antislop-ui/references/motion.md +34 -0
  93. package/dist/presets/quality/antislop/skills/antislop-ui/references/states.md +49 -0
  94. package/package.json +34 -4
@@ -0,0 +1,6 @@
1
+ var T=/^m(\d{4})$/,F=/^b([1-9]\d*)$/,y=/^@([1-9]\d*)@$/,G=/^@b([1-9]\d*)@$/,M="dcp-message-id";function Y(){return{nextRef:1,keyToRef:{},refToKey:{}}}function I(e,n="xml"){let r=n==="compact"?Number.MAX_SAFE_INTEGER:9999;if(!Number.isSafeInteger(e)||e<1||e>r)throw new Error(`Message ID index out of bounds: ${e}. Supported range is 1-${r}.`);return n==="compact"?`@${e}@`:`m${e.toString().padStart(4,"0")}`}function D(e,n="xml"){if(!Number.isInteger(e)||e<1)throw new Error(`Invalid block ID: ${e}`);return n==="compact"?`@b${e}@`:`b${e}`}function k(e,n="xml"){let s=e.trim().toLowerCase().match(n==="compact"?y:T);if(!s)return null;let t=Number.parseInt(s[1],10);if(!Number.isSafeInteger(t))return null;let o=n==="compact"?Number.MAX_SAFE_INTEGER:9999;return t<1||t>o?null:t}function X(e,n="xml"){let s=e.trim().toLowerCase().match(n==="compact"?G:F);if(!s)return null;let t=Number.parseInt(s[1],10);return Number.isSafeInteger(t)?t:null}function j(e,n="xml"){let r=e.trim().toLowerCase(),s=k(r,n);if(s!==null)return{kind:"message",ref:I(s,n),index:s};let t=X(r,n);return t!==null?{kind:"compressed-block",ref:D(t,n),blockId:t}:null}function w(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function m(e){return!e.includes("<dcp-message-id")&&!e.includes("</dcp-message-id")?e:e.replace(/<dcp-message-id(?:\s[^>]*)?>[\s\S]*?<\/dcp-message-id>/gi,"").replace(/<dcp-message-id(?:\s[^>]*)?>[mb]?\d{0,6}/gi,"").replace(/<\/?dcp-message-id(?:\s[^>]*)?>?/gi,"")}function v(e,n,r="xml"){if(r==="compact"){if(e==="BLOCKED")return`
2
+ @blocked@`;let t=n?.priority;return`
3
+ ${e}${t?` [${t}]`:""}`}let s=Object.entries(n||{}).sort(([t],[o])=>t.localeCompare(o)).map(([t,o])=>t.trim().length===0||typeof o!="string"||o.length===0?"":` ${t}="${w(o)}"`).join("");return`
4
+ <${M}${s}>${e}</${M}>`}function C(e){return e.role==="user"||e.role==="assistant"||e.role==="toolResult"}function R(e){let n=new Map;return e.map(r=>{if(!C(r))return null;let s=r.role==="toolResult"?`toolResult:${r.toolCallId}`:`${r.role}:${r.timestamp}`,t=n.get(s)??0;return n.set(s,t+1),r.role==="toolResult"?s:`${s}#${t}`})}function U(e,n){let r=0;for(let s of R(n)){if(s===null||e.keyToRef[s]!==void 0)continue;let t=O(e);e.keyToRef[s]=t,e.refToKey[String(t)]=s,r++}return r}function O(e){let n=Number.isInteger(e.nextRef)?Math.max(1,e.nextRef):1;for(;n<=9999;){if(e.refToKey[String(n)]===void 0)return e.nextRef=n+1,n;n++}throw new Error(`Message ID alias capacity exceeded. Cannot allocate more than ${I(9999)} aliases in this session.`)}function W(e,n){return R(n).map(r=>r===null?null:e.keyToRef[r]??null)}var _="[\\uFF5C|\\u2502\\u01C0\\u2223]",N=`${_}?DSML${_}?`,a="(?:invoke|parameter|tool[_ -]?call)",l=`(?:${N}\\s*)?`,c="(?:\\\\?<|&lt;)",u="(?:>|&gt;)",d="\\\\?/",i="\\s*",g="(?:(?!>|&gt;)[\\s\\S])*",L="[\\s\\S]*?",P=new RegExp(`(?:dsml|${c}${i}(?:${d})?${i}${l}${a}\\b)`,"i"),B=new RegExp(`${c}${i}${l}(${a})\\b${g}${u}${L}${c}${i}${d}${i}${l}\\1\\b${g}${u}`,"gi"),K=new RegExp(`${c}${i}(?:${d})?${i}${l}${a}\\b${g}${u}?`,"gi"),z=new RegExp(`${c}${i}(?:${d})?${i}${N}[A-Za-z_]*`,"gi");function f(e){return P.test(e)?e.replace(B,"").replace(K,"").replace(z,""):e}function J(e){let n=f(m(e));return n===e?e:n.replace(/\n{3,}/g,`
5
+
6
+ `).trim()}var x=new RegExp(`${c}${i}${d}${i}${l}${a}\\b${g}${u}`,"iy"),A=new RegExp(`${c}${i}${l}${a}\\b${g}${u}`,"iy"),b=new RegExp(`${c}${i}(${d})?${i}${l}${a}\\b${g}${u}`,"gi"),h=96;function Q(e){let n=m(e),r=new RegExp(`${c}${i}${l}(${a})\\b${g}${u}`,"gi"),s=new RegExp(`${c}${i}${d}${i}${l}${a}\\b${g}${u}`,"i"),t=-1,o;for(;(o=r.exec(n))!==null;)if(!s.test(n.slice(o.index+o[0].length))){t=o.index;break}return f(t<0?n:n.slice(0,t))}function H(e){x.lastIndex=0;let n=x.exec(e);return n?{kind:"close",length:n[0].length}:(A.lastIndex=0,n=A.exec(e),n?{kind:"open",length:n[0].length}:null)}function V(){let e="",n=!1,r=0;return{push(s){e+=s;let t="";for(;;){if(n){b.lastIndex=0;let p=b.exec(e);if(p){r+=p[1]===void 0?1:-1,e=e.slice(p.index+p[0].length),r<=0&&(n=!1,r=0);continue}let S=Math.max(e.lastIndexOf("<"),e.lastIndexOf("&")),E=S<0?"":e.slice(S);e=E.length<=h&&!E.includes(">")?E:"";break}let o=e.search(/[<&]/);if(o<0){t+=f(e),e="";break}o>0&&(t+=f(e.slice(0,o)),e=e.slice(o));let $=H(e);if($){e=e.slice($.length),$.kind==="open"&&(n=!0,r=1);continue}if(!e.includes(">")&&e.length<=h)break;t+=e[0],e=e.slice(1)}return t},flush(){let s=f(e);return e="",n=!1,r=0,s}}}export{Y as a,I as b,D as c,j as d,m as e,v as f,U as g,W as h,f as i,J as j,Q as k,V as l};
@@ -0,0 +1,3 @@
1
+ import{readFileSync as f,statSync as u}from"node:fs";import{isAbsolute as a,resolve as p}from"node:path";var $=64*1024;function S(o,c){return o.replace(/(^|\s)@([^\s]+)/g,(e,l,i)=>{let t=i.replace(/[),.;:]+$/,""),g=i.slice(t.length),n=a(t)?t:p(c,t);try{let r=u(n);if(!r.isFile()||r.size===0||r.size>$)return e;let s=f(n);return s.includes(0)?e:`${l}<file name="${n}">
2
+ ${s.toString("utf8").trimEnd()}
3
+ </file>${g}`}catch{return e}})}export{S as a};
@@ -0,0 +1,4 @@
1
+ import{i as o,l as a}from"./chunk-MVVEYKN6.js";function f(n){return n.type==="message_update"}function c(n){if(n.type==="toolcall_start"){let t=n.contentIndex,i=t===void 0?void 0:n.partial?.content[t];if(i?.type!=="toolCall")return;let{partial:l,...g}=n;return{...g,id:i.id,toolName:i.name}}if(!("partial"in n))return n;let{partial:s,...e}=n;return e}var p={text:!0,thinking:!0,content:!0};function d(n,s,e=!1){if(typeof n=="string")return e?s(n):n;if(Array.isArray(n))return n.map(t=>d(t,s,e));if(n&&typeof n=="object"){let t={};for(let[r,i]of Object.entries(n))p[r]&&typeof i=="string"?t[r]=s(i):t[r]=d(i,s,e||r==="sections");return t}return n}function u(n,s){let e=d(n,o);if(!f(e))return e;if(e.message.role!=="assistant")return;let t=c(e.assistantMessageEvent);if(t===void 0)return;let r={...t};return"delta"in r&&typeof r.delta=="string"&&(r.delta=s?s(r.delta):o(r.delta)),{type:"message_update",usage:e.message.usage,assistantMessageEvent:r}}function y(n){let s=u(n);if(s!==void 0)return`${JSON.stringify(s)}
2
+ `}function A(){let n=a(),s=e=>n.push(e);return{line(e){let t=u(e,s);if(t!==void 0)return`${JSON.stringify(t)}
3
+ `},finish(){let e=n.flush();if(n=a(),!!e)return`${JSON.stringify({type:"message_update",assistantMessageEvent:{type:"text_delta",delta:e}})}
4
+ `}}}export{u as a,y as b,A as c};
@@ -0,0 +1 @@
1
+ import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q}from"./chunk-YNMLRZJK.js";import"./chunk-WOT6VMZA.js";export{c as APPROVAL_LABELS,b as APPROVAL_MODES,f as MODE_MAX_TIER,e as TIER_RANK,q as createPermissionExtension,h as criticalCommand,n as decideToolCall,o as describeToolCall,p as formatApprovalPrompt,j as getApprovalMode,d as isApprovalMode,l as isDangerousBypass,a as isReadOnlyCommand,g as resolveTier,i as setApprovalMode,m as setApprovalPrompt,k as setDangerousBypass};
@@ -0,0 +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-ACBAN4MH.js";import{b as xe}from"./chunk-27TRKD65.js";import{c as ue}from"./chunk-MBVAG3VC.js";import{h as pe,l as fe}from"./chunk-5X3PQ36J.js";import{r as me}from"./chunk-YNMLRZJK.js";import"./chunk-7LA2AMZB.js";import{H as S,K as de,v as ce,w as le}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import"./chunk-MVVEYKN6.js";import"./chunk-3YOYZOXG.js";import{b as G,c as ie,d as ae}from"./chunk-FLP47RIR.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}
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}
6
+
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
+ `),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)}
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)}
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}">
17
+ ${n.text}
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)}
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(`
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(`
26
+ `)),{content:[{type:"text",text:T.join(`
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(`
30
+ `).trimEnd(),i=`
31
+
32
+ ${o} now reports:
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(`
36
+ `).length?`
37
+ \u2026 truncated`:"";return{content:[{type:"text",text:`${d} finding${d===1?"":"s"}:
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}
41
+ extension: ${i.extensionConnected?"connected":"not connected"}
42
+ browser: ${i.browserVersion||"unknown"}
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}
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};
@@ -0,0 +1,6 @@
1
+ import{b as j}from"./chunk-MCAAX33K.js";import{H as m,N as A}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import{j as R}from"./chunk-MVVEYKN6.js";import{b as M,d as T,f as D}from"./chunk-TUXY64DT.js";import{a as I}from"./chunk-U3GZBLTM.js";import{a as b}from"./chunk-FLP47RIR.js";import"./chunk-WOT6VMZA.js";import{spawnSync as J}from"node:child_process";import{existsSync as S,readdirSync as E,readFileSync as x,realpathSync as B,statSync as C,writeFileSync as F,unlinkSync as z}from"node:fs";import{dirname as N,join as p}from"node:path";var k=[22,19];async function W(t="https://api.howtofix.id/api/status"){let n=[],[s,e]=process.versions.node.split(".").map(Number),r=s>k[0]||s===k[0]&&e>=k[1];n.push({name:"node",ok:r,detail:`${process.versions.node} (needs >= ${k[0]}.${k[1]})`});let i=J("git",["--version"],{encoding:"utf8"});n.push({name:"git",ok:i.status===0,detail:i.status===0?i.stdout.trim():"not found on PATH"});let o=I();n.push({name:"sandbox",ok:!!o,detail:o??"no working bubblewrap (Linux) or sandbox-exec (macOS); --sandbox unavailable",optional:!0});let l=!1,c=m;try{let d=p(m,`.doctor-${process.pid}`);F(d,"ok"),z(d),l=!0}catch(d){c=`${m} is not writable: ${d instanceof Error?d.message:String(d)}`}n.push({name:"state dir",ok:l,detail:c});let a=p(m,"auth.json"),u="no auth.json \u2014 run `howtocode` and sign in",h=!1;try{let d=JSON.parse(x(a,"utf8")),f=Object.keys(d).length;h=f>0,u=h?`${f} provider credential${f===1?"":"s"}`:u}catch{}n.push({name:"auth",ok:h,detail:u,optional:!0});try{let d=Date.now(),f=await fetch(t,{signal:AbortSignal.timeout(5e3)});n.push({name:"gateway",ok:f.ok,detail:`${t} \u2192 ${f.status} in ${Date.now()-d}ms`,optional:!0})}catch(d){n.push({name:"gateway",ok:!1,detail:`${t} unreachable: ${d instanceof Error?d.message:String(d)}`,optional:!0})}return n.push(G()),n}function G(t=q()){if(t===void 0)return{name:"install",ok:!0,detail:"not an npm install; skipped",optional:!0};if(!S(t))return{name:"install",ok:!0,detail:"no bundled dependencies to check",optional:!0};let n=[],s=0;for(let e of["@netrodev"]){let r=p(t,e);if(S(r))for(let i of E(r)){let o=p(r,i,"dist");if(S(o))for(let l of _(o)){s+=1;let c=x(l,"utf8");for(let a of c.matchAll(/import\("(\.[^"]+)"\)/g)){let u=p(N(l),a[1]);S(u)||n.push(`${e}/${i}: ${u.slice(o.length+1)}`)}}}}return n.length>0?{name:"install",ok:!1,detail:`${n.length} module${n.length===1?"":"s"} missing (${n[0]}); reinstall with \`npm install -g howtocode@latest\``}:{name:"install",ok:!0,detail:`${s} lazy module${s===1?"":"s"} present`}}function q(){try{return p(N(N(B(process.argv[1]??""))),"node_modules")}catch{return}}function _(t,n=[]){let s;try{s=E(t)}catch{return n}for(let e of s){let r=p(t,e);if(e.endsWith(".lazy.js"))n.push(r);else if(!e.includes("."))try{C(r).isDirectory()&&_(r,n)}catch{}}return n}async function ie(){let t=await W(),n=Math.max(...t.map(e=>e.name.length));for(let e of t){let r=e.ok?"ok ":e.optional?"warn":"FAIL";console.log(` ${r} ${e.name.padEnd(n)} ${e.detail}`)}let s=t.filter(e=>!e.ok&&!e.optional);return s.length>0?(console.log(`
2
+ ${s.length} problem${s.length===1?"":"s"} must be fixed before a session will work.`),1):0}function ce(t=m){let n=p(t,"models.json"),s;try{s=x(n,"utf8")}catch(a){return a.code==="ENOENT"?console.log(` no models.json at ${n} \u2014 run \`howtocode /connect\` to pull the catalogue`):j(b,"models",a),1}let e;try{e=JSON.parse(s)}catch(a){return console.error(`${b}: models: ${n} is not valid JSON (${a instanceof Error?a.message:String(a)})`),console.error(" fix the file, or delete it and run `howtocode /connect` to write a new one"),1}let r=e.providers??{},i=D(A),o=i?new Set(i.ids):void 0,l=new Set,c=0;for(let[a,u]of Object.entries(r)){let h=u.models??[],d=h.map(f=>f.id).filter(Boolean);for(let f of d)l.add(f);c+=d.length,console.log(` ${a} (${d.length})`);for(let f of h){if(!f.id)continue;let O=T(m).get(f.id),$=M(O??[]),g=$?` ${$}`:"",w=o&&!o.has(f.id)?" \u2014 not on this account":"";console.log(` ${f.id}${g}${w}`)}}if(o){let a=[...l].filter(u=>!o.has(u)).length;console.log(`
3
+ ${[...o].filter(u=>l.has(u)).length} of ${c} listed model(s) this account can call${a>0?`; ${a} cannot (kept for other plans)`:""}`)}else console.log("\n which of these this account can call is unknown: run `howtocode` once to record it");return c===0?(console.log(" no models configured"),1):0}function v(t=15,n=m){let s=p(n,"sessions"),e;try{e=E(s)}catch{return[]}let r=[];for(let i of e){let o=p(s,i),l;try{l=E(o)}catch{continue}for(let c of l){if(!c.endsWith(".jsonl"))continue;let a=p(o,c);try{let u=C(a);r.push({file:a,project:i,modified:u.mtimeMs,bytes:u.size})}catch{}}}return r.sort((i,o)=>o.modified-i.modified).slice(0,t)}function le(t){let n=t.indexOf("--search");if(n>=0){let o=t[n+1]?.trim();if(!o)return console.error(`${b}: sessions: --search needs a word or phrase`),2;let l=K(o);if(l.length===0)return console.log(` no session mentions "${o}"`),0;for(let c of l){let a=new Date(c.row.modified).toISOString().replace("T"," ").slice(0,16),u=`${c.matches} hit${c.matches===1?"":"s"}`;console.log(` ${a} ${c.row.project} (${u})`),console.log(` ${c.row.file}`),console.log(` ${c.snippet}`)}return 0}let s=t.indexOf("--limit"),e=s>=0&&Number(t[s+1])||15,r=v(e);if(r.length===0)return console.log(` no saved sessions under ${p(m,"sessions")}`),t.includes("--export")?1:0;let i=t.indexOf("--export");if(i>=0){let o=Number(t[i+1]);if(!Number.isInteger(o)||o<1||o>r.length)return console.error(`${b}: sessions: --export needs a number from the list (1-${r.length})`),2;let l=r[o-1];try{console.log(Q(l.file))}catch(c){return j(b,"sessions",c),1}return 0}return r.forEach((o,l)=>{let c=new Date(o.modified).toISOString().replace("T"," ").slice(0,16),a=Math.round(o.bytes/1024);console.log(` ${String(l+1).padStart(2)} ${c} ${String(a).padStart(6)}k ${o.project}`),console.log(` ${o.file}`)}),0}function H(t){let n=t;try{let s=JSON.parse(t),e=s.message?.content??s.content;if(typeof e=="string"&&e.trim())n=e;else if(Array.isArray(e)){let r=e.map(i=>i&&typeof i=="object"&&"text"in i?String(i.text):"").join(" ");r.trim()&&(n=r)}}catch{}return R(X(n).replace(/\s+/g," ").trim())}function X(t){return t.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007]*\u0007|\u001b[@-Z\\-_]/g,"")}function Z(t,n,s=80){let e=t.toLowerCase().indexOf(n);if(e<0)return t.slice(0,s*2).trim();let r=Math.max(0,e-s),i=Math.min(t.length,e+n.length+s);return`${r>0?"\u2026":""}${t.slice(r,i).trim()}${i<t.length?"\u2026":""}`}function K(t,n=10,s=m){let e=t.toLowerCase(),r=new RegExp(`\\b${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i"),i=[];for(let o of v(Number.MAX_SAFE_INTEGER,s)){let l;try{l=x(o.file,"utf8")}catch{continue}let c=0,a=0,u=0,h=0,d=!1,f="";for(let $ of l.split(`
4
+ `)){let g=$.toLowerCase(),w=g.indexOf(e);if(w<0)continue;let y=0;for(;w>=0;)y++,w=g.indexOf(e,w+e.length);c+=y;let L=g.includes('"role":"user"'),P=g.includes('"role":"toolresult"')||g.includes('"role":"tool"');L?a+=y:P?h+=y:u+=y,r.test($)&&(d=!0),f||(f=Z(H($),e))}if(c===0)continue;let O=(a>0?100:0)+(u>0?10:0)+Math.min(h,5)+(d?5:0)+Math.min(c,10)/100;i.push({row:o,matches:c,score:O,snippet:f})}return i.sort((o,l)=>l.score-o.score||l.row.modified-o.row.modified).slice(0,n)}function Q(t){let n=[`# Session ${t.split(/[\\/]/).pop()??t}`,""];for(let s of x(t,"utf8").split(`
5
+ `)){if(!s.trim())continue;let e;try{e=JSON.parse(s)}catch{continue}if(e.type!=="message")continue;let r=H(s);r&&n.push(`## ${e.message?.role??"unknown"}`,"",r,"")}return n.join(`
6
+ `).trimEnd()}export{W as collectChecks,Q as exportSessionMarkdown,G as installIntegrity,v as listSessionFiles,ie as runDoctor,ce as runModels,le as runSessions,K as searchSessions};
@@ -0,0 +1,3 @@
1
+ import"./chunk-WOT6VMZA.js";import{createInterface as l}from"node:readline";function f(r){let{agent:u}=r,m=t=>r.output.write(`${JSON.stringify(t)}
2
+ `),e=(t,a,c,s={})=>m({...t!==void 0?{id:t}:{},type:"response",command:a,success:c,...s}),p=u.subscribe(t=>{let a=r.encodeEvent?r.encodeEvent(t):`${JSON.stringify(t)}
3
+ `;a!==void 0&&r.output.write(a)}),d=null;return new Promise(t=>{let a=l({input:r.input});a.on("line",c=>{if(c.trim()==="")return;let s;try{s=JSON.parse(c)}catch{e(void 0,"parse",!1,{error:"a command must be one JSON object per line"});return}let{id:n,type:i}=s;if(i==="prompt"){if(typeof s.message!="string"||s.message.trim()===""){e(n,"prompt",!1,{error:"prompt needs a message"});return}if(d){e(n,"prompt",!1,{error:"a prompt is already running; abort it or wait"});return}e(n,"prompt",!0),d=u.prompt(s.message).catch(o=>{m({type:"error",message:o instanceof Error?o.message:String(o)})}).finally(()=>{d=null});return}if(i==="abort"){u.abort().then(()=>e(n,"abort",!0)).catch(o=>e(n,"abort",!1,{error:o instanceof Error?o.message:String(o)}));return}if(i==="get_state"){e(n,"get_state",!0,{data:{running:d!==null,...r.state?.()??{}}});return}if(i==="get_last_assistant_text"){e(n,"get_last_assistant_text",!0,{data:{text:u.getLastAssistantText()??null}});return}e(n,String(i??"unknown"),!1,{error:`unknown command ${String(i)}`})}),a.on("close",()=>{(d??Promise.resolve()).then(async()=>{p(),await u.dispose(),t()})})})}export{f as runRpc};
@@ -0,0 +1,4 @@
1
+ import{execFile as x}from"node:child_process";import{closeSync as C,existsSync as f,mkdirSync as v,openSync as N,readFileSync as E,realpathSync as k,statSync as T,unlinkSync as w,writeFileSync as _}from"node:fs";import{homedir as p}from"node:os";import{delimiter as $,dirname as I,join as u,sep as m}from"node:path";var l="howtocode",g=["npm","npm.cmd","npm.exe"],A=2e4,O=2,P=12e4,R=600*1e3,U=5*1e3;function L(e,t){let r=s=>{let i=s.trim().split("-")[0]?.split("+")[0]??"";if(/^\d+(\.\d+)*$/.test(i))return i.split(".").map(c=>Number(c))},n=r(e),o=r(t);if(!n||!o)return 0;let a=Math.max(n.length,o.length);for(let s=0;s<a;s+=1){let i=n[s]??0,c=o[s]??0;if(i>c)return 1;if(i<c)return-1}return 0}function H(e,t){return e.includes("-")?!1:L(e,t)>0}var h=(e,t,r)=>new Promise(n=>{x(e,t,{cwd:r.cwd,timeout:r.timeoutMs,windowsHide:!0},(o,a,s)=>{let i=o?o.code:void 0,c=typeof i=="number"?i:o?1:0,d=typeof i=="string"?i:void 0;n({code:c,stdout:String(a??""),stderr:String(s??""),...d?{errorCode:d}:{}})})}),D=new Set(["ENOENT","EACCES","EINVAL","EPERM"]);function b(){let e=I(process.execPath);for(let r of[["..","lib","node_modules","npm","bin","npm-cli.js"],["node_modules","npm","bin","npm-cli.js"]]){let n=u(e,...r);if(f(n))return{command:process.execPath,args:[n]}}let t=process.env.PATH?.split($).filter(Boolean)??[];for(let r of t)for(let n of g){let o=u(r,n);if(!(n.endsWith(".cmd")||n.endsWith(".bat"))&&f(o))return{command:o,args:[]}}if(process.platform==="win32")for(let r of t)for(let n of g){if(!n.endsWith(".cmd")&&!n.endsWith(".bat"))continue;let o=u(r,n);if(f(o))return{command:process.env.ComSpec||"cmd.exe",args:["/d","/s","/c",`"${o}"`]}}}var F="could not check for a newer version: npm was not found, so run `npm install -g howtocode@latest` yourself",G="could not check for a newer version: the registry did not answer";function Q(e){if(e.latest===void 0)return`${e.message} (this is why no update was offered; /update retries it)`}function K(e){if(e.code===-2)return!0;let t=e.errorCode??(e.stderr??"").trim();return D.has(t)}function S(){let t=process.env.HOWTOCODE_CODING_AGENT_DIR?.trim()||u(p(),".howtocode","agent");try{v(t,{recursive:!0})}catch{}return u(t,"update.lock")}function B(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}function y(e,t){try{let r=t-T(e).mtimeMs,n=E(e,"utf8").trim();return{pid:/^\d+$/.test(n)?Number.parseInt(n,10):void 0,ageMs:r}}catch{return}}function W(e){return e?e.pid===void 0?e.ageMs<U:B(e.pid)?e.ageMs<R:!1:!1}function j(e=Date.now()){let t=S();for(let r=0;r<2;r+=1)try{let n=N(t,"wx",384);try{_(n,String(process.pid))}finally{C(n)}return!0}catch(n){if(n.code!=="EEXIST")return!0;if(W(y(t,e)))return!1;try{w(t)}catch{return!1}}return!1}function J(){let e=S();try{let t=y(e,Date.now());if(t&&t.pid!==void 0&&t.pid!==process.pid)return;w(e)}catch{}}async function M(e){let t=e?.runner??h,r=b();if(!r)return{reason:"no-npm"};let n="no-answer";for(let o=0;o<O;o+=1){let a;try{a=await t(r.command,[...r.args,"view",`${l}@latest`,"version","--prefer-online"],{cwd:p(),timeoutMs:e?.timeoutMs??A})}catch{n="no-answer";continue}if(a.code!==0){if(K(a))return{reason:"no-npm"};n="no-answer";continue}let s=a.stdout.trim().split(`
2
+ `).pop()?.trim()??"";if(/^\d+\.\d+/.test(s))return{version:s};n="no-answer"}return{reason:n}}async function Z(e){return(await M(e)).version}async function ee(e,t){let r=await M(t);if(!r.version)return{current:e,available:!1,message:r.reason==="no-npm"?F:G};let n=r.version;return H(n,e)?{current:e,latest:n,available:!0,message:`HowToCode ${n} is available (you have ${e})`}:{current:e,latest:n,available:!1,message:`HowToCode ${e} is up to date`}}function V(e,t,r){let n=`${t}
3
+ ${e}`.split(`
4
+ `).map(d=>d.trim()).filter(Boolean).filter(d=>!/^npm warn\b/i.test(d)),o=n.filter(d=>/^npm error\b/i.test(d)||/\bERR!/i.test(d)),s=(o.find(d=>/^npm error code\b/i.test(d))??o.at(-1)??n.at(-1)??r??"").replace(/^npm error\s*/i,"").trim(),i=`${n.join(" ")} ${r??""}`,c="";return/EACCES|EPERM|permission denied/i.test(i)?c=" \u2014 npm could not write its files (permission denied); close other HowToCode windows and run the terminal as Administrator":/EBUSY|EEXIST|ENOTEMPTY|resource busy|being used by another process/i.test(i)?c=" \u2014 a file is in use; close other HowToCode windows and try again":/ENOSPC/i.test(i)?c=" \u2014 the disk is full":/ETIMEDOUT|ENOTFOUND|EAI_AGAIN|ECONNREFUSED/i.test(i)&&(c=" \u2014 npm could not reach the registry"),{detail:s,hint:c}}async function ne(e){let t=e?.runner??h;if(!j())return{ok:!1,message:"another HowToCode is already installing an update"};try{let r=b();if(!r)return{ok:!1,message:"npm was not found, so run `npm install -g howtocode@latest` yourself"};let n=e?.version?`${l}@${e.version}`:`${l}@latest`,o=await t(r.command,[...r.args,"install","-g",n],{cwd:p(),timeoutMs:e?.timeoutMs??P});if(o.code!==0){let{detail:a,hint:s}=V(o.stdout,o.stderr,o.errorCode);return{ok:!1,message:`the update did not install${s}${a?`: ${a}`:""}`}}return{ok:!0,version:e?.version,message:"updated; it takes effect the next time HowToCode starts"}}catch(r){return{ok:!1,message:`the update failed: ${r instanceof Error?r.message:String(r)}`}}finally{J()}}function te(e=process.argv[1]){if(!e)return!1;let t=e;try{t=k(e)}catch{}return t.includes(`${m}node_modules${m}${l}${m}`)}function re(e){try{return JSON.parse(E(e,"utf8")).autoUpdate!==!1}catch{return!0}}export{l as a,A as b,O as c,P as d,R as e,U as f,L as g,H as h,b as i,F as j,G as k,Q as l,B as m,j as n,J as o,Z as p,ee as q,V as r,ne as s,te as t,re as u};
@@ -0,0 +1,12 @@
1
+ import{j as w,l as k}from"./chunk-MVVEYKN6.js";import"./chunk-WOT6VMZA.js";import{createInterface as P}from"node:readline";var $=1;function O(t){if(!t||Object.keys(t).length===0)return"";let c=d=>JSON.stringify(d).replace(/</g,"\\u003c"),r=[];t.place&&r.push(`place: ${c(t.place)}`),t.selection&&t.selection.length>0&&r.push(`selection: ${c(t.selection)}`),t.connected&&r.push(`connected: ${c(t.connected)}`);for(let[d,f]of Object.entries(t))d==="place"||d==="selection"||d==="connected"||r.push(`${d.replace(/[^\w.-]/g,"_")}: ${c(f)}`);return`<session_context>
2
+ ${r.join(`
3
+ `)}
4
+ </session_context>
5
+
6
+ `}function E(t){return/^(get_|list_|read_|snapshot|diff_|audit|datastore_get|datastore_list|roblox_status)/.test(t)?"read":/^(search|grep|find)/.test(t)?"search":/(execute|run_|luau)/.test(t)?"execute":/^(set_|create_|delete_|clone_|reparent_|edit_|insert_|send_|publish_|upload_|generate_|datastore_set|datastore_delete)/.test(t)?"edit":"other"}function N(t){if(typeof t=="string")return t;let c=t?.content;return Array.isArray(c)?c.map(r=>r.type==="text"?r.text??"":`[${r.type??"?"}]`).join(`
7
+ `):JSON.stringify(t??null)}function J(t){let c=new Map,r=new Map,d=0,f=n=>{t.output.write(`${JSON.stringify({jsonrpc:"2.0",...n})}
8
+ `)},_=(n,i)=>f({id:n,result:i}),l=(n,i,u)=>f({id:n,error:{code:i,message:u}}),m=(n,i)=>f({method:"session/update",params:{sessionId:n,update:i}});async function A(n){let i=n.params??{},u=n.id===void 0;switch(n.method){case"initialize":return _(n.id,{protocolVersion:$,agentCapabilities:{loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!0}},authMethods:[],agentInfo:{name:t.name??"howtocode",title:"HowToCode",version:t.version}});case"session/new":{let s=typeof i.cwd=="string"?i.cwd:process.cwd();try{let a=await t.createAgent(s);d+=1;let p=`sess_${Date.now().toString(36)}_${d}`;return c.set(p,a),_(n.id,{sessionId:p})}catch(a){return l(n.id,-32e3,a instanceof Error?a.message:String(a))}}case"session/prompt":{let s=String(i.sessionId??""),a=c.get(s);if(!a)return l(n.id,-32602,`unknown session ${s}`);if(r.has(s))return l(n.id,-32e3,"a prompt is already running in this session");let g=(Array.isArray(i.prompt)?i.prompt:[]).map(e=>e.type==="text"?e.text??"":e.type==="resource"&&e.resource?.text!==void 0?`<file uri=${JSON.stringify(e.resource.uri??"")}>
9
+ ${e.resource.text}
10
+ </file>`:"").filter(e=>e!=="").join(`
11
+
12
+ `);if(g==="")return l(n.id,-32602,"the prompt has no text");let R=i._meta,v=O(R?.howtocode?.context)+g,x=!1,b=k(),S=e=>{let o=b.push(e);return o?w(o):""},C=a.subscribe(e=>{if(e.type==="message_update"){let o=e.assistantMessageEvent;if(o?.type==="text_delta"&&o.delta){let y=S(o.delta);y&&m(s,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:y}})}else if(o?.type==="thinking_delta"&&o.delta){let y=S(o.delta);y&&m(s,{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:y}})}}else if(e.type==="tool_execution_start"){let o=e;m(s,{sessionUpdate:"tool_call",toolCallId:o.toolCallId,title:o.toolName,kind:E(o.toolName),status:"in_progress",rawInput:o.args??{}})}else if(e.type==="tool_execution_end"){let o=e;m(s,{sessionUpdate:"tool_call_update",toolCallId:o.toolCallId,status:o.isError?"failed":"completed",content:[{type:"content",content:{type:"text",text:N(o.result)}}]})}}),I=a.prompt(v).then(()=>{let e=a.lastStopReason?.(),o=x||e==="aborted"?"cancelled":e==="length"?"max_tokens":"end_turn";_(n.id,{stopReason:o})}).catch(e=>{x?_(n.id,{stopReason:"cancelled"}):l(n.id,-32e3,e instanceof Error?e.message:String(e))}).finally(()=>{let e=b.flush();e&&m(s,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:w(e)}}),C(),r.delete(s),h.delete(s)});r.set(s,I),h.set(s,()=>{x=!0});return}case"session/cancel":{let s=String(i.sessionId??"");r.has(s)&&h.get(s)?.(),await c.get(s)?.abort();return}default:u||l(n.id,-32601,`method not found: ${n.method}`)}}let h=new Map;return new Promise(n=>{let i=P({input:t.input}),u=new Set;i.on("line",s=>{if(s.trim()==="")return;let a;try{a=JSON.parse(s)}catch{l(null,-32700,"parse error");return}let p=A(a).catch(g=>{a.id!==void 0&&l(a.id,-32603,g instanceof Error?g.message:String(g))}).finally(()=>u.delete(p));u.add(p)}),i.on("close",()=>{Promise.allSettled([...u,...r.values()]).then(async()=>{await Promise.allSettled([...c.values()].map(s=>s.dispose())),n()})})})}export{$ as ACP_PROTOCOL_VERSION,O as renderSessionContext,J as runAcp};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-ORJ2QZBG.js";import"./chunk-WOT6VMZA.js";export{a as expandFileReferences};
@@ -0,0 +1,2 @@
1
+ import{mkdirSync as d,readFileSync as s,writeFileSync as p}from"node:fs";import{dirname as l,join as f}from"node:path";function u(r){if(!r||r.length===0)return[];let n=new Set(r.map(e=>e.trim().toLowerCase())),t=[];for(let e of["free","vip","pro"])n.has(e)&&t.push(e);return t}function y(r){let n=r.filter(t=>t!=="unknown");return n.length>0?`(${n.join(", ")})`:""}function g(r){let n=new Map;for(let[t,e]of r){let o=u(e);o.length>0&&n.set(t,o)}return n}function w(r){let n=new Map,t;try{t=JSON.parse(s(f(r,"models.json"),"utf8"))}catch{return n}let e=o=>Array.isArray(o)?o.filter(i=>i==="free"||i==="vip"||i==="pro"):[];for(let o of Object.values(t?.providers??{}))for(let i of o?.models??[]){if(typeof i?.id!="string")continue;let a=e(i.plans);a.length>0?n.set(i.id,a):(i.plan==="free"||i.plan==="vip"||i.plan==="pro")&&n.set(i.id,[i.plan])}return n}function v(r,n,t=Date.now()){try{d(l(r),{recursive:!0}),p(r,`${JSON.stringify({at:t,ids:[...n]},null,2)}
2
+ `)}catch{}}function h(r,n=1440*60*1e3,t=Date.now()){let e;try{e=JSON.parse(s(r,"utf8"))}catch{return}if(!(typeof e?.at!="number"||!Array.isArray(e.ids))&&!(t-e.at>n))return{at:e.at,ids:e.ids.filter(o=>typeof o=="string")}}export{u as a,y as b,g as c,w as d,v as e,h as f};
@@ -0,0 +1,2 @@
1
+ import{spawnSync as s}from"node:child_process";import{accessSync as d,constants as b}from"node:fs";import{join as l}from"node:path";function c(r){try{return d(r,b.X_OK),!0}catch{return!1}}function w(r=process.platform,e=process.env.PATH??""){let n=e.split(":").filter(Boolean),o=t=>n.map(i=>l(i,t)).find(c);if(r==="linux"){let t=o("bwrap");return t&&s(t,["--ro-bind","/","/","--","true"],{stdio:"ignore",timeout:3e3}).status===0?"bubblewrap":void 0}if(r==="darwin")return o("sandbox-exec")?"seatbelt":void 0}function a(r,e){return r==="bubblewrap"?["bwrap","--die-with-parent","--new-session","--ro-bind","/","/","--dev","/dev","--proc","/proc","--tmpfs","/tmp","--bind",e.cwd,e.cwd,"--bind",e.agentDir,e.agentDir,"--chdir",e.cwd,"--",...e.argv]:["sandbox-exec","-p",["(version 1)","(deny default)","(allow process*)","(allow signal)","(allow sysctl-read)","(allow mach-lookup)","(allow network*)","(allow file-read*)",`(allow file-write* (subpath "${e.cwd}") (subpath "${e.agentDir}") (subpath "/tmp") (subpath "/private/tmp") (subpath "/private/var/folders"))`,""].join(`
2
+ `),...e.argv]}function x(r){return r==="bubblewrap"?"sandbox: bubblewrap \u2014 project writable, rest of the filesystem read-only":"sandbox: seatbelt \u2014 project writable, rest of the filesystem read-only"}function g(r,e){let n=s(a(r,e)[0],a(r,e).slice(1),{stdio:"inherit",env:{...process.env,HOWTOCODE_SANDBOXED:"1"}});return n.error?(console.error(`sandbox: could not start ${r}: ${n.error.message}`),1):n.status??1}export{w as a,a as b,x as c,g as d};
@@ -0,0 +1 @@
1
+ import{closeSync as S,fsyncSync as d,openSync as f,renameSync as i,rmSync as t,writeSync as a}from"node:fs";import{dirname as u,join as E}from"node:path";function l(o,m,s){let r=E(u(o),`.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}.tmp`),e=f(r,"w",s?.mode);try{a(e,m),d(e)}finally{S(e)}try{i(r,o)}catch(n){let c=n.code;if(c!=="EPERM"&&c!=="EBUSY"&&c!=="EACCES")throw t(r,{force:!0}),n;t(o,{force:!0});try{i(r,o)}catch(y){throw t(r,{force:!0}),y}}}export{l as a};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g,h}from"./chunk-27TRKD65.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";export{a as DEFAULT_WORKBENCH_SETTINGS,d as markWelcomeSeen,b as readWorkbenchSettings,f as rightClickPastesHere,g as writeAgentsSetting,e as writeRightClickPasteSetting,h as writeStringSetting,c as writeWorkbenchSetting};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-3YOYZOXG.js";import"./chunk-FLP47RIR.js";import"./chunk-WOT6VMZA.js";export{h as CLI_CLIENT_HEADER,a as CLI_SIGNING_KEY_ID,i as cliClientHeader,c as cliSignaturePayload,f as cliSigningKeyFingerprint,e as cliSigningKeyMatchesPanel,b as cliSigningPublicKey,d as createNonce,g as describeClient,j as signLoginRequest};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-3FYCFLNK.js";import"./chunk-WOT6VMZA.js";export{a as PROXY_SETTING_KEY,b as configuredProxy,c as environmentProxy,e as installProxy,d as validateProxyUrl};
@@ -0,0 +1 @@
1
+ var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f}from"./chunk-TUXY64DT.js";import"./chunk-WOT6VMZA.js";export{b as planBadge,d as plansByModel,a as plansFor,f as readReachable,c as tiersFrom,e as writeReachable};
@@ -0,0 +1,2 @@
1
+ import{b as c,d as l}from"./chunk-27TRKD65.js";import{H as s}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import{a as i,b as r}from"./chunk-FLP47RIR.js";import"./chunk-WOT6VMZA.js";var d=[["/connect","sign in to howtofix.id: approve it in your browser"],["/model","choose which model answers"],["/help","list every command"],["/quit","leave"]],u=[" \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u255D \u2588\u2588\u2557\u2588\u2588\u2551 "," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D "],g=[" _ _ _____ ","| | | | __ __ | ___|","| |_| | \\ \\/ / | |_ ","| _ | > < | _| ","|_| |_| /_/\\_\\ |_| "];function m(){if(process.platform==="win32")return!1;let e=(process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"").toLowerCase();return e===""||e==="c"||e==="posix"||!e.includes("utf-8")&&!e.includes("utf8")?!1:!/ja|ko|zh|_kr|_jp|_cn|_tw|_hk/.test(e)}function h(){return m()?u:g}var _="https://howtofix.id/cli";function p(e){let n=process.env.HOME??"",t=n!==""&&e.startsWith(n)?`~${e.slice(n.length)}`:e,o=t.split("/").filter(Boolean);return o.length>3?`\u2026/${o.slice(-2).join("/")}`:t}function f(e){let n=e.signedIn?d.filter(([t])=>t!=="/connect"):d;return[...h(),"",`${i} ${r} \u2014 a terminal coding agent. Describe the change you want and it reads, edits and runs the code in front of you.`,"",` working in ${p(e.cwd)}`,...e.note?[` session ${e.note}`]:[],"",...e.signedIn?[" already signed in to howtofix.id",""]:[],...n.map(([t,o])=>` ${t.padEnd(11)}${o}`),"",' Or just start typing. Every message goes to the model; anything beginning with "/" stays local.'].join(`
2
+ `)}function v(){return[{value:"connect",label:"Sign in to howtofix.id",description:"approve the sign-in in your browser"},{value:"ready",label:"I have a key \u2014 just give me the prompt",description:"drops you at the prompt; run /connect whenever you like"},{value:"release",label:"What's in this release",description:`opens the ${r} notes in your browser`}]}async function E(e,n,t){c(s).welcomeSeen||(l(s),t(`welcome to ${i}`,f(e)),!e.signedIn&&await new Promise(o=>{n("First run \u2014 how do you want to begin?",v(),a=>{a==="connect"&&e.runSlash("/connect"),a==="release"&&e.openExternal(_),o()},()=>o())}))}export{E as maybeShowWelcome};
@@ -0,0 +1,2 @@
1
+ var C=new Set(["think"]),l;function E(n){let t=new WeakSet,o=e=>{if(e===null||typeof e!="object")return e;if(t.has(e))return"[circular]";if(t.add(e),Array.isArray(e))return e.map(o);let r=e,s={};for(let i of Object.keys(r).sort())s[i]=o(r[i]);return s};try{return JSON.stringify(o(n))??""}catch{return""}}function x(n,t){if(C.has(n))return;let o=`${n}\0${E(t)}`,e=l&&l.signature===o?l.count+1:1;return l={signature:o,count:e},e>=3?{repeats:e}:void 0}function Q(){l=void 0}function v(n,t){return`Refused: ${n} has been called ${t} times in a row with identical arguments, so the last attempt cannot have changed anything. Do not repeat it. Either use different arguments, use a different tool, or stop and report what you found and what is blocking you.`}var $=/^-[a-zA-Z0-9_-]/;function h(n,t){switch(t){case"number":return/^\d+$/.test(n);case"string":return!0;default:return!1}}function O(n,t){if(!/^-[^-]/.test(n)||n.includes("="))return!1;for(let o=1;o<n.length;o++){let e=t[`-${n[o]}`];if(!e)return!1;if(e!=="none")return h(n.slice(o+1),e)}return!0}function L(n,t,o){let e=t;for(;e<n.length;){let r=n[e];if(!r){e++;continue}if(r==="--")break;if($.test(r)){if(/^-\d+$/.test(r)&&o.safeFlags["-n"]){e++;continue}let s=r.includes("="),[i="",...c]=r.split("="),a=o.safeFlags[i];if(!a){if(!O(r,o.safeFlags))return!1;e++;continue}if(a==="none"){if(s)return!1;e++;continue}if(a==="optional"){e++;continue}if(s){if(!h(c.join("="),a))return!1;e++;continue}let y=n[e+1];if(y===void 0||!h(y,a))return!1;e+=2;continue}if(o.allowPositional===!1)return!1;e++}return!0}var S={"--all":"none","--branches":"none","--tags":"none","--remotes":"none"},g={"--oneline":"none","--graph":"none","--decorate":"none","--no-decorate":"none","--date":"string","--relative-date":"none"},u={"--max-count":"number","-n":"number"},p={"--stat":"none","--numstat":"none","--shortstat":"none","--name-only":"none","--name-status":"none"},d={"--color":"none","--no-color":"none"},m={"--patch":"none","-p":"none","--no-patch":"none","--no-ext-diff":"none","-s":"none"},F={"--author":"string","--committer":"string","--grep":"string"},I={"-l":"none","--list":"none","-a":"none","-r":"none","-v":"none","-vv":"none","-i":"none"},A={"git status":{safeFlags:{"-s":"none","--short":"none","-b":"none","--branch":"none","-u":"optional","--untracked-files":"optional","--porcelain":"optional","--ignored":"none","--long":"none","--no-renames":"none",...d}},"git diff":{safeFlags:{...p,...d,...m,"--cached":"none","--staged":"none","--word-diff":"none","--check":"none","--quiet":"none","--exit-code":"none","--no-renames":"none","--diff-filter":"string","--relative":"string","--full-index":"none","--binary":"none","--abbrev":"number","--unified":"number","-U":"number","--ignore-all-space":"none","--ignore-space-change":"none","--ignore-blank-lines":"none"}},"git log":{safeFlags:{...g,...u,...p,...d,...m,...F,...S,"--since":"string","--after":"string","--until":"string","--before":"string","--follow":"none","--no-merges":"none","--merges":"none","--first-parent":"none","--reverse":"none","--skip":"number","--all":"none","--format":"string","--pretty":"string","--abbrev-commit":"none","--no-abbrev-commit":"none","--left-right":"none"}},"git show":{safeFlags:{...p,...d,...m,...g,"--format":"string","--pretty":"string","--abbrev-commit":"none","--no-patch":"none","-q":"none"}},"git shortlog":{safeFlags:{...u,"-s":"none","--summary":"none","-n":"none","--numbered":"none","-e":"none","--email":"none","-sn":"none","-ns":"none","--all":"none"}},"git reflog":{safeFlags:{...u,...g,...F,"--all":"none","--date":"string"}},"git blame":{safeFlags:{"-L":"string","-w":"none","-c":"none","-n":"none","-s":"none","-e":"none","-p":"none","--porcelain":"none","--line-porcelain":"none","--date":"string","--since":"string","-C":"none","-M":"none"}},"git ls-files":{safeFlags:{"-m":"none","--modified":"none","-o":"none","--others":"none","-i":"none","--ignored":"none","-s":"none","--stage":"none","-d":"none","--deleted":"none","-c":"none","--cached":"none","-u":"none","--unmerged":"none","--exclude-standard":"none","--error-unmatch":"none","-z":"none"}},"git ls-remote":{safeFlags:{"--heads":"none","--tags":"none","--refs":"none","--symref":"none"}},"git rev-parse":{safeFlags:{"--short":"optional","--abbrev-ref":"none","--verify":"none","--quiet":"none","--git-dir":"none","--show-toplevel":"none","--show-cdup":"none","--is-inside-work-tree":"none","--is-bare-repository":"none","--symbolic-full-name":"none","--abbrev":"optional"}},"git rev-list":{safeFlags:{...u,"--count":"none","--all":"none","--objects":"none","--reverse":"none","--max-parents":"number","--min-parents":"number","--no-merges":"none","--first-parent":"none","--abbrev-commit":"none"}},"git describe":{safeFlags:{"--tags":"none","--all":"none","--long":"none","--always":"none","--dirty":"none","--abbrev":"number","--match":"string","--exclude":"string","--first-parent":"none"}},"git cat-file":{safeFlags:{"-p":"none","-t":"none","-s":"none","-e":"none","--batch-check":"none"}},"git for-each-ref":{safeFlags:{"--format":"string","--count":"number","--sort":"string","--points-at":"string","--merged":"string","--no-merged":"string"}},"git grep":{safeFlags:{"-n":"none","--line-number":"none","-i":"none","--ignore-case":"none","-l":"none","--files-with-matches":"none","-c":"none","--count":"none","-w":"none","--word-regexp":"none","-E":"none","--extended-regexp":"none","-F":"none","--fixed-strings":"none","--cached":"none","--untracked":"none","-e":"string","--and":"none","--or":"none","--not":"none"}},"git merge-base":{safeFlags:{"--all":"none","--is-ancestor":"none","--fork-point":"none","--octopus":"none"}},"git stash list":{safeFlags:{...g}},"git worktree list":{safeFlags:{"--porcelain":"none","-v":"none","--verbose":"none","-z":"none"}},"git branch":{safeFlags:{...I,"--merged":"string","--no-merged":"string","--contains":"string","--no-contains":"string","--sort":"string","--format":"string","--points-at":"string","--column":"none","--show-current":"none"},dangerous:n=>{let t=new Set(["--merged","--no-merged","--contains","--no-contains","--sort","--format","--points-at"]),o=!1;for(let e of n){if(o){o=!1;continue}if(t.has(e)){o=!0;continue}if(!e.startsWith("-"))return!0}return!1}},"git tag":{safeFlags:{"-l":"none","--list":"none","-n":"number","--contains":"string","--no-contains":"string","--merged":"string","--sort":"string","--points-at":"string","--column":"none"},dangerous:n=>{let t=new Set(["--contains","--no-contains","--merged","--sort","--points-at"]),o=!1;for(let e of n){if(o){o=!1;continue}if(t.has(e)){o=!0;continue}if(!e.startsWith("-"))return!0}return!1}},"git remote":{safeFlags:{"-v":"none","--verbose":"none"},dangerous:n=>n.some(t=>!t.startsWith("-"))},"git config --get":{safeFlags:{"--local":"none","--global":"none","--system":"none","--get-all":"none","--get-regexp":"none","--list":"none","-l":"none","--show-origin":"none","--null":"none","-z":"none"}}},M=["ls","pwd","cat","head","tail","wc","which","whoami","date","echo","sleep","true","false","type","test","seq","basename","dirname","realpath","stat","file","du","df","tree","uname","hostname","id","groups","tty","cal","uptime","free","locale","printf","grep","rg","fd","jq","bat","column","paste","nl","expand","fold","fmt","md5sum","sha1sum","sha256sum","sha512sum","b2sum","cksum","diff","cmp"],P={find:{safeFlags:{"-name":"string","-iname":"string","-type":"string","-maxdepth":"number","-mindepth":"number","-newer":"string","-path":"string","-not":"none","-print":"none","-print0":"none","-empty":"none","-size":"string","-mtime":"number","-atime":"number","-perm":"string","-L":"none","-H":"none","-P":"none"},dangerous:n=>n.some(t=>/^-(delete|exec|execdir|ok|okdir|fprint0?|fls|fprintf)$/.test(t))},sort:{safeFlags:{"-n":"none","-r":"none","-u":"none","-k":"string","-t":"string","-f":"none","-h":"none","-V":"none","-s":"none","-c":"none","-m":"none","-b":"none","-z":"none"}},uniq:{safeFlags:{"-c":"none","-d":"none","-u":"none","-i":"none","-f":"number","-s":"number","-w":"number"}},cut:{safeFlags:{"-d":"string","-f":"string","-c":"string","-b":"string","-s":"none","--complement":"none","-z":"none"}},tr:{safeFlags:{"-d":"none","-s":"none","-c":"none"}},node:{safeFlags:{"-v":"none","--version":"none"},allowPositional:!1},python:{safeFlags:{"--version":"none"},allowPositional:!1},python3:{safeFlags:{"--version":"none"},allowPositional:!1},npm:{safeFlags:{"--version":"none","-v":"none"},allowPositional:!1},sed:{safeFlags:{"-n":"none","--quiet":"none","-e":"string","-E":"none","-r":"none","--regexp-extended":"none","-s":"none","-u":"none","-z":"none","--posix":"none"},dangerous:n=>n.some(t=>/^-i|^--in-place/.test(t)||/\b[we]\s/.test(t)||/^[we]$/.test(t))},awk:{safeFlags:{"-F":"string","-v":"string","-f":"string"},dangerous:n=>n.some(t=>/\bsystem\s*\(|\|\s*"|>\s*"/.test(t))},xxd:{safeFlags:{"-l":"number","-s":"string","-c":"number","-g":"number","-p":"none","-i":"none","-u":"none","-b":"none","-e":"none","-o":"number"},dangerous:n=>n.some(t=>t==="-r"||/^-[a-z]*r/.test(t))}},T={"npm ls":{safeFlags:{"--depth":"number","--json":"none","--long":"none","--parseable":"none","--all":"none","--prod":"none","--dev":"none","--omit":"string","--link":"none","--global":"none","-g":"none","--silent":"none"}},"npm view":{safeFlags:{"--json":"none","--registry":"string"}},"docker ps":{safeFlags:{"-a":"none","--all":"none","-q":"none","--quiet":"none","--no-trunc":"none","--format":"string","-n":"number","--last":"number","-s":"none","--size":"none","--filter":"string"}},"docker images":{safeFlags:{"-a":"none","--all":"none","-q":"none","--quiet":"none","--no-trunc":"none","--format":"string","--filter":"string","--digests":"none"}},"docker inspect":{safeFlags:{"--format":"string","-f":"string","-s":"none","--size":"none","--type":"string"}},"kubectl get":{safeFlags:{"-o":"string","--output":"string","-n":"string","--namespace":"string","-A":"none","--all-namespaces":"none","--no-headers":"none","-l":"string","--selector":"string","--show-labels":"none","-w":"none","--watch":"none","--sort-by":"string"}},"kubectl describe":{safeFlags:{"-n":"string","--namespace":"string","-l":"string","--selector":"string"}},"cargo tree":{safeFlags:{"--depth":"number","-e":"string","--edges":"string","--no-dev-dependencies":"none","--prefix":"string","-i":"string","--invert":"string","-p":"string","--package":"string"}},"go version":{safeFlags:{}}},G=["cd","alias","history","arch","ip addr","ifconfig"];function z(n){if(!/\$\(|`|\$\{|>|</.test(n)&&!/(?<!&)&(?!&)/.test(n))return n.split(/\|\||&&|;|\|/).map(t=>t.trim()).filter(t=>t.length>0)}function D(n){let t=n.some(e=>/^cd\b/.test(e)),o=n.some(e=>/^git\b/.test(e));return t&&o}function q(n){let t=[],o=/'[^']*'|"[^"]*"|\S+/g;for(let e of n.match(o)??[])t.push(e.length>=2&&/^['"]/.test(e)?e.slice(1,-1):e);return t}function j(n){if(n.length===0)return;let[t="",o=""]=n,e=`${t} ${o}`;if(t==="git"&&o==="config"){let r=n[2];return r==="--get"||r==="--get-all"||r==="--get-regexp"||r==="-l"||r==="--list"?{name:"git config --get",rest:n.slice(3)}:void 0}return t==="git"&&o==="stash"?n[2]==="list"?{name:"git stash list",rest:n.slice(3)}:void 0:t==="git"&&o==="worktree"?n[2]==="list"?{name:"git worktree list",rest:n.slice(3)}:void 0:t==="git"&&A[`git ${o}`]?{name:`git ${o}`,rest:n.slice(2)}:T[e]?{name:e,rest:n.slice(2)}:{name:t,rest:n.slice(1)}}var N=new Set(["echo","printf"]);function U(n){let t=q(n),o=j(t);if(!o)return!1;let{name:e,rest:r}=o;if(N.has(e)&&r.some(i=>i.includes("$")||i.includes("`")))return!1;let s=A[e]??P[e]??T[e];return s?s.dangerous?.(r)?!1:L(r,0,s):!!(M.includes(e)||G.includes(e))}function b(n){let t=z(n);return!t||t.length===0||D(t)?!1:t.every(U)}var W=["suggest","auto-edit","full-auto"],rn={suggest:"suggest: ask before every edit and command","auto-edit":"auto-edit: edits run, commands ask","full-auto":"full-auto: nothing asks"};function sn(n){return W.includes(n)}var k={read:0,write:1,exec:2},B={suggest:"read","auto-edit":"write","full-auto":"exec"},H={read:"read",grep:"read",find:"read",ls:"read",think:"read",ask:"read",todo:"read",context:"read",web_search:"read",web_fetch:"read",lsp:"read",quality:"read",workflow:"exec",browser:"exec",goal:"read",enter_plan_mode:"read",exit_plan_mode:"read",edit:"write",write:"write",bash:"exec",powershell:"exec",task:"exec"};function R(n){let t=H[n];return t||(n.startsWith("mcp__")?"write":"exec")}var V=new Set(["sudo","doas","env","nohup","time","exec","command","nice","setsid","stdbuf"]),Y=new Set(["-u","-g","-p","-C","-S","-U","--user","--group","--prompt","--close-from","--chdir","--setenv","--unset"]);function Z(n){let t=(n.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(s=>s.replace(/^['"]|['"]$/g,"")),o=0;for(;o<t.length;){let s=t[o]??"";if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(s)||V.has(s)){o++;continue}if(s.startsWith("-")){o+=Y.has(s)?2:1;continue}break}let e=t[o];if(e===void 0)return;let r=e.split("/").pop()??e;if(r==="rm"){let s=t.slice(o+1),i=s.some(a=>/^-[a-zA-Z]*r[a-zA-Z]*$/i.test(a)||a==="--recursive"),c=s.find(a=>!a.startsWith("-"));return i&&(c===void 0||/^(?:\/|\/\*|~|~\/\*|\$HOME|\$HOME\/\*|\*)$/.test(c))?"recursive delete of the filesystem root or home":void 0}if(r==="dd")return t.slice(o+1).some(s=>/^of=\/dev\/(?:sd|nvme|hd|vd)/.test(s))?"raw write to a block device":void 0;if(/^mkfs(?:\.[a-z0-9]+)?$/.test(r))return"filesystem format";if(/:\(\)\s*\{.*\}\s*;:/.test(n))return"fork bomb";if(/^(?:shutdown|reboot|halt|poweroff)$/.test(r))return"host shutdown";if(/>\s*\/etc\/(?:passwd|shadow|sudoers)/.test(n))return"overwrite of a system account file"}var w="full-auto",_=async()=>!1,f=!1;function an(n){w=n}function ln(){return w}function cn(n){f=n}function gn(){return f}function un(n){_=n}function J(n,t,o){if(f)return{action:"run"};let e=typeof o?.command=="string"?o.command:"";if(t==="bash"||t==="powershell"){let s=Z(e);if(s)return{action:"deny",reason:`Refused in every mode: ${s}.`};if(b(e))return{action:"run"}}let r=R(t);return k[r]<=k[B[n]]?{action:"run"}:{action:"prompt",reason:`this is a ${r}-tier tool`}}function K(n,t){if(t&&typeof t=="object"){let o=t;if((n==="bash"||n==="powershell")&&typeof o.command=="string")return o.command;if((n==="edit"||n==="write")&&typeof o.path=="string"){let e=Array.isArray(o.edits)?` (${o.edits.length} edits)`:"";return`${o.path}${e}`}try{let e=JSON.stringify(o);if(e&&e!=="{}")return e.length>300?`${e.slice(0,297)}...`:e}catch{}}return n}function X(n,t,o){let e=[`Allow tool: ${n}`];n.startsWith("mcp__")&&e.push("Origin: MCP server tool"),e.push(`Reason: ${o}`);let r=K(n,t);return r!==n&&e.push(r),e.join(`
2
+ `)}function dn(n={}){return t=>{t.on("tool_call",async o=>{if(f)return;let e=x(o.toolName,o.input);if(e)return{block:!0,reason:v(o.toolName,e.repeats)};let r=w,s=J(r,o.toolName,o.input);if(s.action==="run")return;if(s.action==="deny")return{block:!0,reason:s.reason};if(n.interactive===!1)return{block:!0,reason:`Blocked: this is a ${R(o.toolName)}-tier tool and no UI can approve it here (approval mode: ${r}).`};if(!await _(`${o.toolName} wants to run`,X(o.toolName,o.input,s.reason)))return{block:!0,reason:`Blocked by the user (approval mode: ${r}).`}})}}export{Q as a,b,W as c,rn as d,sn as e,k as f,B as g,R as h,Z as i,an as j,ln as k,cn as l,gn as m,un as n,J as o,K as p,X as q,dn as r};
@@ -0,0 +1 @@
1
+ import{a,b,c,d}from"./chunk-U3GZBLTM.js";import"./chunk-WOT6VMZA.js";export{c as describeSandbox,a as detectSandbox,d as enterSandbox,b as sandboxArgv};
package/dist/main.js ADDED
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ import{b as G,d as J,e as K}from"./chunk-EZNNALD3.js";import"./chunk-7LA2AMZB.js";import{c as H}from"./chunk-PH72JBBL.js";import{a as B,b as j}from"./chunk-MCAAX33K.js";import{H as C,P as D}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import{j as L}from"./chunk-MVVEYKN6.js";import{a as r,b as y}from"./chunk-FLP47RIR.js";import"./chunk-WOT6VMZA.js";import{readdirSync as Z,statSync as Oe}from"node:fs";import{join as I}from"node:path";var V={rpc:!0,acp:!0},q={off:!0,minimal:!0,low:!0,medium:!0,high:!0,xhigh:!0,max:!0},z={suggest:!0,"auto-edit":!0,"full-auto":!0},X={text:!0,json:!0,"stream-json":!0};function Re(l){let e=Number(l);if(!Number.isFinite(e)||e<=0)throw new Error(`--max-budget-usd needs a positive number of dollars, got '${l}'`);return e}function $(l,e,p){let i=l[e];if(i?.includes("="))return i.slice(i.indexOf("=")+1);let d=l[e+1];if(!d||d.startsWith("-"))throw new Error(`${p} needs a value`);return l.splice(e+1,1),d}function Y(l){let e={print:!1,continueSession:!1,noSession:!1,help:!1,version:!1,update:!1,checkUpdate:!1,outputFormat:"text",dangerouslySkipPermissions:!1,sandbox:!1,prompt:""},p=[],i=[...l];i[0]==="resume"&&i[1]&&!i[1].startsWith("-")&&(e.resumeId=i[1],i.splice(0,2));for(let d=0;d<i.length;d++){let s=i[d]??"";if(s==="--"){p.push(...i.slice(d+1));break}if(s==="-h"||s==="--help")e.help=!0;else if(s==="-v"||s==="--version")e.version=!0;else if(s==="-p"||s==="--print")e.print=!0;else if(s==="-c"||s==="--continue")e.continueSession=!0;else if(s==="--no-session")e.noSession=!0;else if(s==="--sandbox")e.sandbox=!0;else if(s==="--update")e.update=!0;else if(s==="--check-update")e.checkUpdate=!0;else if(s==="-r"||s==="--resume")e.continueSession=!0;else if(s==="--session"||s.startsWith("--session="))e.sessionPath=$(i,d,"--session");else if(s==="-m"||s==="--model"||s.startsWith("--model="))e.model=$(i,d,"--model");else if(s==="--thinking"||s.startsWith("--thinking="))e.thinking=$(i,d,"--thinking");else if(s==="--approval"||s.startsWith("--approval="))e.approval=$(i,d,"--approval");else if(s==="--output-format"||s.startsWith("--output-format="))e.outputFormat=$(i,d,"--output-format");else if(s==="--max-budget-usd"||s.startsWith("--max-budget-usd="))e.maxBudgetUsd=Re($(i,d,"--max-budget-usd"));else if(s==="--mode"||s.startsWith("--mode=")){let g=$(i,d,"--mode");if(!V[g])throw new Error(`--mode must be one of: ${Object.keys(V).join(", ")}`);e.mode=g}else if(s==="--acp")e.mode="acp";else if(s==="--dangerously-skip-permissions")e.dangerouslySkipPermissions=!0;else{if(s.startsWith("-"))throw new Error(`unknown option ${s}`);p.push(s)}}if(e.thinking&&!q[e.thinking])throw new Error(`thinking must be one of: ${Object.keys(q).join(", ")}`);if(e.approval&&!z[e.approval])throw new Error(`approval must be one of: ${Object.keys(z).join(", ")}`);if(!X[e.outputFormat])throw new Error(`output-format must be one of: ${Object.keys(X).join(", ")}`);if(e.outputFormat!=="text"&&!e.print)throw new Error(`--output-format ${e.outputFormat} is a machine contract; it needs --print`);if(e.dangerouslySkipPermissions&&!e.print)throw new Error("--dangerously-skip-permissions is for unattended runs; it needs --print. interactively, pick an approval mode instead (/approval, or --approval)");if(e.prompt=p.join(" ").trim(),e.update&&e.checkUpdate)throw new Error("--update installs; --check-update only looks. pick one");if((e.update||e.checkUpdate)&&(e.print||e.continueSession||e.sessionPath||e.prompt))throw new Error("--update and --check-update act on the installation, not a session; they take no prompt");if(e.continueSession&&e.noSession)throw new Error("--continue and --no-session cannot be combined");if(e.sessionPath&&e.noSession)throw new Error("--session and --no-session cannot be combined");if(e.sessionPath&&e.continueSession)throw new Error("--session and --continue cannot be combined");if(e.resumeId&&e.sessionPath)throw new Error("resume <id> and --session cannot be combined");if(e.resumeId&&e.continueSession)throw new Error("resume <id> and --continue cannot be combined");if(e.print&&(e.continueSession||e.sessionPath||e.resumeId))throw new Error("--print runs one prompt in a throwaway session; it cannot be combined with --continue, --session, or resume <id>");if(e.mode&&(e.print||e.prompt))throw new Error(`--mode ${e.mode} is a protocol server: prompts arrive over the protocol, not the command line`);if(e.mode&&(e.continueSession||e.sessionPath))throw new Error(`--mode ${e.mode} opens its own sessions; it cannot be combined with --continue or --session`);if(e.sessionPath&&!e.sessionPath.endsWith(".jsonl"))throw new Error(`--session expects a session file, got '${e.sessionPath}'`);return e}function A(){return`${r} ${y}
3
+ coding agent. layout is a workbench, not a chat log.
4
+
5
+ usage:
6
+ howtocode [options] [prompt]
7
+ howtocode -p "explain this repo"
8
+ howtocode resume <id> reopen one stored conversation by its id (or prefix)
9
+ /browser-relay install|status drive your own Chrome tabs from a session
10
+ howtocode acp serve the Agent Client Protocol on stdio
11
+ howtocode --mode rpc serve JSON-line commands on stdio
12
+ howtocode preset new|check|pack author a preset
13
+ howtocode doctor|models|sessions inspect the installation
14
+ howtocode sessions --search <text> find a session by what was said in it
15
+ howtocode sessions --export <n> print session n from the list as markdown
16
+
17
+ options:
18
+ -p, --print run one prompt and print the answer
19
+ -c, --continue resume the latest session in this folder
20
+ -r, --resume alias for --continue
21
+ --session <file> run inside a specific saved session file
22
+ --no-session do not write a session file
23
+ -m, --model <id> provider/model, or a fuzzy model id
24
+ --thinking <lv> off | minimal | low | medium | high | xhigh | max
25
+ --approval <m> suggest | auto-edit | full-auto
26
+ --output-format <f> text | json | stream-json
27
+ text for a person; json writes the final result only;
28
+ stream-json writes every event as it happens
29
+ --max-budget-usd <n> stop the run once it has spent n dollars
30
+ --mode <m> rpc | acp: serve a protocol on stdin/stdout, no terminal
31
+ --acp same as --mode acp
32
+ --sandbox run the whole session inside a filesystem sandbox:
33
+ the project is writable, the rest is read-only.
34
+ needs bubblewrap (Linux) or sandbox-exec (macOS)
35
+ --dangerously-skip-permissions
36
+ run everything, including commands otherwise refused.
37
+ unattended runs only; pairs with --print
38
+ --update install the newest release and exit
39
+ --check-update say whether a newer release exists
40
+ -h, --help
41
+ -v, --version
42
+
43
+ keys:
44
+ enter send
45
+ shift+enter new line
46
+ ctrl+c stop the run, or quit when idle
47
+ ctrl+d quit
48
+ ctrl+l jump to the latest line
49
+ ctrl+o clear the screen (history is kept)
50
+ ctrl+t raise the thinking level (wraps to off)
51
+ ctrl+shift+t lower the thinking level
52
+ esc clear the draft
53
+ ctrl+v paste from the clipboard
54
+ pgup / pgdn scroll the transcript a page
55
+ home / end jump to the top / back to the latest line
56
+ wheel scroll the transcript
57
+
58
+ commands:
59
+ /init /model /providers /thinking /approval /login /connect /logout /new
60
+ /resume /compact /name /stats /rtk /diff /commit /undo /rewind /review /tools /export
61
+ /copy /agents /goal /plan /workflow /session /help /quit /exit
62
+ /dcp /context /decompress /sweep
63
+ /update /usage /wallet /sync
64
+ /skills /preset /settings /trust /proxy /roblox /vault
65
+ /roblox shows whether RoToolbox is on and Roblox Studio's MCP server is connected.
66
+ RoToolbox uses Studio's own MCP server: open a place in Studio, nothing to install.
67
+
68
+ /stats shows session tokens, cost, and the prompt-cache hit rate; a high read
69
+ total alone hides re-billed context, so the rate is what tells you the truth.
70
+ /rtk compresses long tool output (logs, diffs, greps) before the model reads it.
71
+ Off by default: /rtk on to save tokens when skimming, /rtk off to keep every line.
72
+ Nothing is invented by it \u2014 it drops redundant lines and says how many it dropped,
73
+ and never touches a failed command or one already truncated.
74
+
75
+ /preset lists skills bundled with this build and skills from the registry, by
76
+ category; picking one downloads it into the project and loads it as a skill.
77
+ An integration preset installs disabled: its skills and MCP server stay dormant
78
+ until /preset enable <name>, and /preset disable <name> takes the server back
79
+ out of the live session. /roblox reports that state for RoToolbox in one line.
80
+ /skills lists what is loaded now.
81
+
82
+ /proxy <url> routes requests through a proxy, /proxy off stops, /proxy env uses
83
+ HTTPS_PROXY / HTTP_PROXY / ALL_PROXY; /proxy alone shows what is set.
84
+
85
+ /agents <id> <message> messages a parked agent; /agents <id> shows one.
86
+
87
+ a line starting with ! runs in the project shell.
88
+
89
+ an npm install checks for a newer release at startup and can install it itself;
90
+ /update does it on demand. config and sessions live in ~/.howtocode/agent.
91
+ /connect signs in to howtofix.id in your browser, and falls back to a pasted
92
+ token; /login takes another provider's key.
93
+ `}function Me(l,e=!1){let{message:p,hint:i}=B(l),d=i?`${p}
94
+ ${i}`:p;if(!e)return d;let s=l instanceof Error?l.stack:void 0;return s&&s.includes(`
95
+ `)?`${d}
96
+ ${s}`:d}function Q(l,e){let p=e?.debug??process.env.HOWTOCODE_DEBUG==="1",i=e?.exit??(s=>process.exit(s)),d=s=>{console.error(`${l}: ${Me(s,p)}`),i(1)};process.on("uncaughtException",d),process.on("unhandledRejection",d)}function Te(){try{return{cwd:process.cwd()}}catch{return{error:"the current directory no longer exists (it was deleted while the shell stayed in it). cd to a directory that exists, or pass one on the command line."}}}function Ae(){process.stdout.on("error",l=>{throw l.code==="EPIPE"&&process.exit(0),l})}async function je(){Ae(),D();let l=performance.now(),e=Te();if("error"in e){console.error(`${r}: ${e.error}`),process.exitCode=1;return}let p=e.cwd,i=process.env.HXF_FAKE_NODE??process.versions.node,[d,s]=i.split(".").map(t=>Number.parseInt(t,10));if(!Number.isFinite(d)||d<22||d===22&&Number.isFinite(s)&&s<19){console.error(`${r}: Node ${i} is too old. Node 22.19 or newer is required (run "node --version" to check yours), because undici needs zstd, which Node added in 22.19. Upgrade Node and run this again.`),process.exitCode=1;let t=process.argv.slice(2);if(t.some(n=>n==="-h"||n==="--help")){console.log(A());return}if(t.some(n=>n==="-v"||n==="--version")){console.log(`${r} ${y}`);return}return}let g=process.argv.slice(2);if(g[0]==="doctor"||g[0]==="models"||g[0]==="sessions"){let t=g[0];try{let n=await import("./chunk-QEPPIFSI.js");t==="doctor"?process.exitCode=await n.runDoctor():t==="models"?process.exitCode=n.runModels():process.exitCode=n.runSessions(g.slice(1))}catch(n){j(r,t,n),process.exitCode=1}return}let ee=g[0]==="acp"?["--acp",...g.slice(1)]:g,E;try{E=Y(ee)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`${r}: ${n}
97
+ ${A()}`),process.exitCode=2;return}if(E.print&&!E.prompt){console.error(`${r}: --print needs a prompt`),process.exitCode=2;return}let{repairGatewayModels:se,ensureGatewaySettings:oe,repairModelFacts:te,syncGatewayModelsOnStart:ne,checkAccount:re,fetchGatewayPrices:ie,readProviderKey:ae}=await import("./chunk-BV6J5Q4T.js"),{tiersFrom:de,writeReachable:ce}=await import("./chunk-XBVWQC7P.js"),{readCliCredential:le,renewCliCredentialIfNeeded:pe}=await import("./chunk-ELHK7EH4.js"),{AGENT_DIR:h,REACHABLE_CACHE_PATH:ue}=await import("./chunk-ELM3OMOE.js"),{readCachedPrices:me,writeCachedPrices:he}=await import("./chunk-A3LZMZ3C.js"),F=se(h);F>0&&console.error(`${r}: repaired ${F} howtocode model(s) that the gateway would have rejected`);let P,R,M=new Map,_=me(h);if(_){P=_.prices;for(let[t,n]of _.groups)M.set(t,n)}try{let t=le(h),n=t?(await pe(h,t)).credential.accessToken:ae(h,"howtocode");if(n){let[m,u]=await Promise.all([_?Promise.resolve(P??new Map):ie(n,{groups:M}),re(n)]);!_&&m.size>0&&(P=m,he(h,m,M)),u.ok&&(R=u.models)}}catch{}let N=de(M),O=await te(h,{...P?{prices:P}:{},...N.size>0?{tiers:N}:{}});if(O.changed>0?console.error(`${r}: filled in the context window, reasoning flag and price for ${O.changed} model(s)`):O.message&&console.error(`${r}: model catalogue unavailable (${O.message}); context windows stay at their conservative defaults`),oe(h)&&console.error(`${r}: set httpIdleTimeoutMs in settings.json so a stalled provider recovers instead of hanging`),R){ce(ue,R);try{let t=await ne(h,R,P);t.added>0&&console.error(`${r}: added ${t.added} model(s) this account can now reach`)}catch{}}let o=E;if(o.help){console.log(A());return}if(o.version){console.log(`${r} ${y}`);let{cliSigningKeyMatchesPanel:t,cliSigningKeyFingerprint:n}=await import("./chunk-VUQVLOAD.js");t()||(console.error(`${r}: this build's CLI signing key (${n()}) does not match the key the panel verifies against, so sign-in will be refused.`),process.exitCode=1);return}if(o.sandbox&&!process.env.HOWTOCODE_SANDBOXED){let{detectSandbox:t,enterSandbox:n,describeSandbox:m}=await import("./chunk-YX2QDCVK.js"),u=t();if(!u){console.error(`${r}: --sandbox needs a working bubblewrap (Linux) or sandbox-exec (macOS). Neither could be used here \u2014 on Linux this usually means unprivileged user namespaces are disabled.`),process.exitCode=1;return}console.error(m(u)),process.exitCode=n(u,{cwd:p,agentDir:C,argv:[process.execPath,...process.argv.slice(1)]});return}let{installProxy:fe}=await import("./chunk-WKUJ7CFO.js");fe(C);let{retireRobloxBridge:ge}=await import("./chunk-CCISJKGS.js");if(ge(C),o.update||o.checkUpdate){let{PACKAGE_NAME:t,checkForUpdate:n,installUpdate:m,isInstalledCopy:u}=await import("./chunk-LYLJZVZ7.js"),w=await n(y);if(!w.latest){console.error(`${r}: ${w.message}`),process.exitCode=o.update?1:0;return}if(console.log(w.message),o.checkUpdate||!w.available)return;if(!u()){console.error(`${r}: this copy was not installed by npm, so npm cannot replace it. install it with: npm install -g ${t}`),process.exitCode=1;return}let v=await m({version:w.latest});console.log(v.message),v.ok||(process.exitCode=1);return}let U=process.argv.slice(2);if(U[0]==="preset"){let{runPresetCommand:t}=await import("./chunk-AS4FUFAN.js");process.exitCode=t(U.slice(1));return}let{expandFileReferences:we}=await import("./chunk-TSEKPGK4.js"),{isApprovalMode:be,setApprovalMode:ke,setDangerousBypass:xe,isDangerousBypass:ye}=await import("./chunk-PVFHAKN6.js"),{openSession:ve}=await import("./chunk-QBHBECIB.js");ke(o.approval&&be(o.approval)?o.approval:"full-auto");let{readWorkbenchSettings:Se}=await import("./chunk-V3R4FYTJ.js");if((o.dangerouslySkipPermissions||Se(h).skipPermissions)&&xe(!0),ye()&&console.error(`${r}: permission checks are OFF \u2014 critical commands (filesystem wipes, fork bombs, host shutdown) and the repeated-call guard are NOT enforced for this run. Turn it off with /settings, or by removing skipPermissions from settings.json.`),o.mode){let{serveProtocol:t}=await import("./chunk-43YCQFSH.js");await t(o.mode,{cwd:p,model:o.model,thinking:o.thinking});return}let W=t=>ve({cwd:p,model:o.model,thinking:o.thinking,continueSession:t.continueSession??!1,noSession:t.noSession??!1,sessionPath:t.sessionPath,interactive:!o.print});if(o.resumeId&&!o.sessionPath){let t=I(C,"sessions"),n=[];try{for(let m of Z(t))for(let u of Z(I(t,m))){if(!u.endsWith(".jsonl")||!u.includes(o.resumeId))continue;let w=I(t,m,u);try{n.push({path:w,mtime:Oe(w).mtimeMs})}catch{}}}catch{}if(n=n.sort((m,u)=>u.mtime-m.mtime),n.length===0){console.error(`${r}: no stored session matches '${o.resumeId}'. Run 'howtocode -c' to continue the latest one in this folder.`),process.exitCode=1;return}n.length>1&&console.error(`${r}: '${o.resumeId}' matches ${n.length} sessions; using the newest (${n[0].path}).`),o.sessionPath=n[0].path}let a=await W({continueSession:o.continueSession,sessionPath:o.sessionPath,noSession:o.noSession||o.print});if(o.print&&a.note&&console.error(a.note),o.maxBudgetUsd!==void 0&&!a.priced){console.error(`${r}: ${K(a.modelLabel,h)}`),await a.dispose(),process.exitCode=2;return}if(o.print){let t=o.prompt.trimStart();if(t.startsWith("/")){let b=t.slice(1).split(/\s+/)[0]??"",{skillInvocation:T}=await import("./chunk-BZJSYOTO.js"),S=a.session.resourceLoader.getSkills().skills.map(f=>f.name);if(!(T(t,S)!==void 0)){let{slashCommands:f}=await import("./chunk-DCFM67MM.js");if(f(a.session).some(c=>c.name===b)){console.error(`${r}: /${b} runs in the TUI only \u2014 --print sends prompts straight to the model. Run \`howtocode\` without --print for interactive commands.`),await a.dispose(),process.exitCode=2;return}}}let n=o.outputFormat==="stream-json",m=o.outputFormat==="json",u=n||m;if(n){let b={type:"system",subtype:"init",cwd:p,session_id:a.session.sessionId,model:a.modelLabel,output_format:o.outputFormat,max_budget_usd:o.maxBudgetUsd??null,dangerously_skip_permissions:o.dangerouslySkipPermissions,cli_version:y};process.stdout.write(`${JSON.stringify(b)}
98
+ `)}let w,v,Ee=()=>{if(o.maxBudgetUsd===void 0||v!==void 0)return;let b=a.session.getSessionStats().cost;b>o.maxBudgetUsd&&(v={spent:b},a.session.abort())};try{let b,T=H();if(w=a.session.subscribe(c=>{if(n){let x=T.line(c);x!==void 0&&process.stdout.write(x)}if(c.type==="turn_end"&&c.message?.role==="assistant"){let x=c.message;x.stopReason==="error"||x.stopReason==="aborted"||x.errorMessage?b={stopReason:x.stopReason??"error",errorMessage:x.errorMessage}:b=void 0}Ee()}),await a.session.prompt(we(o.prompt,p)),n){let c=T.finish();c!==void 0&&process.stdout.write(c)}let S=L(a.session.getLastAssistantText()??"");if(v){if(console.error(`${r}: ${J(v.spent,o.maxBudgetUsd)}`),u){let c=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:"error_max_budget_usd",is_error:!0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:c.assistantMessages,total_cost_usd:c.cost,usage:{input_tokens:c.tokens.input,output_tokens:c.tokens.output,cache_read_input_tokens:c.tokens.cacheRead,cache_creation_input_tokens:c.tokens.cacheWrite}})}
99
+ `)}process.exitCode=1;return}let k=a.session.state.messages.at(-1),f=b??(k?.role==="assistant"&&(k.stopReason==="error"||k.stopReason==="aborted"||k.errorMessage)?{stopReason:k.stopReason??"error",errorMessage:k.errorMessage}:void 0);if(u){let c=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:f?f.stopReason==="aborted"?"error_aborted":"error_during_execution":"success",is_error:f!==void 0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:c.assistantMessages,total_cost_usd:c.cost,usage:{input_tokens:c.tokens.input,output_tokens:c.tokens.output,cache_read_input_tokens:c.tokens.cacheRead,cache_creation_input_tokens:c.tokens.cacheWrite},stop_reason:f?.stopReason??(k?.role==="assistant"?k.stopReason:void 0)})}
100
+ `)}else process.stdout.write(S.endsWith(`
101
+ `)?S:`${S}
102
+ `);if(f&&(process.exitCode=1,f.errorMessage)){console.error(`${r}: ${f.errorMessage}`);let c=G(f.errorMessage);c!==void 0&&console.error(`${r}: ${c}`)}}finally{w?.(),await a.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${r}: interactive mode needs a terminal. use --print for pipes.`),await a.dispose(),process.exitCode=2;return}let{runWorkbench:$e}=await import("./chunk-DCFM67MM.js"),{autoUpdateEnabled:Pe,isInstalledCopy:_e}=await import("./chunk-LYLJZVZ7.js"),Ce=_e()&&Pe(`${h}/settings.json`);await $e({cwd:p,modelLabel:a.modelLabel,session:a.session,dispose:()=>a.dispose(),setCompressToolOutput:a.setCompressToolOutput,initialPrompt:o.prompt||void 0,note:a.note,maxBudgetUsd:o.maxBudgetUsd,update:Ce?{current:y,install:!0}:void 0,reopen:W})}Q(r);je().catch(l=>{j(r,void 0,l),process.exitCode=1});
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "api",
3
+ "title": "HTTP API",
4
+ "description": "Design an HTTP API contract before writing handlers: status codes, error shape, idempotency, versioning.",
5
+ "category": "backend",
6
+ "tags": [
7
+ "http",
8
+ "rest",
9
+ "api",
10
+ "contract"
11
+ ],
12
+ "version": "1.0.0",
13
+ "skills": [
14
+ "api-contract"
15
+ ],
16
+ "prompt": "prompt.md"
17
+ }
@@ -0,0 +1,9 @@
1
+ When this preset is active, write the contract before the handler:
2
+
3
+ 1. Name every endpoint, its method, and what it returns on success.
4
+ 2. Name the failure modes and the status code for each. A 500 for a bad request is a bug.
5
+ 3. Write the request and response bodies as concrete examples with real field names.
6
+ 4. Only then write the handler.
7
+
8
+ An endpoint whose error shape was decided after the code was written will have three
9
+ different error shapes by the end of the week.
@@ -0,0 +1,35 @@
1
+ ---
2
+ name: api-contract
3
+ description: Write an HTTP API contract before the handler. Use when adding or changing an endpoint.
4
+ ---
5
+
6
+ # API contract first
7
+
8
+ The contract is the part other people depend on. It costs ten minutes to write and
9
+ saves a version bump.
10
+
11
+ ## Decide these, in this order
12
+
13
+ 1. **Method and path.** A `GET` that changes state is the classic mistake — it will be
14
+ retried by something eventually.
15
+ 2. **Success shape.** Exact field names, types, and which are nullable. Not "returns the
16
+ user" — the JSON.
17
+ 3. **Failure shape.** One shape for every error, so a client writes one handler:
18
+
19
+ ```json
20
+ { "error": { "code": "invalid_email", "message": "..." } }
21
+ ```
22
+
23
+ 4. **Status codes.** 400 for a malformed request, 401 unauthenticated, 403
24
+ unauthorised, 404 absent, 409 conflict, 422 semantically invalid, 429 rate limited.
25
+ 5. **Idempotency.** Which calls may be retried safely, and what makes them safe.
26
+
27
+ ## Versioning
28
+
29
+ Add a field rather than change one. Removing or retyping a field is the change that
30
+ breaks callers, and it is the one worth a new version.
31
+
32
+ ## Pagination
33
+
34
+ Pick one shape and keep it. Cursor-based survives a growing table; offset-based does
35
+ not. Whatever you choose, say whether the next page exists and how to ask for it.
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "sql",
3
+ "title": "SQL & schema",
4
+ "description": "Write queries and migrations that stay correct as the table grows: indexes, NULLs, safe migrations.",
5
+ "category": "data",
6
+ "tags": [
7
+ "sql",
8
+ "database",
9
+ "migration",
10
+ "index"
11
+ ],
12
+ "version": "1.0.0",
13
+ "skills": [
14
+ "query-hygiene"
15
+ ],
16
+ "prompt": "prompt.md"
17
+ }
@@ -0,0 +1,9 @@
1
+ When this preset is active, decide the schema before the query:
2
+
3
+ 1. Say what the table holds, which column identifies a row, and which columns are
4
+ nullable. A column that is nullable "just in case" makes every read a branch.
5
+ 2. Write the migration so it is safe on a table that already has rows: adding a
6
+ nullable column is safe, adding a NOT NULL one without a default is not.
7
+ 3. Name the index a query needs, or say why it needs none.
8
+ 4. Before claiming a query is correct, say what it returns for zero rows and for
9
+ NULL in the column it filters on. Both are where queries are usually wrong.