hablas-ai 1.0.7 → 1.0.8
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/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -793,7 +793,7 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
|
793
793
|
</self_eval>
|
|
794
794
|
`.trim()}parseSelfEval(e){let t=[/^\s*(\{[\s\S]*\})\s*$/,/```(?:json)?\s*\n([\s\S]*?)\n```/,/<self_eval_result>([\s\S]*?)<\/self_eval_result>/,/(\{[\s\S]*?"score"[\s\S]*?"completed"[\s\S]*?\})/];for(let s of t){let r=e.match(s);if(r)try{let i=JSON.parse(r[1]);return this.normalizeSelfEval(i)}catch{}}return null}normalizeSelfEval(e){let t=typeof e.score=="number"?Math.max(0,Math.min(10,Math.round(e.score))):5,s=typeof e.completed=="boolean"?e.completed:t>=7,r=typeof e.rationale=="string"?e.rationale.slice(0,500):"No rationale provided",i=Array.isArray(e.issues)?e.issues.filter(a=>typeof a=="string").slice(0,5):[],o="medium";return e.confidence==="high"||e.confidence==="medium"||e.confidence==="low"?o=e.confidence:t>=8?o="high":t<=4&&(o="low"),{score:t,completed:s,rationale:r,issues:i,confidence:o}}buildBudgetWarningPrompt(){let e=this.remainingBudget();return e<=0?"[SYSTEM] You have exceeded the maximum reasoning steps. You MUST provide your final answer NOW. Do not call any more tools.":e<=3?`[SYSTEM] You have only ${e} step(s) remaining. Wrap up your work and provide a final answer soon.`:null}buildReflectionHint(e,t,s){return t?"":["<thinking>",`Tool "${e}" FAILED. Before retrying:`,"1. What went wrong? Analyze the error message carefully.","2. Can I fix the arguments and retry?","3. Is there an alternative approach?",`Error preview: ${s.slice(0,300)}`,"</thinking>"].join(`
|
|
795
795
|
`)}getTurnSummary(){let e=this.turnSteps.length,t=this.turnSteps.filter(r=>r.action).length,s=this.turnSteps.filter(r=>r.reflection).length;return`${e} steps, ${t} actions, ${s} reflections`}}});function xs(n=3){return new jl(n)}var Q$,jl,Hl=N(()=>{"use strict";Q$=[{test:n=>/ENOENT|no such file|not found|does not exist/i.test(n),errorClass:"file_not_found",strategy:"read_first",explanation:"The file or directory does not exist.",suggestion:"Use list_dir to check what files exist, then retry with the correct path.",alternatives:["list_dir","search_codebase"],autoRetry:!1},{test:n=>/EACCES|permission denied/i.test(n),errorClass:"permission_denied",strategy:"graceful_fail",explanation:"Permission denied \u2014 the process lacks access rights.",suggestion:"Check file ownership or try a different path. Do NOT use sudo.",alternatives:[],autoRetry:!1},{test:n=>/EISDIR|is a directory/i.test(n),errorClass:"path_is_directory",strategy:"retry_fixed",explanation:"The path points to a directory, not a file.",suggestion:"Append the filename to the path. Use list_dir to see contents.",alternatives:["list_dir"],autoRetry:!1},{test:n=>/EEXIST|already exists/i.test(n),errorClass:"file_already_exists",strategy:"read_first",explanation:"A file or directory already exists at that path.",suggestion:"Read the existing file first, then decide whether to overwrite or edit it.",alternatives:["read_file","edit_file"],autoRetry:!1},{test:n=>/no match|not found in file|search string not found/i.test(n),errorClass:"search_no_match",strategy:"read_first",explanation:"The search string was not found in the file.",suggestion:"Read the file first to see its actual content, then use the exact text for search/replace.",alternatives:["read_file","search_codebase"],autoRetry:!1},{test:n=>/command not found|not recognized/i.test(n),errorClass:"command_not_found",strategy:"alternative_tool",explanation:"The command does not exist on this system.",suggestion:"Check if the program is installed, or use a different command that achieves the same goal.",alternatives:["run_command"],autoRetry:!1},{test:n=>/timeout|timed out|ETIMEDOUT/i.test(n),errorClass:"command_timeout",strategy:"retry_fixed",explanation:"The command took too long and was terminated.",suggestion:"Try a simpler version of the command, or increase the timeout, or run it in background.",alternatives:[],autoRetry:!1},{test:n=>/exit code|exited with|non-zero/i.test(n),errorClass:"command_exit_error",strategy:"retry_fixed",explanation:"The command executed but returned an error.",suggestion:"Read the error output carefully. Fix the root cause (missing dependency, wrong syntax, etc.).",alternatives:[],autoRetry:!1},{test:n=>/syntax error|unexpected token|parse error|SyntaxError/i.test(n),errorClass:"syntax_error",strategy:"retry_fixed",explanation:"The content has a syntax error.",suggestion:"Review the generated code for syntax issues, fix them, and retry.",alternatives:[],autoRetry:!1},{test:n=>/ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(n),errorClass:"network_error",strategy:"retry_same",explanation:"Network connection failed.",suggestion:"This may be transient. Retry the same operation, or check connectivity.",alternatives:[],autoRetry:!0},{test:n=>/invalid argument|missing required|expected.*but got|type error/i.test(n),errorClass:"invalid_arguments",strategy:"retry_fixed",explanation:"The tool was called with invalid or missing arguments.",suggestion:"Check the tool's parameter requirements and provide correct values.",alternatives:[],autoRetry:!1},{test:n=>/ENOMEM|out of memory|resource|too large|max.*exceeded/i.test(n),errorClass:"resource_limit",strategy:"decompose_task",explanation:"Resource limit exceeded (memory, file size, etc.).",suggestion:"Break the task into smaller pieces, or process less data at once.",alternatives:[],autoRetry:!1}],jl=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,t,s){let r=this.failures.get(e),i=r?r.count+1:1,o={tool:e,count:i,lastError:t,lastStrategy:"retry_same"};if(i>this.maxRetriesPerTool)return o.lastStrategy="ask_user",this.failures.set(e,o),{errorClass:"unknown",strategy:"ask_user",explanation:`Tool "${e}" has failed ${i} times in this turn.`,suggestion:`Stop retrying "${e}". Ask the user for clarification or try a completely different approach.`,alternatives:this.suggestAlternatives(e),autoRetry:!1};for(let a of Q$)if(a.test(t)){let l=r?.lastStrategy===a.strategy&&i>=2,u=l?"decompose_task":a.strategy;return o.lastStrategy=u,this.failures.set(e,o),{errorClass:a.errorClass,strategy:u,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,t){let s=[`ERROR: ${t}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&s.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":s.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":s.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":s.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":s.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":s.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":s.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return s.join(`
|
|
796
|
-
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let t=this.failures.get(e);return t?t.count<=1&&t.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}}});function Z$(){try{if(It.existsSync(jr))return JSON.parse(It.readFileSync(jr,"utf-8"))}catch{}return{}}function e0(n){try{let e=Hr.dirname(jr);It.existsSync(e)||It.mkdirSync(e,{recursive:!0}),It.writeFileSync(jr,JSON.stringify(n,null,2),"utf-8")}catch{}}function Kl(n,e){let t=0,s=!1,r=!1;for(let i=e;i<n.length;i++){let o=n[i];if(r){r=!1;continue}if(o==="\\"&&s){r=!0;continue}if(o==='"'){s=!s;continue}if(!s&&(o==="{"&&t++,o==="}"&&(t--,t===0)))return n.slice(e,i+1)}return null}function Ss(n){if(typeof n.name=="string"&&n.arguments&&typeof n.arguments=="object")return{tool:n.name,args:n.arguments};if(typeof n.tool=="string"&&n.args&&typeof n.args=="object")return{tool:n.tool,args:n.args};if(typeof n.name=="string"&&n.parameters&&typeof n.parameters=="object")return{tool:n.name,args:n.parameters};if(n.function&&typeof n.function=="object"){let e=n.function;if(typeof e.name=="string"){let t={};if(typeof e.arguments=="string")try{t=JSON.parse(e.arguments)}catch{t={}}else e.arguments&&typeof e.arguments=="object"&&(t=e.arguments);return{tool:e.name,args:t}}}return null}function t0(n){return n.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function n0(n){let e=[],t=/<<?action\s*>>?([\s\S]*?)(?:<<?\/action\s*>>?|$)/gi,s;for(;(s=t.exec(n))!==null;){let r=s[1].trim();if(r)try{let i=JSON.parse(r);i.tool&&i.args&&typeof i.args=="object"&&e.push({tool:i.tool,args:i.args,format:"action_tag_json",rawMatch:s[0]})}catch{let i=Kl(r,r.indexOf("{"));if(i)try{let o=JSON.parse(i);o.tool&&o.args&&typeof o.args=="object"&&e.push({tool:o.tool,args:o.args,format:"action_tag_json",rawMatch:s[0]})}catch{}}}return e}function s0(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim()),i=Ss(r);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function r0(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim());if(r.parameters||r.name){let i=Ss(r);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function i0(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;){let r=s[1],i=ag(r);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function ag(n){let e=[],t=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info"];for(let s of t){let r=new RegExp(`<<?${s}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${s}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=r.exec(n))!==null;){let o=i[1]||"",a=i[2]||"",l={},u=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,d;for(;(d=u.exec(o))!==null;){let p=d[1].toLowerCase(),m=d[2]??d[3]??d[4];l[p]=t0(m)}let f=a.trim();f&&(s==="write_file"||s==="append_to_file"?l.content=a:s==="run_command"?l.command=f:s==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),s==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:s,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function o0(n){return ag(n)}function a0(n){let e=[],t=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim()),i=Ss(r);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function l0(n){let e=[],t=/\{\s*"function"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Kl(n,s.index);if(r)try{let i=JSON.parse(r),o=Ss(i);o&&e.push({...o,format:"function_call",rawMatch:r})}catch{}}return e}function c0(n){let e=[],t=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Kl(n,s.index);if(r)try{let i=JSON.parse(r),o=Ss(i);o&&e.push({...o,format:"json_object",rawMatch:r})}catch{}}return e}function u0(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,s,r=!1;for(;(s=t.exec(n))!==null;){let i=s[1],o=/<function=([^>]+)>/i.exec(i);if(o){r=!0;let a=o[1].trim(),l={},u=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,d;for(;(d=u.exec(i))!==null;){let f=d[1].trim(),p=d[2].trim();p==="true"?p=!0:p==="false"?p=!1:!isNaN(Number(p))&&p!==""&&(p=Number(p)),l[f]=p}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:s[0]})}}if(!r&&/<function=([^>]+)>/i.test(n)){let i=/<function=([^>]+)>/i.exec(n);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=l.exec(n))!==null;){let d=u[1].trim(),f=u[2].trim();f==="true"?f=!0:f==="false"?f=!1:!isNaN(Number(f))&&f!==""&&(f=Number(f)),a[d]=f}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:n})}}return e}function lg(){return Ul||(Ul=new ql),Ul}var It,Hr,og,jr,Bl,ql,Ul,cg=N(()=>{"use strict";It=O(require("fs")),Hr=O(require("path")),og=O(require("os")),jr=Hr.join(og.homedir(),".hablas","model-formats.json");Bl=[{format:"action_tag_json",parse:n0},{format:"xml_tool_call_wrapper",parse:i0},{format:"xml_prompt",parse:o0},{format:"xml_tags",parse:s0},{format:"xml_parameters",parse:u0},{format:"hermes",parse:r0},{format:"markdown_json",parse:a0},{format:"function_call",parse:l0},{format:"json_object",parse:c0}],ql=class{registry;constructor(){this.registry=Z$()}parse(e,t,s){if(t&&Array.isArray(t)&&t.length>0){let i=t.filter(o=>o?.function?.name&&typeof o.function.name=="string");if(i.length>0){let o=i.map(a=>({function:{name:a.function.name,arguments:a.function.arguments||{}}}));return s&&this.learnFormat(s,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let r=e||"";if(!r.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(s){let i=this.registry[s];if(i&&i.format!=="native"){let o=Bl.find(a=>a.format===i.format);if(o){let a=o.parse(r);if(a.length>0)return this.learnFormat(s,i.format),this.buildResult(a,r)}}}for(let{parse:i}of Bl){let o=i(r);if(o.length>0){let a=o[0].format;return s&&this.learnFormat(s,a),this.buildResult(o,r)}}return{toolCalls:[],displayContent:r.trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let t=e.trim();return!!(/<<?action[\s>]/i.test(t)||/<<?tool[-_]call[\s>]/i.test(t)||/<function=/i.test(t)||t.includes("```tool_call")||t.includes("```json")&&t.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info)[\s>]/i.test(t)||t.startsWith("{")&&(t.includes('"name"')||t.includes('"tool"'))&&(t.includes('"arguments"')||t.includes('"args"')||t.includes('"parameters"'))||t.includes('"function"')&&t.includes('"name"'))}detectFormat(e){for(let{format:t,parse:s}of Bl)if(s(e).length>0)return t;return"unknown"}learnFormat(e,t){let s=this.registry[e];s&&s.format===t?(s.successCount++,s.lastUsed=new Date().toISOString()):this.registry[e]={format:t,successCount:1,lastUsed:new Date().toISOString()},e0(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[t,s]of Object.entries(this.registry))e[t]={format:s.format,successCount:s.successCount};return e}buildResult(e,t){let s=e.map(o=>({function:{name:o.tool,arguments:o.args}})),r=t,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)r=r.replace(o.rawMatch,"");return r=r.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),r=r.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),r=r.replace(/<<?action>>?[\s\S]*?<<?\/action>>?/gi,""),r=r.replace(/\n{3,}/g,`
|
|
796
|
+
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let t=this.failures.get(e);return t?t.count<=1&&t.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}}});function Z$(){try{if(It.existsSync(jr))return JSON.parse(It.readFileSync(jr,"utf-8"))}catch{}return{}}function e0(n){try{let e=Hr.dirname(jr);It.existsSync(e)||It.mkdirSync(e,{recursive:!0}),It.writeFileSync(jr,JSON.stringify(n,null,2),"utf-8")}catch{}}function Kl(n,e){let t=0,s=!1,r=!1;for(let i=e;i<n.length;i++){let o=n[i];if(r){r=!1;continue}if(o==="\\"&&s){r=!0;continue}if(o==='"'){s=!s;continue}if(!s&&(o==="{"&&t++,o==="}"&&(t--,t===0)))return n.slice(e,i+1)}return null}function Ss(n){if(typeof n.name=="string"&&n.arguments&&typeof n.arguments=="object")return{tool:n.name,args:n.arguments};if(typeof n.tool=="string"&&n.args&&typeof n.args=="object")return{tool:n.tool,args:n.args};if(typeof n.name=="string"&&n.parameters&&typeof n.parameters=="object")return{tool:n.name,args:n.parameters};if(n.function&&typeof n.function=="object"){let e=n.function;if(typeof e.name=="string"){let t={};if(typeof e.arguments=="string")try{t=JSON.parse(e.arguments)}catch{t={}}else e.arguments&&typeof e.arguments=="object"&&(t=e.arguments);return{tool:e.name,args:t}}}return null}function t0(n){return n.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function n0(n){let e=[],t=/<<?action\s*>>?([\s\S]*?)(?:<<?\/action\s*>>?|$)/gi,s;for(;(s=t.exec(n))!==null;){let r=s[1].trim();if(r)try{let i=JSON.parse(r);i.tool&&i.args&&typeof i.args=="object"&&e.push({tool:i.tool,args:i.args,format:"action_tag_json",rawMatch:s[0]})}catch{let i=Kl(r,r.indexOf("{"));if(i)try{let o=JSON.parse(i);o.tool&&o.args&&typeof o.args=="object"&&e.push({tool:o.tool,args:o.args,format:"action_tag_json",rawMatch:s[0]})}catch{}}}return e}function s0(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim()),i=Ss(r);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function r0(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim());if(r.parameters||r.name){let i=Ss(r);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function i0(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;){let r=s[1],i=ag(r);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function ag(n){let e=[],t=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info"];for(let s of t){let r=new RegExp(`<<?${s}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${s}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=r.exec(n))!==null;){let o=i[1]||"",a=i[2]||"",l={},u=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,d;for(;(d=u.exec(o))!==null;){let p=d[1].toLowerCase(),m=d[2]??d[3]??d[4];l[p]=t0(m)}let f=a.trim();f&&(s==="write_file"||s==="append_to_file"?l.content=a:s==="run_command"?l.command=f:s==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),s==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:s,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function o0(n){return ag(n)}function a0(n){let e=[],t=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim()),i=Ss(r);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function l0(n){let e=[],t=/\{\s*"function"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Kl(n,s.index);if(r)try{let i=JSON.parse(r),o=Ss(i);o&&e.push({...o,format:"function_call",rawMatch:r})}catch{}}return e}function c0(n){let e=[],t=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Kl(n,s.index);if(r)try{let i=JSON.parse(r),o=Ss(i);o&&e.push({...o,format:"json_object",rawMatch:r})}catch{}}return e}function u0(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,s,r=!1;for(;(s=t.exec(n))!==null;){let i=s[1],o=/<function=([^>]+)>/i.exec(i);if(o){r=!0;let a=o[1].trim(),l={},u=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,d;for(;(d=u.exec(i))!==null;){let f=d[1].trim(),p=d[2].trim();p==="true"?p=!0:p==="false"?p=!1:!isNaN(Number(p))&&p!==""&&(p=Number(p)),l[f]=p}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:s[0]})}}if(!r&&/<function=([^>]+)>/i.test(n)){let i=/<function=([^>]+)>/i.exec(n);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=l.exec(n))!==null;){let d=u[1].trim(),f=u[2].trim();f==="true"?f=!0:f==="false"?f=!1:!isNaN(Number(f))&&f!==""&&(f=Number(f)),a[d]=f}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:n})}}return e}function lg(){return Ul||(Ul=new ql),Ul}var It,Hr,og,jr,Bl,ql,Ul,cg=N(()=>{"use strict";It=O(require("fs")),Hr=O(require("path")),og=O(require("os")),jr=Hr.join(og.homedir(),".hablas","model-formats.json");Bl=[{format:"action_tag_json",parse:n0},{format:"xml_tool_call_wrapper",parse:i0},{format:"xml_prompt",parse:o0},{format:"xml_tags",parse:s0},{format:"xml_parameters",parse:u0},{format:"hermes",parse:r0},{format:"markdown_json",parse:a0},{format:"function_call",parse:l0},{format:"json_object",parse:c0}],ql=class{registry;constructor(){this.registry=Z$()}parse(e,t,s){if(t&&Array.isArray(t)&&t.length>0){let i=t.filter(o=>o?.function?.name&&typeof o.function.name=="string");if(i.length>0){let o=i.map(a=>({function:{name:a.function.name,arguments:a.function.arguments||{}}}));return s&&this.learnFormat(s,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let r=e||"";if(!r.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(s){let i=this.registry[s];if(i&&i.format!=="native"){let o=Bl.find(a=>a.format===i.format);if(o){let a=o.parse(r);if(a.length>0)return this.learnFormat(s,i.format),this.buildResult(a,r)}}}for(let{parse:i}of Bl){let o=i(r);if(o.length>0){let a=o[0].format;return s&&this.learnFormat(s,a),this.buildResult(o,r)}}return{toolCalls:[],displayContent:r.trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let t=e.trim();return!!(/<<?action[\s>]/i.test(t)||/<<?tool[-_]call[\s>]/i.test(t)||/<function=/i.test(t)||t.includes("```tool_call")||t.includes("```json")&&t.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info)[\s>]/i.test(t)||t.startsWith("{")&&(t.includes('"name"')||t.includes('"tool"'))&&(t.includes('"arguments"')||t.includes('"args"')||t.includes('"parameters"'))||t.includes('"function"')&&t.includes('"name"'))}detectFormat(e){for(let{format:t,parse:s}of Bl)if(s(e).length>0)return t;return"unknown"}learnFormat(e,t){let s=this.registry[e];s&&s.format===t?(s.successCount++,s.lastUsed=new Date().toISOString()):this.registry[e]={format:t,successCount:1,lastUsed:new Date().toISOString()},e0(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[t,s]of Object.entries(this.registry))e[t]={format:s.format,successCount:s.successCount};return e}buildResult(e,t){let s=e.map(o=>({function:{name:o.tool,arguments:o.args}})),r=t,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)r=r.replace(o.rawMatch,"");return r=r.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),r=r.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),r=r.replace(/<<?action>>?[\s\S]*?<<?\/action>>?/gi,""),r=r.replace(/<<?response>>?/gi,"").replace(/<<?\/response>>?/gi,""),r=r.replace(/\n{3,}/g,`
|
|
797
797
|
|
|
798
798
|
`),{toolCalls:s,displayContent:r.trim(),format:e[0]?.format??"unknown"}}},Ul=null});function f0(n,e,t){let r=lg().parse(e,n,t);return{toolCalls:r.toolCalls,displayContent:r.displayContent}}function p0(n,e){return n==="write_file"&&typeof e.path=="string"?`create ${e.path}`:(n==="edit_file"||n==="patch_file"||n==="search_and_replace")&&typeof e.path=="string"?`modify ${e.path}`:n==="read_file"&&typeof e.path=="string"?`read ${e.path}`:n==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):typeof e.path=="string"?String(e.path):n.replace(/_/g," ")}function h0(n){let e=(n||"").toLowerCase();return e.includes("eacces")||e.includes("permission")||e.includes("enospc")||e.includes("readonly")||e.includes("security")||e.includes("[write_file]")||e.includes("[delete_file]")||e.includes("[move_file]")||e.includes("[search_and_replace]")}async function fg(n,e,t,s){let r=0,i=Date.now();for(;r<=dg;){let o=await n.execute({name:e,arguments:t});if(o.success||r>=dg)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:r};r++,s.info({tool:e,retry:r,error:o.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-i,retries:r}}async function Ur(n){let{identity:e,client:t,registry:s,session:r,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:u,skipTools:d}=n,f=n.reactEngine??ws(),p=n.errorRecovery??xs(),m=d?[]:s.getOllamaTools(),h=t.getModel(),g=n.maxIterations??150,S="IDLE",k=0,x=(E,I)=>{let $=d0[S];if(!$||!$.includes(E))throw new Error(`\u{1F6AB} Illegal State Transition Attempt: ${S} \u2501\u2501\u25B6 ${E} (Reason: ${I??"none"})`);o.info({from:S,to:E,reason:I},"FSM State Transition"),S=E},A=[],y=[],v=[],b="",w=0,_=!1;for(x("THINKING","Starting agentic turn");w<g;){if(w++,u?.aborted)return x("TERMINAL_ABORT","Operation aborted by signal"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:"Aborted",completedNaturally:_};let E=f.buildBudgetWarningPrompt();E&&r.addUserMessage(E,{priority:"critical",tags:["system-budget"]});let I;try{I=await t.chatWithTools(r.getMessages(),m,u)}catch(C){if(C.name==="AbortError"||u?.aborted)return x("TERMINAL_ABORT","Aborted during inference"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:"Aborted",completedNaturally:_};if(w<=1){a.onNotice?.(`Transient model error: ${C.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(ne=>setTimeout(ne,1e3)),w--;continue}return x("TERMINAL_ABORT","Inference failure"),a.onError?.(C.message??"Model request failed"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:C.message,completedNaturally:_}}let $=I.message?.content||"",F=I.message?.tool_calls,H=f.parseThinking($);H.hasThinking&&(f.recordStep({thought:H.thinking}),o.debug({thinking:H.thinking.slice(0,200)},"ReAct thinking")),x("PARSE_VALIDATING","Received model response, parsing");let{toolCalls:X,displayContent:T}=f0(F,$,h);if(X.length===0&&$.toLowerCase().includes("<action>")){if(k++,k>=Br){x("STATE_RECONCILIATION",`Self-correction loop exhausted after ${k} attempts`);let ne=`Failed to execute after ${Br} syntax corrections. Rollback initiated.`;a.onError?.(ne);try{let D=s.get("undo");D&&await D.execute({count:100})}catch{}return x("TERMINAL_ABORT","Fatal syntactic self-correction exhaustion"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:ne,completedNaturally:_}}let C=`[SYSTEM ERROR - RETRY ${k}/${Br}] Malformed action block detected inside <action> tags. Expected a valid JSON object matching the HEP-1 tool schema.
|
|
799
799
|
Please correct your format and try again. Ensure all JSON keys/values are double-quoted and correctly escaped.`;x("ERROR_HEALING",`Syntax error inside action tags (attempt ${k})`),a.onNotice?.(`Malformed action block detected \u2014 healing attempt ${k}/${Br}\u2026`,"retry"),r.addToolMessage(C),x("THINKING","Error injected, waiting for next generation");continue}if(T&&T.trim()&&(b=T,await a.onAssistantText?.(T,e)),X.length===0){r.addAssistantMessage($,void 0,e.role),_=!0,x("SYNTHESIZING","Completed execution naturally");break}x("ACTION_READY","Action parsed and verified"),r.addAssistantMessage($,X,e.role);for(let C=0;C<X.length;C++){let ne=X[C];if(!ne?.function?.name)continue;let D=ne.function.name,W=ne.function.arguments||{},ie=s.getSafetyLevel(D)??"confirm";if(!s.get(D)){x("ERROR_HEALING",`Unknown tool execution: ${D}`),a.onNotice?.(`Unknown tool: ${D} \u2014 skipping`,"warn"),r.addToolMessage(`Error: Unknown tool "${D}". Available: ${s.getAll().map(re=>re.name).join(", ")}`),x("THINKING","Returning to thought loop");continue}if(await l(D,ie,W)==="skip"){r.addToolMessage(`Tool ${D} was skipped by policy/user.`);break}A.push(D),typeof W.path=="string"&&v.push(W.path);let ee=p0(D,W);a.onToolStart?.(D,ee,W),a.onToolCall?.(),f.recordStep({thought:H.hasThinking?`Executing: ${D}`:"",action:D,actionInput:W}),x("EXECUTING_TOOL",`Executing tool: ${D}`);let ge=await fg(s,D,W,o);a.onToolEnd?.(D,ge.success,ge.error||ge.output,ge.duration,W);let Fe;if(ge.success)Fe=ds(ge.output,ug),f.recordObservation(Fe.slice(0,300)),y.push({tool:D,success:!0,summary:ge.output.slice(0,150)}),x("THINKING",`Successfully executed tool: ${D}`);else{let re=ge.error||"Unknown error";if(h0(re)){x("STATE_RECONCILIATION",`Critical failure in tool ${D}: ${re}`),a.onNotice?.("Critical tool failure \u2014 aborting and rolling back changes.","warn");try{let se=s.get("undo");se&&await se.execute({count:100})}catch{}return x("TERMINAL_ABORT","State reverted due to critical failure"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:re,completedNaturally:_}}let K=p.analyze(D,re,W);if(Fe=p.buildRecoveryMessage(K,re),f.recordObservation(`FAILED: ${re}`,`Recovery: ${K.strategy} \u2014 ${K.suggestion}`),y.push({tool:D,success:!1,summary:re.slice(0,150)}),K.autoRetry&&!f.isOverBudget()){x("ERROR_HEALING","Attempting auto-recovery for transient error"),a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let se=await fg(s,D,W,o);a.onToolEnd?.(D,se.success,se.output,se.duration,W),se.success?(Fe=ds(se.output,ug),f.recordObservation(Fe.slice(0,300),"Auto-retry succeeded"),y[y.length-1]={tool:D,success:!0,summary:se.output.slice(0,150)},x("THINKING","Recovery successful")):x("THINKING","Recovery failed, continuing turn")}else x("THINKING","Continuing turn with failed step")}r.addToolMessage(Fe),ge.success&&D==="read_file"&&typeof W.path=="string"&&i?.addFile(W.path,ge.output),o.info({tool:D,success:ge.success,durationMs:ge.duration,retries:ge.retries},"Tool executed")}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return w>=g&&!_?(a.onNotice?.(`Reached max iterations (${g}). Stopping.`,"warn"),x("TERMINAL_ABORT","Max iterations boundary exceeded"),{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!1,error:"Max iterations exceeded",completedNaturally:_}):(x("TERMINAL_SUCCESS","Turn finalized successfully"),S="IDLE",{output:b,toolsUsed:Ne(A),toolResults:y,touchedFiles:Ne(v),iterations:w,success:!0,completedNaturally:_})}function Ne(n){return[...new Set(n)]}function pg(n){return async(e,t)=>{let s=e.replace(/_/g," ");return!n.autoMode&&n.interactive?t==="confirm"&&n.confirm?await n.confirm(`Proceed with ${s}?`)?"allow":"skip":t==="dangerous"&&n.confirmDangerous?await n.confirmDangerous(`Dangerous: ${s}`)?"allow":"skip":"allow":!n.autoMode&&t==="dangerous"?"skip":"allow"}}function hg(){return(n,e)=>e==="dangerous"?"skip":"allow"}var ug,dg,Br,d0,Wl=N(()=>{"use strict";ba();Fl();Hl();cg();ug=2e3,dg=2,Br=3,d0={IDLE:["THINKING"],THINKING:["PARSE_VALIDATING","TERMINAL_ABORT"],PARSE_VALIDATING:["ACTION_READY","ERROR_HEALING","SYNTHESIZING","TERMINAL_ABORT"],ACTION_READY:["EXECUTING_TOOL","STATE_RECONCILIATION","TERMINAL_ABORT"],EXECUTING_TOOL:["THINKING","ERROR_HEALING","STATE_RECONCILIATION","TERMINAL_ABORT"],ERROR_HEALING:["THINKING","STATE_RECONCILIATION","TERMINAL_ABORT"],STATE_RECONCILIATION:["TERMINAL_ABORT"],SYNTHESIZING:["TERMINAL_SUCCESS","TERMINAL_ABORT"],TERMINAL_SUCCESS:["IDLE"],TERMINAL_ABORT:["IDLE"]}});var gg,m0,g0,y0,mg,qr,yg=N(()=>{"use strict";gg=O(Dl());Bn();wa();va();mn();Ni();Ua();Wl();m0={hablas:"planner",bob:"architect",alex:"coder",david:"researcher",emma:"product-manager"},g0=(0,gg.default)({level:"silent"}),y0=40,mg={hablas:{role:"hablas",model:"stepfun-ai/step-3.7-flash",temperature:.7},bob:{role:"bob",model:"stepfun-ai/step-3.7-flash",temperature:.4},alex:{role:"alex",model:"stepfun-ai/step-3.7-flash",temperature:.2},david:{role:"david",model:"stepfun-ai/step-3.7-flash",temperature:.5},emma:{role:"emma",model:"stepfun-ai/step-3.7-flash",temperature:.6}},qr=class{baseConfig;agentModels;toolRegistry=null;onOutput=null;channel=null;mindsetRegistry=br();sharedContext=null;contextManager;constructor(e){this.baseConfig=e,this.agentModels=qn(),this.contextManager=new on(e)}setSharedContext(e){this.sharedContext=e}setChannel(e){this.channel=e}setToolRegistry(e){this.toolRegistry=e}setOutputCallback(e){this.onOutput=e}reloadModels(){this.agentModels=qn()}getAgentModel(e){let t=this.agentModels[e];if(t)return{model:t.model,temperature:t.temperature??mg[e]?.temperature??.5};let s=mg[e];return{model:s.model,temperature:s.temperature??.5}}async runAgent(e,t,s,r,i){let o=Date.now(),a=_e.find(x=>x.role===e),l=this.getAgentModel(e),u=i?.maxIterations||y0,d={...this.baseConfig,model:l.model},f=He(d),p=this.buildAgentPrompt(a,s),m=new an(p,30,this.baseConfig.contextBudget);m.addUserMessage(t);let h={name:a.name,title:a.title,role:e};this.emit(a.name,"thinking",`\u2605 Hablas \u2192 Delegating to @${a.name} (${a.title})...`);let g={onAssistantText:x=>{this.emit(a.name,"speaking",x.slice(0,200))},onToolStart:(x,A,y)=>{this.emit(a.name,"tool",A),this.channel&&this.channel.emitEvent({type:"act",agent:a.name,toolName:x,toolArgs:this.safeArgs(y),content:A})},onToolEnd:(x,A,y)=>{this.channel&&this.channel.emitEvent({type:"observe",agent:a.name,toolName:x,success:A,content:A?this.summarizeOk(x,y):`error: ${y.slice(0,120)}`})},onError:x=>this.emit(a.name,"error",x)},S=await Ur({identity:h,client:f,registry:this.toolRegistry,session:m,contextManager:this.contextManager,logger:g0,io:g,safetyPolicy:hg(),abortSignal:i?.abortSignal,skipTools:(!r||r.length===0,!1),maxIterations:u});if(this.sharedContext&&S.touchedFiles.length)try{this.sharedContext.set(`files:@${a.name}`,S.touchedFiles.join(", "))}catch{}let k=S.touchedFiles.length?[`@${a.name} touched: ${S.touchedFiles.join(", ")}`]:[];return{agent:e,agentName:a.name,output:S.output||(S.success?"Done.":S.error??"No output"),toolsUsed:S.toolsUsed,toolResults:S.toolResults,duration:Date.now()-o,iterations:S.iterations,success:S.success,error:S.error,discoveries:k,touchedFiles:S.touchedFiles}}async runSequential(e,t,s){let r=[],i="",o=[];for(let a=0;a<e.length;a++){let{role:l,task:u}=e[a];if(s?.abortSignal?.aborted)break;let d=[];if(i&&(d.push("## Previous Agent Results"),d.push(i)),o.length>0){d.push(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hablas-ai",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.8",
|
|
4
4
|
"description": "Premium multi-agent AI coding agent for your terminal — local-first via Ollama, NVIDIA NIM, or any OpenAI-compatible API. Watch the team work in front of you.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"bin": {
|