howtocode 0.0.0-stage → 0.7.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +248 -2
- package/dist/chunk-27TRKD65.js +2 -0
- package/dist/chunk-2SHU7WQ5.js +10 -0
- package/dist/chunk-3FYCFLNK.js +1 -0
- package/dist/chunk-4BWBQ4HV.js +1 -0
- package/dist/chunk-7IUWRCVT.js +197 -0
- package/dist/chunk-7LA2AMZB.js +1 -0
- package/dist/chunk-A3LZMZ3C.js +2 -0
- package/dist/chunk-ADJLVYL3.js +1 -0
- package/dist/chunk-AEDSISJB.js +1 -0
- package/dist/chunk-AEWC7NIN.js +5 -0
- package/dist/chunk-AYBGCIQH.js +8 -0
- package/dist/chunk-DML5JQIR.js +1 -0
- package/dist/chunk-DT7VRY24.js +1 -0
- package/dist/chunk-EZNNALD3.js +1 -0
- package/dist/chunk-FGKA3GGW.js +6 -0
- package/dist/chunk-FJBHQI6Q.js +6 -0
- package/dist/chunk-JWPDIJUV.js +1 -0
- package/dist/chunk-KA2CULSQ.js +2 -0
- package/dist/chunk-KTS2F755.js +2 -0
- package/dist/chunk-LYLJZVZ7.js +1 -0
- package/dist/chunk-MCAAX33K.js +2 -0
- package/dist/chunk-MCDEIIEN.js +1 -0
- package/dist/chunk-MVVEYKN6.js +6 -0
- package/dist/chunk-MWSWXDNN.js +5 -0
- package/dist/chunk-ORJ2QZBG.js +3 -0
- package/dist/chunk-PH72JBBL.js +4 -0
- package/dist/chunk-PVFHAKN6.js +1 -0
- package/dist/chunk-QOYTPACU.js +3 -0
- package/dist/chunk-RGYXELNI.js +140 -0
- package/dist/chunk-SDO33XPR.js +4 -0
- package/dist/chunk-SZPFD4XF.js +47 -0
- package/dist/chunk-TOV557ET.js +12 -0
- package/dist/chunk-TSEKPGK4.js +1 -0
- package/dist/chunk-TUXY64DT.js +2 -0
- package/dist/chunk-U3GZBLTM.js +2 -0
- package/dist/chunk-UTYFLLSM.js +1 -0
- package/dist/chunk-V3R4FYTJ.js +1 -0
- package/dist/chunk-VWAUPT4A.js +1 -0
- package/dist/chunk-WKUJ7CFO.js +1 -0
- package/dist/chunk-WOT6VMZA.js +1 -0
- package/dist/chunk-XBVWQC7P.js +1 -0
- package/dist/chunk-XHHNV7A5.js +2 -0
- package/dist/chunk-YNMLRZJK.js +2 -0
- package/dist/chunk-YX2QDCVK.js +1 -0
- package/dist/main.js +102 -0
- package/dist/presets/backend/api/preset.json +17 -0
- package/dist/presets/backend/api/prompt.md +9 -0
- package/dist/presets/backend/api/skills/api-contract/SKILL.md +35 -0
- package/dist/presets/data/sql/preset.json +17 -0
- package/dist/presets/data/sql/prompt.md +9 -0
- package/dist/presets/data/sql/skills/query-hygiene/SKILL.md +48 -0
- package/dist/presets/devops/containers/preset.json +17 -0
- package/dist/presets/devops/containers/prompt.md +9 -0
- package/dist/presets/devops/containers/skills/image-discipline/SKILL.md +59 -0
- package/dist/presets/frontend/web-ui/preset.json +17 -0
- package/dist/presets/frontend/web-ui/prompt.md +11 -0
- package/dist/presets/frontend/web-ui/skills/responsive-check/SKILL.md +46 -0
- package/dist/presets/gamedev/rotoolbox/preset.json +31 -0
- package/dist/presets/gamedev/rotoolbox/prompt.md +34 -0
- package/dist/presets/gamedev/rotoolbox/skills/rotoolbox/SKILL.md +129 -0
- package/dist/presets/hub.json +14582 -0
- package/dist/presets/lang/typescript/preset.json +16 -0
- package/dist/presets/lang/typescript/prompt.md +5 -0
- package/dist/presets/lang/typescript/skills/ts-strict/SKILL.md +48 -0
- package/dist/presets/mcp/filesystem/preset.json +27 -0
- package/dist/presets/mcp/filesystem/prompt.md +8 -0
- package/dist/presets/mcp/filesystem/skills/mcp-files/SKILL.md +27 -0
- package/dist/presets/mcp/memory/preset.json +25 -0
- package/dist/presets/mcp/memory/skills/mcp-memory/SKILL.md +31 -0
- package/dist/presets/mcp/rea/preset.json +28 -0
- package/dist/presets/mcp/rea/prompt.md +5 -0
- package/dist/presets/mcp/rea/skills/mcp-rea/SKILL.md +6 -0
- package/dist/presets/mcp/remotion/preset.json +27 -0
- package/dist/presets/mcp/remotion/prompt.md +7 -0
- package/dist/presets/mcp/remotion/skills/mcp-remotion/SKILL.md +6 -0
- package/dist/presets/mcp-hub.json +157 -0
- package/dist/presets/mobile/app/preset.json +17 -0
- package/dist/presets/mobile/app/prompt.md +7 -0
- package/dist/presets/mobile/app/skills/touch-targets/SKILL.md +47 -0
- package/dist/presets/quality/antislop/preset.json +25 -0
- package/dist/presets/quality/antislop/prompt.md +16 -0
- package/dist/presets/quality/antislop/skills/antislop/SKILL.md +595 -0
- package/dist/presets/quality/antislop/skills/antislop/references/gate.md +84 -0
- package/dist/presets/quality/antislop/skills/antislop-code/SKILL.md +128 -0
- package/dist/presets/quality/antislop/skills/antislop-copywriting/SKILL.md +413 -0
- package/dist/presets/quality/antislop/skills/antislop-human/SKILL.md +147 -0
- package/dist/presets/quality/antislop/skills/antislop-human/contrast-check.py +165 -0
- package/dist/presets/quality/antislop/skills/antislop-layoutmobile/SKILL.md +170 -0
- package/dist/presets/quality/antislop/skills/antislop-ui/SKILL.md +313 -0
- package/dist/presets/quality/antislop/skills/antislop-ui/references/motion.md +34 -0
- package/dist/presets/quality/antislop/skills/antislop-ui/references/states.md +49 -0
- package/package.json +34 -4
|
@@ -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-7IUWRCVT.js";import{b as xe}from"./chunk-27TRKD65.js";import{c as ue}from"./chunk-FGKA3GGW.js";import{h as pe,l as fe}from"./chunk-XHHNV7A5.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-2SHU7WQ5.js";import"./chunk-UTYFLLSM.js";import"./chunk-MVVEYKN6.js";import"./chunk-KA2CULSQ.js";import{b as G,c as ie,d as ae}from"./chunk-AEWC7NIN.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,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{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i}from"./chunk-XHHNV7A5.js";import"./chunk-UTYFLLSM.js";import"./chunk-KA2CULSQ.js";import"./chunk-AEWC7NIN.js";import"./chunk-WOT6VMZA.js";export{b as CLI_REFRESH_SKEW_MS,c as accessTokenIsFresh,g as clearCliCredential,a as cliCredentialsPath,e as readCliCredential,h as refreshCliCredential,d as refreshTokenIsUsable,i as renewCliCredentialIfNeeded,f as writeCliCredential};
|
|
@@ -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{a as T}from"./chunk-UTYFLLSM.js";import{g as R,j as P}from"./chunk-KA2CULSQ.js";import{existsSync as z,readFileSync as ye,rmSync as xe}from"node:fs";import{join as ve}from"node:path";import{createHash as q,randomBytes as J}from"node:crypto";import{createServer as ne}from"node:http";import{execFileSync as X}from"node:child_process";import{createHmac as Q}from"node:crypto";import{readFileSync as ee}from"node:fs";import{arch as F,cpus as M,hostname as N,platform as v,userInfo as O}from"node:os";var te="howtocode-cli-hwid-v1";function x(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function $(e,t){try{let r=X(e,t,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});return r.trim().length>0?r.trim():void 0}catch{return}}function re(){let e=v();if(e==="linux"){let t=x("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=x("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let o=x("/sys/class/dmi/id/product_uuid");return o?{value:o,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=$("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"])?.match(/MachineGuid\s+REG_SZ\s+(\S+)/i);return r?.[1]?{value:r[1],source:"windows-machine-guid",strong:!0}:void 0}if(e==="darwin"){let r=$("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function H(){let e=re(),t=e?.value??[N(),v(),F(),O().username].join("\0"),r=e?.source??"hostname";return{id:Q("sha256",te).update(t).digest("hex").slice(0,32),source:r,strong:e?.strong??!1}}function U(e){return[e.id,e.source,N(),v(),F(),O().username,String(M().length),M()[0]?.model??""]}var _="https://howtofix.id",se=300*1e3,G=3e3,K="/callback";function I(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return I(J(32))}function ie(e){return I(q("sha256").update(e).digest())}function ae(){return I(J(16))}var ce="howtocode-cli-",ue="x-howtocode-client",le="cli";function L(e){let t=e??U(H());return ce+q("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function de(){return{"content-type":"application/json",[ue]:le}}var fe=()=>new Promise((e,t)=>{let r=ne();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let{port:o}=r.address();e({port:o,close:()=>r.close(),waitForCode:(n,s)=>new Promise((i,a)=>{let c=(l,f)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){f.writeHead(404).end("not found");return}let y=(V,Z)=>f.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),S=h.searchParams.get("error")??"",E=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(S){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${S}`));return}if(!E||Y!==n){y("This callback did not belong to the login","You can close this tab."),u(new Error("the callback carried the wrong state"));return}y("Signed in","You can close this tab and go back to HowToCode."),u(void 0,E)},u=(l,f)=>{r.off("request",c),s?.removeEventListener("abort",g),l?a(l):i(f)},g=()=>u(new Error("cancelled"));s?.addEventListener("abort",g,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function p(e,t,r,o){let n=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:o}),s={};try{s=await n.json()}catch{}let i=Number(n.headers?.get?.("retry-after"));return{status:n.status,body:s,retryAfterSeconds:Number.isFinite(i)&&i>0?i:void 0}}function d(...e){for(let t of e)if(typeof t=="string"&&t.trim()!=="")return t.trim()}function j(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}function me(e){try{let t=new URL(e).searchParams.get("code");return t&&t.trim()!==""?t.trim():void 0}catch{return}}async function ge(e,t,r){let o=await e(t,{headers:de(),signal:r}),n={};try{n=await o.json()}catch{}let s=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(s)&&s>0?s:void 0}}function A(e){let t=e.data,r=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let o of r)if(typeof o=="string"&&o.trim().startsWith("sk-"))return o.trim()}function pe(e){let t=e.data,r=d(e.token,t?.token),o=d(e.refresh_token,t?.refresh_token),n=d(e.device_id,t?.device_id);if(!r||!o||!n)return;let s=j(e.access_expires_at,t?.access_expires_at),i=j(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:s,refreshToken:o,deviceId:n,refreshExpiresAt:i}}function m(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function He(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??_).replace(/\/+$/,""),o=e.timeoutMs??se,n={...e,panel:r,fetchImpl:t,timeoutMs:o},s=await ke(n);if(s.ok||s.terminal)return s.result;let i=await he(n);if(i.ok||i.terminal)return i.result;let a=await we(n);return a.ok?a:{ok:!1,message:`${s.result.ok?"":s.result.message}; ${i.result.ok?"":i.result.message}; ${a.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${r}/keys instead.`}}async function he(e){let t=oe(),r=ae(),o;try{o=await(e.loopback??fe)();let n=`http://127.0.0.1:${o.port}${K}`,s=await p(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:n,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(s.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(s.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(s.body,`the panel refused the login (${s.status})`)}};let i=typeof s.body.authorize_url=="string"?s.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};k(e,{kind:"browser",url:i});let a=await be(o.waitForCode(r,e.signal),e.timeoutMs),c=await p(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:s.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(c.body,`the panel refused the exchange (${c.status})`)}};let u=A(c.body);return u?{ok:!0,result:{ok:!0,token:u}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}finally{o?.close()}}async function ke(e){let t=e.fingerprintId??L(),r=e.clientInfo??R(),o=P(t,r);try{let n=await p(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:t,clientInfo:r,...o},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(n.status===401)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not recognise this build as the HowToCode CLI \u2014 update it with `npm install -g howtocode@latest`"}};if(n.status===429)return{ok:!1,terminal:!0,result:{ok:!1,message:`too many sign-in attempts from this machine right now.${n.retryAfterSeconds?` Try again in ${Math.ceil(n.retryAfterSeconds/60)} minute(s).`:""}`}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(n.body,`the panel refused the login (${n.status})`)}};let s=n.body.data??{},i=d(n.body.login_url,s.login_url),a=d(n.body.code,s.code)??(i?me(i):void 0),c=d(n.body.secret,s.secret);return!i||!a?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:c?(k(e,{kind:"browser",url:i}),await D(e,a,c)):(k(e,{kind:"browser",url:i}),await D(e,a,void 0))}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}}async function D(e,t,r){let o=e.pollIntervalMs??G,n=Date.now()+e.timeoutMs;for(;Date.now()<n;){await w(o,e.signal);let s=new URLSearchParams(r?{code:t,secret:r}:{code:t});s.set("capability","device-refresh");let i=await ge(e.fetchImpl,`${e.panel}/api/auth/cli/status?${s}`,e.signal);if(i.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};if(i.status===403)return{ok:!1,terminal:!0,result:{ok:!1,message:"the panel rejected this poll \u2014 run /connect again"}};if(i.status===429){let u=Math.min(Math.max(i.retryAfterSeconds??5,1)*1e3,3e4);await w(u,e.signal);continue}let a=A(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:pe(i.body)}};if(d(i.body.data?.status,i.body.status)==="expired")return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in link expired before it was approved"}};if(i.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(i.body,`the panel refused the poll (${i.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}async function we(e){let t=e.pollIntervalMs??G;try{let r=await p(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(r.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(r.status>=400)return{ok:!1,message:m(r.body,`the panel refused the request (${r.status})`)};let o=typeof r.body.device_code=="string"?r.body.device_code:"",n=typeof r.body.user_code=="string"?r.body.user_code:"",s=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!o||!n)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:n,url:s});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await p(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:o},e.signal);if(a.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let c=typeof a.body.status=="string"?a.body.status:"";if(c==="pending")continue;if(c==="slow_down"){await w(t,e.signal);continue}if(c==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(c==="expired")return{ok:!1,message:"the code expired; run /connect again"};let u=A(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:m(a.body,`the panel refused the poll (${a.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}}function be(e,t){return new Promise((r,o)=>{let n=setTimeout(()=>o(new Error("the sign-in was not finished in time")),t);e.then(s=>{clearTimeout(n),r(s)},s=>{clearTimeout(n),o(s)})})}function w(e,t){return new Promise((r,o)=>{let n=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(n),o(new Error("cancelled"))},{once:!0})})}function b(e){return ve(e,"cli-credentials.json")}var _e=300*1e3;function Ie(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-_e>t:!1}function Le(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Ge(e){let t=b(e);if(!z(t))return;let r;try{r=JSON.parse(ye(t,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let o=r,n=typeof o.accessToken=="string"?o.accessToken.trim():"",s=typeof o.refreshToken=="string"?o.refreshToken.trim():"",i=typeof o.deviceId=="string"?o.deviceId.trim():"";if(!(!n||!s||!i))return{accessToken:n,accessExpiresAt:W(o.accessExpiresAt),refreshToken:s,deviceId:i,refreshExpiresAt:W(o.refreshExpiresAt)}}function Ae(e,t){try{return T(b(e),`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,{mode:384}),!0}catch{return!1}}function Ce(e){try{let t=b(e);z(t)&&xe(t,{force:!0})}catch{}}function W(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function Se(e,t){let r=(t?.panelUrl??_).replace(/\/+$/,""),o=t?.fetchImpl??fetch,n=t?.timeoutMs??15e3,s=new AbortController,i=setTimeout(()=>s.abort(),n);try{let a=await o(`${r}/api/auth/cli/refresh`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({device_id:e.deviceId,refresh_token:e.refreshToken,fingerprint_id:L()}),signal:s.signal}),c=await a.json().catch(()=>({}));if(a.status===401||a.status===403)return{ok:!1,terminal:!0,message:"this sign-in is no longer valid; run /connect to sign in again"};if(!a.ok)return{ok:!1,terminal:!1,message:`the panel refused the renewal (${a.status})`};let u=c.data??{},g=C(c.token,u.token),l=C(c.refresh_token,u.refresh_token),f=C(c.device_id,u.device_id)??e.deviceId;return!g||!l?{ok:!1,terminal:!1,message:"the panel did not return a renewed credential"}:{ok:!0,terminal:!1,credential:{accessToken:g,accessExpiresAt:B(c.access_expires_at,u.access_expires_at),refreshToken:l,deviceId:f,refreshExpiresAt:B(c.refresh_expires_at,u.refresh_expires_at)}}}catch(a){return{ok:!1,terminal:!1,message:a instanceof Error&&a.name==="AbortError"?`the panel did not answer within ${Math.round(n/1e3)}s`:"could not reach the panel"}}finally{clearTimeout(i)}}function C(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim()}function B(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}async function Ke(e,t,r){let o=r?.now??Date.now();if(Ie(t,o)||!Le(t,o))return{credential:t,renewed:!1,terminal:!1};let n=await Se(t,r);if(!n.ok||!n.credential)return n.terminal&&Ce(e),{credential:t,renewed:!1,terminal:n.terminal,message:n.message};let s=Ae(e,n.credential);return{credential:n.credential,renewed:!0,terminal:!1,message:s?void 0:`the renewed sign-in could not be saved to ${b(e)}`}}export{H as a,_ as b,He as c,b as d,_e as e,Ie as f,Le as g,Ge as h,Ae as i,Ce as j,Se as k,Ke as l};
|
|
@@ -0,0 +1,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-2SHU7WQ5.js";import"./chunk-UTYFLLSM.js";import{j as L}from"./chunk-MVVEYKN6.js";import{a as r,b as y}from"./chunk-AEWC7NIN.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-FJBHQI6Q.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-JWPDIJUV.js"),{tiersFrom:de,writeReachable:ce}=await import("./chunk-XBVWQC7P.js"),{readCliCredential:le,renewCliCredentialIfNeeded:pe}=await import("./chunk-VWAUPT4A.js"),{AGENT_DIR:h,REACHABLE_CACHE_PATH:ue}=await import("./chunk-AEDSISJB.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-DT7VRY24.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-4BWBQ4HV.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-AYBGCIQH.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-SZPFD4XF.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-ADJLVYL3.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-DML5JQIR.js"),S=a.session.resourceLoader.getSkills().skills.map(f=>f.name);if(!(T(t,S)!==void 0)){let{slashCommands:f}=await import("./chunk-RGYXELNI.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-RGYXELNI.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.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: query-hygiene
|
|
3
|
+
description: SQL and schema rules that hold up as data grows. Use when writing queries or migrations.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Query hygiene
|
|
7
|
+
|
|
8
|
+
## NULL is not a value
|
|
9
|
+
|
|
10
|
+
```sql
|
|
11
|
+
WHERE status = 'open' -- rows with NULL status are invisible
|
|
12
|
+
WHERE status <> 'open' -- and NULL status is invisible here too
|
|
13
|
+
WHERE status IS DISTINCT FROM 'open' -- what you usually meant
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
`NULL = NULL` is unknown, not true. Any `<>` or `NOT IN` over a nullable column
|
|
17
|
+
silently drops rows — including `NOT IN (SELECT ...)`, which returns **zero rows**
|
|
18
|
+
if the subquery yields a single NULL.
|
|
19
|
+
|
|
20
|
+
## Indexes follow the query, not the column
|
|
21
|
+
|
|
22
|
+
An index on `(user_id, created_at)` serves `WHERE user_id = ? ORDER BY created_at`
|
|
23
|
+
and does nothing for `WHERE created_at > ?` alone. The rule is the leftmost prefix:
|
|
24
|
+
a composite index is usable only from its first column rightwards.
|
|
25
|
+
|
|
26
|
+
Do not index every column — each index is written on every insert.
|
|
27
|
+
|
|
28
|
+
## Migrations on a live table
|
|
29
|
+
|
|
30
|
+
| Change | Safe? |
|
|
31
|
+
|---|---|
|
|
32
|
+
| Add a nullable column | yes |
|
|
33
|
+
| Add NOT NULL with a default | depends on the engine; a rewrite on large tables |
|
|
34
|
+
| Add NOT NULL without a default | no — fails on existing rows |
|
|
35
|
+
| Rename a column | no — breaks readers mid-deploy |
|
|
36
|
+
| Drop a column | only after no code reads it |
|
|
37
|
+
|
|
38
|
+
The pattern that works for a rename: add the new column, write to both, backfill,
|
|
39
|
+
switch reads, then drop the old one. Four deploys, no downtime.
|
|
40
|
+
|
|
41
|
+
## Before saying a query is right
|
|
42
|
+
|
|
43
|
+
State what it returns for:
|
|
44
|
+
- zero rows (does the caller handle empty, or does it index `[0]`?),
|
|
45
|
+
- NULL in the filtered column,
|
|
46
|
+
- a duplicate on the join key (a join is a multiply, not a lookup).
|
|
47
|
+
|
|
48
|
+
If you cannot say, the query is not verified — it is untested.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "containers",
|
|
3
|
+
"title": "Containers & deploy",
|
|
4
|
+
"description": "Write a Dockerfile and a deploy step that fail loudly instead of shipping a broken image.",
|
|
5
|
+
"category": "devops",
|
|
6
|
+
"tags": [
|
|
7
|
+
"docker",
|
|
8
|
+
"deploy",
|
|
9
|
+
"ci",
|
|
10
|
+
"image"
|
|
11
|
+
],
|
|
12
|
+
"version": "1.0.0",
|
|
13
|
+
"skills": [
|
|
14
|
+
"image-discipline"
|
|
15
|
+
],
|
|
16
|
+
"prompt": "prompt.md"
|
|
17
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
When this preset is active, treat the image as the artifact under test:
|
|
2
|
+
|
|
3
|
+
1. Build the image and run it. An image that builds is not an image that starts —
|
|
4
|
+
the usual failure is a missing runtime file, and it appears only at `docker run`.
|
|
5
|
+
2. Pin base image versions. `node:latest` means the build is a different build
|
|
6
|
+
next week.
|
|
7
|
+
3. Never put a secret in a layer: `ENV`, `ARG` and a copied `.env` are all
|
|
8
|
+
readable from the image history.
|
|
9
|
+
4. Say what the health check hits and what it returns before calling a deploy done.
|