@noorm/marie-cli 0.1.5 → 0.1.6
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/extension.cjs
CHANGED
|
@@ -544,7 +544,7 @@ Reason: <one concise line integrating Auditor/ISO findings>
|
|
|
544
544
|
|
|
545
545
|
Required Actions must be <= ${n}.`,d=await this.provider.createMessage({model:L.getModel(),system:nl,messages:[...e.map(u=>({role:u.role,content:u.content})),{role:"user",content:p}],max_tokens:900}),l=Qt.wrap(d.content).getText().substring(0,1200);return this.parseDecree(l,e,t,i,s,n,t.victoryStreak)}catch(i){return console.error("MarieAscendant evaluation error",i),{strategy:"EXECUTE",urgency:"MEDIUM",confidence:Math.max(1.2,this.lastConfidence*.8),isContinueDirective:this.hasContinueDirective(e),structuralUncertainty:!1,reason:"Fallback: Hero maintains course via instinct.",requiredActions:[],blockedBy:[],stopCondition:"landed",profile:L.getAscensionProfile(),raw:"Fallback decree (spirit pressure rift)"}}}parseDecree(e,t,a,i,s,n,o){let p=e.replace(/\r/g,""),d=p.match(/Strategy\s*:\s*(EXECUTE|DEBUG|RESEARCH|HYPE|PANIC)/i),l=p.match(/Urgency\s*:\s*(LOW|MEDIUM|HIGH)/i),u=p.match(/Confidence\s*:\s*([0-9]+(?:\.[0-9]+)?)/i),c=p.match(/Structural\s*Uncertainty\s*:\s*(YES|NO|TRUE|FALSE)/i),m=p.match(/Continue\s*Directive\s*:\s*(YES|NO|TRUE|FALSE)/i),h=p.match(/Required\s*Actions\s*:\s*(.+)/i),v=p.match(/Heroic\s*Vow\s*:\s*(.+)/i),f=p.match(/Karma\s*Bond\s*:\s*(.+)/i),g=p.match(/Sacrifice\s*Triggered\s*:\s*(YES|NO|TRUE|FALSE)/i),b=p.match(/Blocked\s*By\s*:\s*(.+)/i),A=p.match(/Stop\s*Condition\s*:\s*(landed|structural_uncertainty)/i),k=p.match(/Reason\s*:\s*(.+)/i),E=this.inferStrategy(p),N=d?.[1]?.toUpperCase()||E,V=l?.[1]?.toUpperCase()||this.inferUrgency(p),T=this.clampConfidence(Number(u?.[1]??this.inferConfidence(V,N))),w=this.parseBoolean(c?.[1])||this.inferUncertainty(p),_=this.parseBoolean(m?.[1])||this.hasContinueDirective(t)||/continue\s+immediately/i.test(p),M=this.parseDelimitedList(h?.[1]).slice(0,n),D=v?.[1]?.trim(),R=f?.[1]?.trim(),q=this.parseBoolean(g?.[1]),j=this.parseDelimitedList(b?.[1]).slice(0,4),W=A?.[1]?.toLowerCase()||(w?"structural_uncertainty":"landed");return D&&(T=Math.min(3,T+.5)),a.isAwakened&&(T=3),T=this.applyProfileTuning(T,i,s,w,o),_&&(N==="EXECUTE"||N==="HYPE")&&(T=Math.min(3,T+.3)),this.lastConfidence=T,N==="EXECUTE"||N==="HYPE"?this.consecutiveSuccesses++:this.consecutiveSuccesses=0,{strategy:N,urgency:V,confidence:T,structuralUncertainty:w,isContinueDirective:_,heroicVow:D,sacrificeTriggered:q,reason:(k?.[1]||this.defaultReason(N,V)).trim().substring(0,220),requiredActions:M,blockedBy:j,stopCondition:W,profile:i,raw:p.substring(0,1200)}}inferStrategy(e){return/uncertainty|unknown|unclear|ambiguous\s+structure|dependency\s+risk/i.test(e)?"DEBUG":/research|investigate|inspect/i.test(e)?"RESEARCH":/ship|launch|demo day|hype|singularity/i.test(e)?"HYPE":/panic|halt|assess\s+failure/i.test(e)?"PANIC":/limit\s*break|absolute\s*conviction|no\s*limit/i.test(e)?"LIMIT_BREAK":"EXECUTE"}inferUrgency(e){return/immediately|now|urgent|critical momentum|no hesitation/i.test(e)?"HIGH":/careful|cautious|stability/i.test(e)?"LOW":"MEDIUM"}inferConfidence(e,t){return t==="HYPE"?2:t==="PANIC"?.5:e==="HIGH"?1.9:e==="LOW"?1:1.5}inferUncertainty(e){return/structural\s+uncertainty|critical unknown|not enough context|missing wiring/i.test(e)}defaultReason(e,t){return`Hero signal: ${e} with ${t.toLowerCase()} urgency.`}parseBoolean(e){return e?["YES","TRUE"].includes(e.toUpperCase()):!1}clampConfidence(e){return Number.isFinite(e)?Math.min(3,Math.max(.5,e)):1.2}applyProfileTuning(e,t,a,i,s){let n=1;t==="demo_day"&&(n=1.2),t==="recovery"&&(n=.9);let o=Math.min(.5,(s||0)*.05),p=e*n*a*(1+o);i&&(p*=.85);let d=this.lastConfidence*.15;return p+=d,this.clampConfidence(p)}parseDelimitedList(e){return e?/^none$/i.test(e.trim())?[]:e.split(/[|,;]/).map(t=>t.trim()).filter(Boolean).slice(0,6):[]}hasContinueDirective(e){let t=[...e].reverse().find(a=>a?.role==="user"&&typeof a?.content=="string");return t?/\bcontinue\b/i.test(t.content):!1}};var gi=class{constructor(e){this.tracker=e}toolsInFlight=new Map;getLock(e){let t=this.toolsInFlight.get(e);return t||(t={write:null,reads:new Set},this.toolsInFlight.set(e,t)),t}async acquireLock(e,t,a,i){let s=this.getLock(e);if(i&&s.ownerContextId===i)return;let n=Date.now(),o=async p=>{if(!p)return;let d=setInterval(()=>{let c=Date.now()-n;c>5e3&&(console.warn(`[MarieLockManager] SLOW LOCK: Acquisition on ${e} taking ${c}ms...`),this.tracker&&this.tracker.emitEvent({type:"reasoning",runId:this.tracker.getRun().runId,text:`\u26A0\uFE0F SLOW LOCK: Acquisition on ${e} is delayed...`,elapsedMs:this.tracker.elapsedMs()}))},5e3),l,u=new Promise((c,m)=>l=setTimeout(()=>m(new Error(`Extreme Stability: Lock Acquisition Timeout on ${e}`)),3e4));try{return await Promise.race([p,u])}finally{clearInterval(d),clearTimeout(l)}};if(t)for(s.write&&await o(s.write),await o(Promise.allSettled(Array.from(s.reads))),s=this.getLock(e);s.write||s.reads.size>0;){if(a?.aborted)throw new Error("Aborted while waiting for lock");s.write&&await o(s.write),s.reads.size>0&&await o(Promise.allSettled(Array.from(s.reads))),s=this.getLock(e)}else s.write&&await o(s.write)}registerExecution(e,t,a,i){let s=this.getLock(e);t?(s.write=a,i&&(s.ownerContextId=i)):s.reads.add(a),a.finally(()=>{this.releaseLock(e,t,a,i)})}releaseLock(e,t,a,i){let s=this.toolsInFlight.get(e);s&&(t?s.write===a&&(s.write=null,s.ownerContextId===i&&(s.ownerContextId=void 0)):s.reads.delete(a),!s.write&&s.reads.size===0&&this.toolsInFlight.delete(e))}async waitForAll(){let e=[];for(let t of Array.from(this.toolsInFlight.values()))t.write&&e.push(t.write),t.reads.forEach(a=>e.push(a));await Promise.allSettled(e)}};var Pe=class{static repairJsonDetailed(e){if(typeof e!="string")return{repaired:"{}",wasFixed:!1};let t=e.trim();if(!t)return{repaired:"{}",wasFixed:!1};let a=!1,i=t;t=t.replace(/'/g,'"');let s=!1,n=[],o=0;for(;o<t.length;){let l=t[o],c=(o>0?t[o-1]:"")==="\\";if(l==='"'&&!c)s=!s;else if(!s){if(l==="{"||l==="[")n.push(l);else if(l==="}"||l==="]"){let m=l==="}"?"{":"[";n.length>0&&n[n.length-1]===m&&n.pop()}}o++}s&&(t+='"');let p=n.length>0;for(;n.length>0;){let l=n.pop();l==="{"?t+="}":l==="["&&(t+="]")}t=t.replace(/([{,]\s*)([a-zA-Z0-9_$]+)(\s*):/g,'$1"$2"$3:');let d=/,\s*[}\]]/.test(t);return t=t.replace(/,\s*([}\]])/g,"$1"),a=t!==i||p||d||s,{repaired:t,wasFixed:a}}static repairJson(e){return this.repairJsonDetailed(e).repaired}static parseCache=new Map;static PARSE_CACHE_MAX=100;static safeParseJson(e){let t=this.parseCache.get(e);if(t)return t.result;let{repaired:a,wasFixed:i}=this.repairJsonDetailed(e),s=JSON.parse(a);if(this.parseCache.set(e,{result:s,wasFixed:i}),this.parseCache.size>this.PARSE_CACHE_MAX){let n=this.parseCache.keys().next().value;n&&this.parseCache.delete(n)}return s}static safeParseJsonDetailed(e){let t=this.parseCache.get(e);if(t)return t;let{repaired:a,wasFixed:i}=this.repairJsonDetailed(e),n={result:JSON.parse(a),wasFixed:i};if(this.parseCache.set(e,n),this.parseCache.size>this.PARSE_CACHE_MAX){let o=this.parseCache.keys().next().value;o&&this.parseCache.delete(o)}return n}static extractToolCall(e){if(typeof e!="string")return null;let t=e.trim();if(!t||t.length<5)return null;let a=e,i=!1,s="";if(a=a.replace(/<thought>[\s\S]*?<\/thought>/g,""),/^\s*<\|tool_calls_section_begin\|>\s*<\|tool_calls_section_end\|>\s*$/.test(a))return console.warn("[Marie] JsonUtils: Empty tool section markers detected"),null;try{let m=a.indexOf("{"),h=a.lastIndexOf("}");if(m!==-1&&h>m){let v=a.substring(m,h+1),f=JSON.parse(v);if(f.tool_calls&&Array.isArray(f.tool_calls)&&f.tool_calls.length>0){let g=f.tool_calls[0];if(g.type&&g.arguments)return console.log("[Marie] JsonUtils: Found JSON tool_calls format"),{name:g.type,input:g.arguments,id:g.id,repaired:!0}}}}catch{}let o=a.match(/<(?:\|tool_call_begin\|>|\|tool_calls_section_begin\|>)\s*([\w.]+)(?::\d+)?(?:\s*<\|tool_call_arguments?_begin\|>)?\s*([\s\S]*?)(?:\s*(?:<\|tool_call_end\|>|<\|tool_calls_section_end\|>)|$)/);if(o){let m=o[2];if(!m||!m.trim())return console.warn("[Marie] JsonUtils: Tool section markers found but no content between them"),null;s=o[1].replace(/^functions\./,""),a=m,i=!0}else{let m=a.match(/([\w.]+)(?::(\d+))?>(\{[\s\S]*?)(?:$)/);if(m){s=m[1].replace(/^functions\./,"");let v=m[2]?`call_${m[2]}`:void 0;a=m[3];let{repaired:f,wasFixed:g}=this.repairJsonDetailed(a);try{let b=JSON.parse(f);return{name:s,input:b,id:v,repaired:g}}catch{}}let h=a.match(/<tool_code>([\s\S]*?)(?:<\/tool_code>|$)/);if(h)a=h[1];else{let v=a.match(/<tool_call>([\s\S]*?)(?:<\/tool_call>|$)/);if(v)a=v[1];else{let f=a.match(/<tool>([\s\S]*?)(?:<\/tool>|$)/);if(f)a=f[1];else{let g=a.match(/<invoke\s+([^>]*?name=["']?([^"'\s>]+)["']?[^>]*?)>/i);if(g){s=g[2];let b=g.index,A=a.substring(b+g[0].length),k=A.lastIndexOf("</invoke>"),E=k!==-1?A.substring(0,k):A,N={},V=/<parameter\s+[^>]*?name=["']?([^"'\s>]+)["']?[^>]*?>/gi,T;for(;(T=V.exec(E))!==null;){let w=T[1],_=T.index+T[0].length,M=E.indexOf("</parameter>",_),R=(M!==-1?E.substring(_,M):E.substring(_)).trim();if(R.startsWith("{")||R.startsWith("["))try{N[w]=JSON.parse(this.repairJson(R))}catch{N[w]=R}else R.toLowerCase()==="true"?N[w]=!0:R.toLowerCase()==="false"?N[w]=!1:!isNaN(Number(R))&&R!==""?N[w]=Number(R):N[w]=R}if(Object.keys(N).length>0)return{name:s,input:N,repaired:!0};a=E}}}}}let p=/```/.test(a);p&&(a=a.replace(/```(?:json)?/g,"").replace(/```/g,""));let d=a.indexOf("{"),l=a.lastIndexOf("}"),u=a.match(/\[Tool Use:\s*([\w.]+)\s*\]/i);if(u&&!s&&(s=u[1],console.log(`[Marie] JsonUtils: Found bracketed tool name: ${s}`)),d===-1)return s?{name:s,input:{},repaired:!0}:null;let c=a.substring(d);try{let{repaired:m,wasFixed:h}=this.repairJsonDetailed(c),v=JSON.parse(m);if(i)return{name:s,input:v,repaired:h||p};let f=this.normalizeToolCall(v);if(f)return f.repaired=h||p||d>0,f;if(s)return{name:s,input:v,repaired:h||p||d>0}}catch{}return null}static normalizeToolCall(e){if(e.tool_name&&e.tool_input)return{name:e.tool_name,input:e.tool_input,id:e.tool_id};if(e.name&&e.arguments)return{name:e.name,input:typeof e.arguments=="string"?this.safeParseJson(e.arguments):e.arguments,id:e.id};if(e.name&&e.input)return{name:e.name,input:e.input,id:e.id};let t=Object.keys(e);return t.length===1&&typeof e[t[0]]=="object"&&!Array.isArray(e[t[0]])?{name:t[0],input:e[t[0]]}:null}};var Vl={write_file:"write_to_file",edit_file:"replace_file_content",replace_in_file:"replace_file_content",read_files:"read_file",list_files:"list_dir",search_files:"grep_search",execute_command:"run_command",get_folder_tree:"get_folder_structure",multi_replace:"multi_replace_file_content",multi_edit_file:"multi_replace_file_content",delete_file:"discard_file",discard_file:"delete_file"},gn=class{constructor(e){this.toolRegistry=e}async performFuzzyRepair(e,t,a,i,s,n){if(Vl[e.name]){let u=Vl[e.name];if(this.toolRegistry.getTools().some(c=>c.name===u))return a.emitEvent({type:"reasoning",runId:a.getRun().runId,text:`\u{1FA79} PROACTIVE REPAIR: Mapping hallucinated tool: ${e.name} -> ${u}`,elapsedMs:a.elapsedMs()}),e.name=u,e.repaired=!0,await i.process(e,n)}let o=this.toolRegistry.getTools(),p="",d=0;for(let u of o){let c=Me.similarity(e.name,u.name);c>d&&(d=c,p=u.name)}let l=p?{name:p,similarity:d}:null;if(l&&l.similarity>.8&&l.name!==e.name)return a.emitEvent({type:"reasoning",runId:a.getRun().runId,text:`\u{1FA79} FUZZY REPAIR: Fixing tool name hallucination: ${e.name} -> ${l.name}`,elapsedMs:a.elapsedMs()}),e.name=l.name,await i.process(e,n);if(t.includes("ENOENT")||t.includes("not found")){let u=e.input?.path||e.input?.targetFile||e.input?.file;if(u&&typeof u=="string"){let c=s.recentFiles||[],m="",h=0;for(let f of c){let g=Me.similarity(u,f);g>h&&(h=g,m=f)}let v=m?{path:m,similarity:h}:null;if(v&&v.similarity>.85&&v.path!==u)return a.emitEvent({type:"reasoning",runId:a.getRun().runId,text:`\u{1FA79} FUZZY REPAIR: Fixing path hallucination: ${u} -> ${v.path}`,elapsedMs:a.elapsedMs()}),e.input.path&&(e.input.path=v.path),e.input.targetFile&&(e.input.targetFile=v.path),e.input.file&&(e.input.file=v.path),await i.process(e,n)}}return null}repairJsonString(e){let{repaired:t}=Pe.repairJsonDetailed(e);try{return JSON.parse(t),t}catch{return e}}};var he=$(require("vscode"),1);var yn=class r{buffers=new Map;static KEY_PATTERNS=new Map([['"path":',/[{"\s,]"path":/],['"content":',/[{"\s,]"content":/],['"old_content":',/[{"\s,]"old_content":/],['"search":',/[{"\s,]"search":/],['"replace":',/[{"\s,]"replace":/]]);static LINE_START_REGEX=/[{"\s,]"line_start"\s*:\s*(\d+)/;append(e,t){let a=(this.buffers.get(e)||"")+t;if(a.endsWith("\\")){let i=0;for(let s=a.length-1;s>=0&&a[s]==="\\";s--)i++;if(i%2!==0)return this.buffers.set(e,a.slice(0,-1)),this.parse(a.slice(0,-1))}return this.buffers.set(e,a),this.parse(a)}parse(e){let t={};t.path=this.extractString(e,'"path":'),t.content=this.extractString(e,'"content":'),t.old_content=this.extractString(e,'"old_content":'),t.search=this.extractString(e,'"search":'),t.replace=this.extractString(e,'"replace":');let a=e.match(r.LINE_START_REGEX);if(a){let i=parseInt(a[1]);isNaN(i)||(t.line_start=i)}return t}extractString(e,t){let a=e.indexOf(t);if(a===-1||this.isInsideString(e,a))return;if(a>0){let p=e[a-1];if(!["{",","," "," ",`
|
|
546
546
|
`,"\r"].includes(p))return}let i=a+t.length,s=e.indexOf('"',i);if(s===-1)return;let n=e.substring(s+1),o=this.findClosingQuote(n);return o!==-1?this.unescape(n.substring(0,o)):this.unescape(n)}isInsideString(e,t){let a=!1,i=!1;for(let s=0;s<t;s++){let n=e[s];if(i){i=!1;continue}if(n==="\\"){i=!0;continue}n==='"'&&(a=!a)}return a}findClosingQuote(e){for(let t=0;t<e.length;t++)if(e[t]==='"'){let a=0;for(let i=t-1;i>=0&&e[i]==="\\";i--)a++;if(a%2===0)return t}return-1}unescape(e){return e.replace(/\\(u[0-9a-fA-F]{4}|[^u])/g,(t,a)=>{if(a.startsWith("u")){let i=a.substring(1);return i.length===4?String.fromCharCode(parseInt(i,16)):`\\${a}`}switch(a){case"n":return`
|
|
547
|
-
`;case"r":return"\r";case"t":return" ";case"b":return"\b";case"f":return"\f";case'"':return'"';case"\\":return"\\";case"/":return"/";default:return a}})}clear(e){this.buffers.delete(e)}clearAll(){this.buffers.clear()}};var ql=$(require("vscode"),1),va=class r{static instance;scm;static MAX_DIFF_URIS=200;diffUris=new Map;constructor(e){this.scm=ql.scm.createSourceControl("marie","Marie Proposed Edits"),this.scm.quickDiffProvider={provideOriginalResource:t=>this.diffUris.get(t.toString())},e.subscriptions.push(this.scm),r.instance=this}static getInstance(){return this.instance}registerDiff(e,t){if(this.diffUris.size>=r.MAX_DIFF_URIS){let a=this.diffUris.keys().next().value;a&&this.diffUris.delete(a)}this.diffUris.set(e.toString(),t)}clear(e){this.diffUris.delete(e.toString())}clearAll(){this.diffUris.clear()}};var wa=class{static parser=new yn;static lastUpdate=0;static activeGhosts=new Map;static ghostDecoration=he.window.createTextEditorDecorationType({before:{color:new he.ThemeColor("editorGhostText.foreground"),fontStyle:"italic",margin:"0 0.5em 0 0"},opacity:"0.4",backgroundColor:new he.ThemeColor("editorGhostText.background"),isWholeLine:!0});static init(e){e.subscriptions.push(he.window.onDidChangeVisibleTextEditors(()=>{new Set(Array.from(this.activeGhosts.values()).map(a=>a.uri)).forEach(a=>this.refreshDecorations(he.Uri.parse(a)))}))}static thoughtDecoration=he.window.createTextEditorDecorationType({after:{color:new he.ThemeColor("editorCodeLens.foreground"),fontStyle:"italic",margin:"0 0 0 2em"},isWholeLine:!0});static showThought(e,t){let a=he.window.activeTextEditor;if(!a)return;let i=a.selection.active.line,s={range:new he.Range(i,0,i,0),renderOptions:{after:{contentText:` // \u{1F9E0} ${e}: ${t}`}}};a.setDecorations(this.thoughtDecoration,[s]);let n=`${a.document.uri.toString()}:${i}`;this.thoughtTimeouts.has(n)&&clearTimeout(this.thoughtTimeouts.get(n));let o=setTimeout(()=>{a.setDecorations(this.thoughtDecoration,[]),this.thoughtTimeouts.delete(n)},4e3);this.thoughtTimeouts.set(n,o)}static pendingDeltas=new Map;static updateTimer=null;static handleDelta(e,t,a){if(!["write_file","replace_in_file","write_to_file","replace_file_content","multi_replace_file_content"].includes(t))return;let i=this.pendingDeltas.get(e)||"";this.pendingDeltas.set(e,i+a),this.updateTimer||(this.updateTimer=setTimeout(()=>this.flushUpdates(),50))}static flushUpdates(){this.updateTimer=null;for(let[e,t]of Array.from(this.pendingDeltas.entries())){let a=this.parser.append(e,t),i=a.content!==void 0||a.replace!==void 0;if(a.path&&i){let s=he.Uri.file(a.path);this.updateGhost(e,s,a)}}this.pendingDeltas.clear()}static updateGhost(e,t,a){let i=he.window.visibleTextEditors.filter(l=>l.document.uri.toString()===t.toString());if(i.length===0)return;let s=i[0],n=0;if(a.line_start!==void 0)n=Math.max(0,a.line_start-1);else if(a.old_content||a.search){let u=(a.search||a.old_content||"").substring(0,30);if(u){for(let c=0;c<s.document.lineCount;c++)if(s.document.lineAt(c).text.includes(u)){n=c;break}}}let o=new he.Range(n,0,n,0),d=` $(sync~spin) Proposed: ${(a.replace||Me.extractText(a.content)||"").substring(0,80).replace(/\n/g," ")}...`;this.activeGhosts.set(e,{uri:t.toString(),range:o,text:d}),this.refreshDecorations(t),va.getInstance()?.registerDiff(t,t)}static refreshDecorations(e){let t=e.toString(),i=Array.from(this.activeGhosts.values()).filter(s=>s.uri===t).map(s=>({range:s.range,renderOptions:{before:{contentText:s.text}}}));he.window.visibleTextEditors.filter(s=>s.document.uri.toString()===t).forEach(s=>s.setDecorations(this.ghostDecoration,i))}static clear(e){let t=this.activeGhosts.get(e);t&&(this.activeGhosts.delete(e),this.refreshDecorations(he.Uri.parse(t.uri)),Array.from(this.activeGhosts.values()).some(i=>i.uri===t.uri)||va.getInstance()?.clear(he.Uri.parse(t.uri))),this.parser.clear(e)}static clearAll(){let e=new Set(Array.from(this.activeGhosts.values()).map(t=>t.uri));this.activeGhosts.clear(),this.parser.clearAll(),e.forEach(t=>this.refreshDecorations(he.Uri.parse(t))),va.getInstance()?.clearAll()}static thoughtTimeouts=new Map;static dispose(){this.ghostDecoration.dispose(),this.thoughtDecoration.dispose(),this.thoughtTimeouts.forEach(e=>clearTimeout(e)),this.thoughtTimeouts.clear(),this.updateTimer&&clearTimeout(this.updateTimer)}};var vn=class{constructor(e){this.tracker=e}heartbeatTimer=null;watchdogTimer=null;startTurnWatchdog(e){return this.stopTurnWatchdog(),this.watchdogTimer=setTimeout(()=>{console.error("[MariePulseService] LOCK RECOVERY: AI Engine lock held for >120s. Force-releasing..."),this.tracker.emitEvent({type:"reasoning",runId:this.tracker.getRun().runId,text:"\u{1F6A8} LOCK RECOVERY: Stale reasoning process detected (>120s). Force-releasing engine lock.",elapsedMs:this.tracker.elapsedMs()}),e()},12e4),this.watchdogTimer}stopTurnWatchdog(){this.watchdogTimer&&(clearTimeout(this.watchdogTimer),this.watchdogTimer=null)}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setTimeout(()=>{this.tracker.emitEvent({type:"reasoning",runId:this.tracker.getRun().runId,text:"\u{1F6A8} PLANETARY STABILITY HAZARD: AI reasoning hang detected (>60s).",elapsedMs:this.tracker.elapsedMs()})},6e4)}stopHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null)}cleanup(){this.stopHeartbeat(),this.stopTurnWatchdog(),wa.clearAll()}};var wn=class{static lag=0;static interval=null;static lastTick=Date.now();static cooldownActive=!1;static start(){this.interval||(this.lastTick=Date.now(),this.interval=setInterval(()=>{let e=Date.now(),t=e-this.lastTick-1e3;this.lag=Math.max(0,t),this.lastTick=e,this.lag>150?(console.warn(`[MarieStabilityMonitor] CRITICAL EVENT LOOP LAG: ${this.lag}ms. Triggering UI preservation cooldown.`),this.cooldownActive=!0):this.lag<50&&(this.cooldownActive=!1)},1e3),this.interval.unref&&this.interval.unref())}static stop(){this.interval&&(clearInterval(this.interval),this.interval=null)}static isHighPressure(){let e=process.memoryUsage(),t=e.heapUsed/e.heapTotal>.85;return this.lag>100||t||this.cooldownActive}static getLag(){return this.lag}static getMetrics(){let e=process.memoryUsage();return{lagMs:this.lag,heapUsedMb:Math.round(e.heapUsed/1024/1024),heapTotalMb:Math.round(e.heapTotal/1024/1024),cooldown:this.cooldownActive}}};var bn=class r{iterations=[];static MAX_SELF_REFLECTIONS=3;actionFrozen=!1;think(e,t){return this.iterations.length>=r.MAX_SELF_REFLECTIONS?!1:(this.iterations.push({iteration:this.iterations.length+1,thought:e,proposedAction:t}),!0)}freezeAction(){this.actionFrozen=!0}isActionFrozen(){return this.actionFrozen}validateOutput(e,t){return t(e)}getIterations(){return this.iterations}getIterationCount(){return this.iterations.length}isExhausted(){return this.iterations.length>=r.MAX_SELF_REFLECTIONS}produceResult(e,t){let a=this.validateOutput(e,t);return{iterations:this.iterations,finalOutput:e,schemaValidated:a,actionFrozen:this.actionFrozen}}reset(){this.iterations=[],this.actionFrozen=!1}};function Eu(r){return r>0?"continuation":"full"}var yi=class r{constructor(e,t,a,i,s,n){this.provider=e;this.toolRegistry=t;this.approvalRequester=a;this.providerFactory=i;this.fs=s;this.ghostPort=n;this.ascendant=new fn(this.provider),this.state=this.initializeState(),this.lockManager=new gi,this.toolMender=new gn(this.toolRegistry),this.reasoningBudget=new bn}static CONTENT_BUFFER_MAX_BYTES=1024*1024;ascendant;state;lockManager;toolMender;pulseService;reasoningBudget;toolCallCounter=0;contentBuffer="";lastContentEmit=0;static activeTurn=null;disposed=!1;initializeState(){return{errorHotspots:{},totalErrorCount:0,spiritPressure:50,recentFiles:[],toolHistory:[],techniqueExecutions:[],victoryStreak:0,shakyResponseDensity:0,writtenFiles:[],actionDiffs:{},wiringAlerts:[],mood:"STABLE",isSpiritBurstActive:!1,isAwakened:!1,karmaBond:void 0,panicCoolDown:0,environment:this.fs?.type==="vscode"?"vscode":"cli",lastFailedFile:void 0}}async chatLoop(e,t,a,i,s=0,n=0,o=""){if(this.disposed)throw new Error("MarieEngine has been disposed.");if(console.log(`[MarieEngine] chatLoop started at depth ${n}. Accumulated content length: ${o.length}`),r.activeTurn){console.warn("[MarieEngine] TURN COLLISION DETECTED. Waiting for previous turn to finalize..."),t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:"\u23F3 TURN COLLISION: Another AI turn is active. Queuing reasoning loop...",elapsedMs:t.elapsedMs()});let l=this.ensurePulseService(t).startTurnWatchdog(()=>{r.activeTurn=null});try{await r.activeTurn}finally{l&&clearTimeout(l)}}let p=()=>{};r.activeTurn=new Promise(d=>{p=d});try{let d=await this._executeChatLoop(e,t,a,i,s,n,o);return console.log(`[MarieEngine] chatLoop finished at depth ${n}. Final content length: ${d.length}`),d}finally{p(),r.activeTurn=null}}async _executeChatLoop(e,t,a,i,s=0,n=0,o=""){let p=this.ensurePulseService(t);if(n>20)throw new Error("Extreme Stability Alert: Maximum chatLoop depth reached. Possible infinite reasoning loop detected.");t.resetReasoningBudget(),this.lockManager=new gi(t);let d=new mn(t,this.ghostPort);wn.start(),t.getRun().steps===0&&!t.getRun().isResuming&&t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:"\u{1F525} Ascension protocol initiated. Hero's conviction rising.",elapsedMs:t.elapsedMs()});let l=this.state.isSpiritBurstActive,u=this.state.isAwakened;this.state.isSpiritBurstActive=this.state.spiritPressure>85,this.state.isAwakened=this.state.spiritPressure>95,this.state.isAwakened&&!u?t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:"\u2728 AWAKENED! Ultra Instinct achieved. Full codebase sovereignty established.",elapsedMs:t.elapsedMs()}):this.state.isSpiritBurstActive&&!l&&t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:"\u{1F4A5} SPIRIT BURST! Conviction is absolute. Auto-approval mandate expanded.",elapsedMs:t.elapsedMs()}),Date.now()-(this.state.techniqueExecutions.slice(-1)[0]?.timestamp||0)>3e5&&(this.state.spiritPressure=Math.max(30,this.state.spiritPressure-10));let c=new hn(this.toolRegistry,t,async(w,_)=>this.shouldAutoApprove(w,_)?(t.emitEvent({type:"checkpoint",runId:t.getRun().runId,status:"approved",toolName:w,summary:{what:"Ascension Auto-Approved",why:"Heroic Conviction",impact:"Maximum Speed"},elapsedMs:t.elapsedMs()}),!0):this.approvalRequester(w,_),this.state,this.fs),m="",h=new Map,v=new Map,f=[],g=0,b=0,A=Date.now(),k=30,E=async w=>{if(!this.toolRegistry.getTool(w.name))return this.updateShakyResponse(),{type:"tool_result",tool_use_id:w.id,content:`Error: Tool "${w.name}" not found.`};let M=Date.now();p.startHeartbeat();try{t.getRun().activeObjectiveId==="understand_request"&&(t.setObjectiveStatus("understand_request","completed"),t.setObjectiveStatus("execute_plan","in_progress"),t.getRun().activeObjectiveId="execute_plan",t.emitProgressUpdate(`Executing technique: ${w.name}`));let D=await c.process(w,i);typeof D=="string"&&D.length>1024*1024&&(D=D.substring(0,1024*1024)+`
|
|
547
|
+
`;case"r":return"\r";case"t":return" ";case"b":return"\b";case"f":return"\f";case'"':return'"';case"\\":return"\\";case"/":return"/";default:return a}})}clear(e){this.buffers.delete(e)}clearAll(){this.buffers.clear()}};var ql=$(require("vscode"),1),va=class r{static instance;scm;static MAX_DIFF_URIS=200;diffUris=new Map;constructor(e){this.scm=ql.scm.createSourceControl("marie","Marie Proposed Edits"),this.scm.quickDiffProvider={provideOriginalResource:t=>this.diffUris.get(t.toString())},e.subscriptions.push(this.scm),r.instance=this}static getInstance(){return this.instance}registerDiff(e,t){if(this.diffUris.size>=r.MAX_DIFF_URIS){let a=this.diffUris.keys().next().value;a&&this.diffUris.delete(a)}this.diffUris.set(e.toString(),t)}clear(e){this.diffUris.delete(e.toString())}clearAll(){this.diffUris.clear()}};var wa=class{static parser=new yn;static lastUpdate=0;static activeGhosts=new Map;static ghostDecoration=he.window.createTextEditorDecorationType({before:{color:new he.ThemeColor("editorGhostText.foreground"),fontStyle:"italic",margin:"0 0.5em 0 0"},opacity:"0.4",backgroundColor:new he.ThemeColor("editorGhostText.background"),isWholeLine:!0});static init(e){e.subscriptions.push(he.window.onDidChangeVisibleTextEditors(()=>{new Set(Array.from(this.activeGhosts.values()).map(a=>a.uri)).forEach(a=>this.refreshDecorations(he.Uri.parse(a)))}))}static thoughtDecoration=he.window.createTextEditorDecorationType({after:{color:new he.ThemeColor("editorCodeLens.foreground"),fontStyle:"italic",margin:"0 0 0 2em"},isWholeLine:!0});static showThought(e,t){let a=he.window.activeTextEditor;if(!a)return;let i=a.selection.active.line,s={range:new he.Range(i,0,i,0),renderOptions:{after:{contentText:` // \u{1F9E0} ${e}: ${t}`}}};a.setDecorations(this.thoughtDecoration,[s]);let n=`${a.document.uri.toString()}:${i}`;this.thoughtTimeouts.has(n)&&clearTimeout(this.thoughtTimeouts.get(n));let o=setTimeout(()=>{a.setDecorations(this.thoughtDecoration,[]),this.thoughtTimeouts.delete(n)},2e3);this.thoughtTimeouts.set(n,o)}static pendingDeltas=new Map;static updateTimer=null;static handleDelta(e,t,a){if(!["write_file","replace_in_file","write_to_file","replace_file_content","multi_replace_file_content"].includes(t))return;let i=this.pendingDeltas.get(e)||"";this.pendingDeltas.set(e,i+a),this.updateTimer||(this.updateTimer=setTimeout(()=>this.flushUpdates(),20))}static flushUpdates(){this.updateTimer=null;for(let[e,t]of Array.from(this.pendingDeltas.entries())){let a=this.parser.append(e,t),i=a.content!==void 0||a.replace!==void 0;if(a.path&&i){let s=he.Uri.file(a.path);this.updateGhost(e,s,a)}}this.pendingDeltas.clear()}static updateGhost(e,t,a){let i=he.window.visibleTextEditors.filter(l=>l.document.uri.toString()===t.toString());if(i.length===0)return;let s=i[0],n=0;if(a.line_start!==void 0)n=Math.max(0,a.line_start-1);else if(a.old_content||a.search){let u=(a.search||a.old_content||"").substring(0,30);if(u){for(let c=0;c<s.document.lineCount;c++)if(s.document.lineAt(c).text.includes(u)){n=c;break}}}let o=new he.Range(n,0,n,0),d=` $(sync~spin) Proposed: ${(a.replace||Me.extractText(a.content)||"").substring(0,80).replace(/\n/g," ")}...`;this.activeGhosts.set(e,{uri:t.toString(),range:o,text:d}),this.refreshDecorations(t),va.getInstance()?.registerDiff(t,t)}static refreshDecorations(e){let t=e.toString(),i=Array.from(this.activeGhosts.values()).filter(s=>s.uri===t).map(s=>({range:s.range,renderOptions:{before:{contentText:s.text}}}));he.window.visibleTextEditors.filter(s=>s.document.uri.toString()===t).forEach(s=>s.setDecorations(this.ghostDecoration,i))}static clear(e){let t=this.activeGhosts.get(e);t&&(this.activeGhosts.delete(e),this.refreshDecorations(he.Uri.parse(t.uri)),Array.from(this.activeGhosts.values()).some(i=>i.uri===t.uri)||va.getInstance()?.clear(he.Uri.parse(t.uri))),this.parser.clear(e)}static clearAll(){let e=new Set(Array.from(this.activeGhosts.values()).map(t=>t.uri));this.activeGhosts.clear(),this.parser.clearAll(),e.forEach(t=>this.refreshDecorations(he.Uri.parse(t))),va.getInstance()?.clearAll()}static thoughtTimeouts=new Map;static dispose(){this.ghostDecoration.dispose(),this.thoughtDecoration.dispose(),this.thoughtTimeouts.forEach(e=>clearTimeout(e)),this.thoughtTimeouts.clear(),this.updateTimer&&clearTimeout(this.updateTimer)}};var vn=class{constructor(e){this.tracker=e}heartbeatTimer=null;watchdogTimer=null;startTurnWatchdog(e){return this.stopTurnWatchdog(),this.watchdogTimer=setTimeout(()=>{console.error("[MariePulseService] LOCK RECOVERY: AI Engine lock held for >300s. Force-releasing..."),this.tracker.emitEvent({type:"reasoning",runId:this.tracker.getRun().runId,text:"\u{1F6A8} LOCK RECOVERY: Stale reasoning process detected (>300s). Force-releasing engine lock.",elapsedMs:this.tracker.elapsedMs()}),e()},3e5),this.watchdogTimer}stopTurnWatchdog(){this.watchdogTimer&&(clearTimeout(this.watchdogTimer),this.watchdogTimer=null)}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setTimeout(()=>{this.tracker.emitEvent({type:"reasoning",runId:this.tracker.getRun().runId,text:"\u{1F6A8} PLANETARY STABILITY HAZARD: AI reasoning hang detected (>120s).",elapsedMs:this.tracker.elapsedMs()})},12e4)}stopHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null)}cleanup(){this.stopHeartbeat(),this.stopTurnWatchdog(),wa.clearAll()}};var wn=class{static lag=0;static interval=null;static lastTick=Date.now();static cooldownActive=!1;static start(){this.interval||(this.lastTick=Date.now(),this.interval=setInterval(()=>{let e=Date.now(),t=e-this.lastTick-1e3;this.lag=Math.max(0,t),this.lastTick=e,this.lag>150?(console.warn(`[MarieStabilityMonitor] CRITICAL EVENT LOOP LAG: ${this.lag}ms. Triggering UI preservation cooldown.`),this.cooldownActive=!0):this.lag<50&&(this.cooldownActive=!1)},1e3),this.interval.unref&&this.interval.unref())}static stop(){this.interval&&(clearInterval(this.interval),this.interval=null)}static isHighPressure(){let e=process.memoryUsage(),t=e.heapUsed/e.heapTotal>.85;return this.lag>100||t||this.cooldownActive}static getLag(){return this.lag}static getMetrics(){let e=process.memoryUsage();return{lagMs:this.lag,heapUsedMb:Math.round(e.heapUsed/1024/1024),heapTotalMb:Math.round(e.heapTotal/1024/1024),cooldown:this.cooldownActive}}};var bn=class r{iterations=[];static MAX_SELF_REFLECTIONS=3;actionFrozen=!1;think(e,t){return this.iterations.length>=r.MAX_SELF_REFLECTIONS?!1:(this.iterations.push({iteration:this.iterations.length+1,thought:e,proposedAction:t}),!0)}freezeAction(){this.actionFrozen=!0}isActionFrozen(){return this.actionFrozen}validateOutput(e,t){return t(e)}getIterations(){return this.iterations}getIterationCount(){return this.iterations.length}isExhausted(){return this.iterations.length>=r.MAX_SELF_REFLECTIONS}produceResult(e,t){let a=this.validateOutput(e,t);return{iterations:this.iterations,finalOutput:e,schemaValidated:a,actionFrozen:this.actionFrozen}}reset(){this.iterations=[],this.actionFrozen=!1}};function Eu(r){return r>0?"continuation":"full"}var yi=class r{constructor(e,t,a,i,s,n){this.provider=e;this.toolRegistry=t;this.approvalRequester=a;this.providerFactory=i;this.fs=s;this.ghostPort=n;this.ascendant=new fn(this.provider),this.state=this.initializeState(),this.lockManager=new gi,this.toolMender=new gn(this.toolRegistry),this.reasoningBudget=new bn}static CONTENT_BUFFER_MAX_BYTES=1024*1024;ascendant;state;lockManager;toolMender;pulseService;reasoningBudget;toolCallCounter=0;contentBuffer="";lastContentEmit=0;static activeTurn=null;disposed=!1;initializeState(){return{errorHotspots:{},totalErrorCount:0,spiritPressure:50,recentFiles:[],toolHistory:[],techniqueExecutions:[],victoryStreak:0,shakyResponseDensity:0,writtenFiles:[],actionDiffs:{},wiringAlerts:[],mood:"STABLE",isSpiritBurstActive:!1,isAwakened:!1,karmaBond:void 0,panicCoolDown:0,environment:this.fs?.type==="vscode"?"vscode":"cli",lastFailedFile:void 0}}async chatLoop(e,t,a,i,s=0,n=0,o=""){if(this.disposed)throw new Error("MarieEngine has been disposed.");if(console.log(`[MarieEngine] chatLoop started at depth ${n}. Accumulated content length: ${o.length}`),r.activeTurn){console.warn("[MarieEngine] TURN COLLISION DETECTED. Waiting for previous turn to finalize..."),t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:"\u23F3 TURN COLLISION: Another AI turn is active. Queuing reasoning loop...",elapsedMs:t.elapsedMs()});let l=this.ensurePulseService(t).startTurnWatchdog(()=>{r.activeTurn=null});try{await r.activeTurn}finally{l&&clearTimeout(l)}}let p=()=>{};r.activeTurn=new Promise(d=>{p=d});try{let d=await this._executeChatLoop(e,t,a,i,s,n,o);return console.log(`[MarieEngine] chatLoop finished at depth ${n}. Final content length: ${d.length}`),d}finally{p(),r.activeTurn=null}}async _executeChatLoop(e,t,a,i,s=0,n=0,o=""){let p=this.ensurePulseService(t);if(n>20)throw new Error("Extreme Stability Alert: Maximum chatLoop depth reached. Possible infinite reasoning loop detected.");t.resetReasoningBudget(),this.lockManager=new gi(t);let d=new mn(t,this.ghostPort);wn.start(),t.getRun().steps===0&&!t.getRun().isResuming&&t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:"\u{1F525} Ascension protocol initiated. Hero's conviction rising.",elapsedMs:t.elapsedMs()});let l=this.state.isSpiritBurstActive,u=this.state.isAwakened;this.state.isSpiritBurstActive=this.state.spiritPressure>85,this.state.isAwakened=this.state.spiritPressure>95,this.state.isAwakened&&!u?t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:"\u2728 AWAKENED! Ultra Instinct achieved. Full codebase sovereignty established.",elapsedMs:t.elapsedMs()}):this.state.isSpiritBurstActive&&!l&&t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:"\u{1F4A5} SPIRIT BURST! Conviction is absolute. Auto-approval mandate expanded.",elapsedMs:t.elapsedMs()}),Date.now()-(this.state.techniqueExecutions.slice(-1)[0]?.timestamp||0)>3e5&&(this.state.spiritPressure=Math.max(30,this.state.spiritPressure-10));let c=new hn(this.toolRegistry,t,async(w,_)=>this.shouldAutoApprove(w,_)?(t.emitEvent({type:"checkpoint",runId:t.getRun().runId,status:"approved",toolName:w,summary:{what:"Ascension Auto-Approved",why:"Heroic Conviction",impact:"Maximum Speed"},elapsedMs:t.elapsedMs()}),!0):this.approvalRequester(w,_),this.state,this.fs),m="",h=new Map,v=new Map,f=[],g=0,b=0,A=Date.now(),k=30,E=async w=>{if(!this.toolRegistry.getTool(w.name))return this.updateShakyResponse(),{type:"tool_result",tool_use_id:w.id,content:`Error: Tool "${w.name}" not found.`};let M=Date.now();p.startHeartbeat();try{t.getRun().activeObjectiveId==="understand_request"&&(t.setObjectiveStatus("understand_request","completed"),t.setObjectiveStatus("execute_plan","in_progress"),t.getRun().activeObjectiveId="execute_plan",t.emitProgressUpdate(`Executing technique: ${w.name}`));let D=await c.process(w,i);typeof D=="string"&&D.length>1024*1024&&(D=D.substring(0,1024*1024)+`
|
|
548
548
|
|
|
549
549
|
\u{1F6A8} Truncated at 1MB.`);let R=Date.now()-M,q=w.input?.path||w.input?.targetFile||w.input?.file;return typeof D=="string"&&D.startsWith("Error")?(this.handleFailure(t,w.name,D,q),g++):this.handleSuccess(t,w.name,R,q),this.toolCallCounter++,{type:"tool_result",tool_use_id:w.id,content:D}}finally{p.stopHeartbeat()}},N=Eu(n),V=new cn(this.provider,this.toolRegistry,a,e,t,this.providerFactory,N);try{let w=V.executeLoop(e,i);for await(let _ of w)if(A=Date.now(),p.startHeartbeat(),process.env.MARIE_DEBUG&&console.log(`[Engine Debug] AI Event: ${_.type}`,_.type==="content_delta"?`(${_.text.length} chars)`:""),d.dispatch(_),_.type==="content_delta"){if(m+=_.text,this.contentBuffer+=_.text,this.contentBuffer.length>=r.CONTENT_BUFFER_MAX_BYTES)break}else if(_.type==="tool_call_delta"){let D=h.get(_.index);if(D?(_.id&&!D.id&&(D.id=_.id),_.name&&!D.name&&(D.name=_.name)):(D={id:_.id,name:_.name,inputString:""},h.set(_.index,D)),_.argumentsDelta&&(D.inputString+=_.argumentsDelta),D.name&&this.isLikelyCompleteJson(D.inputString)){let R=this.tryParseToolInput(D.inputString,D.name,v);if(!R)continue;if(h.delete(_.index),b++,b>k)break;let q=R.path||R.targetFile||R.file||"GLOBAL",j=["write_to_file","replace_file_content","multi_replace_file_content","run_command","delete_file"].includes(D.name);await this.lockManager.acquireLock(q,j,i,t.getRun().runId);let W=await E({id:D.id,name:D.name,input:R});f.push(W)}}else _.type==="usage"&&(t.getRun().usage=_.usage)}finally{p.cleanup()}for(let[w,_]of h.entries())if(_.name){let M=this.tryParseToolInput(_.inputString,_.name,v);if(M){b++;let D=M.path||M.targetFile||M.file||"GLOBAL",R=["write_to_file","replace_file_content","multi_replace_file_content","run_command","delete_file"].includes(_.name);await this.lockManager.acquireLock(D,R,i,t.getRun().runId);let q=await E({id:_.id,name:_.name,input:M});f.push(q)}}h.clear();let T=o+m;if(console.log(`[MarieEngine] Depth ${n}: Turn content length: ${m.length}. New accumulated length: ${T.length}`),this.contentBuffer.length>0&&(this.contentBuffer=""),await this.lockManager.waitForAll(),b>0){e.push({role:"user",content:f});let w=await this.ascendant.evaluate(e,this.state);return this.state.lastDecree=w,t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:`\u26A1 Protocol Decree: ${w.strategy} @ ${w.confidence.toFixed(2)} \u2014 ${w.reason}`,elapsedMs:t.elapsedMs()}),this.calibrateStrategicTrajectory(w,t),w.strategy==="PANIC"&&(this.state.panicCoolDown=3,e.push({role:"user",content:"\u{1F6A8} SYSTEM PANIC: Instability detected. Re-evaluating ascension trajectory."})),w.strategy==="LIMIT_BREAK"?(t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:"\u26A1 LIMIT BREAK! Bypassing recursive safety seals for peak momentum.",elapsedMs:t.elapsedMs()}),a(t.getRun()).catch(_=>console.error("History Save Error:",_)),await this._executeChatLoop(e,t,a,i,g>0?s+1:0,n,T)):(w.heroicVow&&(t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:`\u{1F5E1}\uFE0F HEROIC VOW: "${w.heroicVow}". Spirit Pressure surging!`,elapsedMs:t.elapsedMs()}),this.state.spiritPressure=Math.min(100,this.state.spiritPressure+20)),w.sacrificeTriggered&&(t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:"\u{1F56F}\uFE0F HEROIC SACRIFICE! Resetting soul for a final, absolute strike.",elapsedMs:t.elapsedMs()}),this.state.spiritPressure=50,w.confidence=3),this.suggestSelfHealing(t,e),a(t.getRun()).catch(_=>console.error("History Save Error:",_)),await this._executeChatLoop(e,t,a,i,g>0?s+1:0,n+1,T))}return t.setObjectiveStatus("execute_plan","completed"),t.setObjectiveStatus("deliver_result","completed"),t.emitEvent({type:"reasoning",runId:t.getRun().runId,text:"\u2728 Convergence achieved. The pattern sparks joy.",elapsedMs:t.elapsedMs()}),d.clear(),T}handleSuccess(e,t,a,i){this.state.victoryStreak++,this.state.totalErrorCount=0,this.state.spiritPressure=Math.min(100,this.state.spiritPressure+10),this.state.techniqueExecutions.push({name:t,durationMs:a,success:!0,timestamp:Date.now(),filePath:i}),this.state.toolHistory.push(t),this.state.victoryStreak%3===0&&e.emitEvent({type:"reasoning",runId:e.getRun().runId,text:`\u2728 Technique Mastery! ${t} executed perfectly. Victory Streak: ${this.state.victoryStreak}.`,elapsedMs:e.elapsedMs()}),i&&!this.state.recentFiles.includes(i)&&(this.state.recentFiles.push(i),this.state.recentFiles.length>10&&this.state.recentFiles.shift(),this.proactiveContextAnchoring(i,e))}handleFailure(e,t,a,i){this.state.victoryStreak=0,this.state.spiritPressure=Math.max(0,this.state.spiritPressure-20),this.state.techniqueExecutions.push({name:t,durationMs:0,success:!1,timestamp:Date.now(),filePath:i});let s=(this.state.errorHotspots[i||"system"]||0)+1;i&&(this.state.errorHotspots[i]=s,this.state.totalErrorCount++,this.state.lastFailedFile=i),e.emitEvent({type:"reasoning",runId:e.getRun().runId,text:`\u26A0\uFE0F Technique Falter! ${t} failed in ${i||"system"}. Resistance: ${s}x. Regrouping...`,elapsedMs:e.elapsedMs()})}updateShakyResponse(){this.state.shakyResponseDensity=Math.min(1,this.state.shakyResponseDensity+.2)}shouldAutoApprove(e,t){if(["read_file","view_file","list_dir","grep_search","search_web","get_file_diagnostics"].includes(e))return!0;let i=this.state.spiritPressure,s=this.state.victoryStreak;return!!(i>70&&s>5||this.state.isAwakened&&s>10||this.state.isSpiritBurstActive&&s>3&&!["delete_file","run_command"].includes(e))}tryParseToolInput(e,t,a){try{return JSON.parse(e)}catch{let i=this.toolMender.repairJsonString(e);try{return JSON.parse(i)}catch{return null}}}isLikelyCompleteJson(e){let t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return!1;let a=0,i=!1;for(let s=0;s<t.length;s++)t[s]==='"'&&t[s-1]!=="\\"&&(i=!i),i||((t[s]==="{"||t[s]==="[")&&a++,(t[s]==="}"||t[s]==="]")&&a--);return a===0&&t.length>=2}suggestSelfHealing(e,t){let a=this.state.spiritPressure,i=Object.entries(this.state.errorHotspots).filter(([s,n])=>n>=2);if(a<40||i.length>0){let s=i.map(([o])=>Ul.default.basename(o)).join(", "),n=a<40?"Low spirit pressure (instability detected)":`Repeated failures in: ${s}`;e.emitEvent({type:"reasoning",runId:e.getRun().runId,text:`\u{1F9EC} HIGH-CONVICTION RECOVERY: ${n}. Marie mandates a systemic audit.`,elapsedMs:e.elapsedMs()}),t.push({role:"user",content:`\u{1F6A8} **MANDATORY RECOVERY PROTOCOL**: Codebase stability has dropped below safety thresholds.
|
|
550
550
|
Reason: ${n}
|
|
@@ -18,15 +18,15 @@ export class MariePulseService {
|
|
|
18
18
|
startTurnWatchdog(onRecover) {
|
|
19
19
|
this.stopTurnWatchdog();
|
|
20
20
|
this.watchdogTimer = setTimeout(() => {
|
|
21
|
-
console.error("[MariePulseService] LOCK RECOVERY: AI Engine lock held for >
|
|
21
|
+
console.error("[MariePulseService] LOCK RECOVERY: AI Engine lock held for >300s. Force-releasing...");
|
|
22
22
|
this.tracker.emitEvent({
|
|
23
23
|
type: "reasoning",
|
|
24
24
|
runId: this.tracker.getRun().runId,
|
|
25
|
-
text: "🚨 LOCK RECOVERY: Stale reasoning process detected (>
|
|
25
|
+
text: "🚨 LOCK RECOVERY: Stale reasoning process detected (>300s). Force-releasing engine lock.",
|
|
26
26
|
elapsedMs: this.tracker.elapsedMs(),
|
|
27
27
|
});
|
|
28
28
|
onRecover();
|
|
29
|
-
},
|
|
29
|
+
}, 300000);
|
|
30
30
|
return this.watchdogTimer;
|
|
31
31
|
}
|
|
32
32
|
stopTurnWatchdog() {
|
|
@@ -44,10 +44,10 @@ export class MariePulseService {
|
|
|
44
44
|
this.tracker.emitEvent({
|
|
45
45
|
type: "reasoning",
|
|
46
46
|
runId: this.tracker.getRun().runId,
|
|
47
|
-
text: "🚨 PLANETARY STABILITY HAZARD: AI reasoning hang detected (>
|
|
47
|
+
text: "🚨 PLANETARY STABILITY HAZARD: AI reasoning hang detected (>120s).",
|
|
48
48
|
elapsedMs: this.tracker.elapsedMs(),
|
|
49
49
|
});
|
|
50
|
-
},
|
|
50
|
+
}, 120000);
|
|
51
51
|
}
|
|
52
52
|
stopHeartbeat() {
|
|
53
53
|
if (this.heartbeatTimer) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MariePulseService.js","sourceRoot":"","sources":["../../../../../src/monolith/infrastructure/ai/core/MariePulseService.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wCAAwC,CAAC;AAE3E;;;;GAIG;AACH,MAAM,OAAO,iBAAiB;IAIR;IAHZ,cAAc,GAA0B,IAAI,CAAC;IAC7C,aAAa,GAA0B,IAAI,CAAC;IAEpD,YAAoB,OAA6B;QAA7B,YAAO,GAAP,OAAO,CAAsB;IAAG,CAAC;IAErD;;;OAGG;IACI,iBAAiB,CAAC,SAAqB;QAC5C,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACxB,IAAI,CAAC,aAAa,GAAG,UAAU,CAAC,GAAG,EAAE;YACnC,OAAO,CAAC,KAAK,CACX,sFAAsF,CACvF,CAAC;YAEF,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;gBACrB,IAAI,EAAE,WAAW;gBACjB,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,KAAK;gBAClC,IAAI,EAAE,0FAA0F;gBAChG,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE;aACpC,CAAC,CAAC;YAEH,SAAS,EAAE,CAAC;QACd,CAAC,EAAE,MAAM,CAAC,CAAC;QACX,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAEM,gBAAgB;QACrB,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACvB,YAAY,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YACjC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC5B,CAAC;IACH,CAAC;IAED;;OAEG;IACI,cAAc;QACnB,IAAI,CAAC,aAAa,EAAE,CAAC;QACrB,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,GAAG,EAAE;YACpC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;gBACrB,IAAI,EAAE,WAAW;gBACjB,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,KAAK;gBAClC,IAAI,EAAE,
|
|
1
|
+
{"version":3,"file":"MariePulseService.js","sourceRoot":"","sources":["../../../../../src/monolith/infrastructure/ai/core/MariePulseService.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wCAAwC,CAAC;AAE3E;;;;GAIG;AACH,MAAM,OAAO,iBAAiB;IAIR;IAHZ,cAAc,GAA0B,IAAI,CAAC;IAC7C,aAAa,GAA0B,IAAI,CAAC;IAEpD,YAAoB,OAA6B;QAA7B,YAAO,GAAP,OAAO,CAAsB;IAAG,CAAC;IAErD;;;OAGG;IACI,iBAAiB,CAAC,SAAqB;QAC5C,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACxB,IAAI,CAAC,aAAa,GAAG,UAAU,CAAC,GAAG,EAAE;YACnC,OAAO,CAAC,KAAK,CACX,sFAAsF,CACvF,CAAC;YAEF,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;gBACrB,IAAI,EAAE,WAAW;gBACjB,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,KAAK;gBAClC,IAAI,EAAE,0FAA0F;gBAChG,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE;aACpC,CAAC,CAAC;YAEH,SAAS,EAAE,CAAC;QACd,CAAC,EAAE,MAAM,CAAC,CAAC;QACX,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAEM,gBAAgB;QACrB,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACvB,YAAY,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YACjC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC5B,CAAC;IACH,CAAC;IAED;;OAEG;IACI,cAAc;QACnB,IAAI,CAAC,aAAa,EAAE,CAAC;QACrB,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,GAAG,EAAE;YACpC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;gBACrB,IAAI,EAAE,WAAW;gBACjB,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,KAAK;gBAClC,IAAI,EAAE,oEAAoE;gBAC1E,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE;aACpC,CAAC,CAAC;QACL,CAAC,EAAE,MAAM,CAAC,CAAC;IACb,CAAC;IAEM,aAAa;QAClB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,YAAY,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;YAClC,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC7B,CAAC;IACH,CAAC;IAED;;OAEG;IACI,OAAO;QACZ,IAAI,CAAC,aAAa,EAAE,CAAC;QACrB,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACxB,iBAAiB,CAAC,QAAQ,EAAE,CAAC;IAC/B,CAAC;CACF"}
|
|
@@ -56,7 +56,7 @@ export class MarieGhostService {
|
|
|
56
56
|
const timeout = setTimeout(() => {
|
|
57
57
|
activeEditor.setDecorations(this.thoughtDecoration, []);
|
|
58
58
|
this.thoughtTimeouts.delete(timeoutKey);
|
|
59
|
-
},
|
|
59
|
+
}, 2000);
|
|
60
60
|
this.thoughtTimeouts.set(timeoutKey, timeout);
|
|
61
61
|
}
|
|
62
62
|
static pendingDeltas = new Map();
|
|
@@ -75,7 +75,7 @@ export class MarieGhostService {
|
|
|
75
75
|
this.pendingDeltas.set(toolCallId, current + delta);
|
|
76
76
|
// Schedule flush if not already pending
|
|
77
77
|
if (!this.updateTimer) {
|
|
78
|
-
this.updateTimer = setTimeout(() => this.flushUpdates(),
|
|
78
|
+
this.updateTimer = setTimeout(() => this.flushUpdates(), 20);
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
81
|
static flushUpdates() {
|
package/package.json
CHANGED