agent-afk 0.1.0 → 0.2.1

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/telegram.mjs CHANGED
@@ -1,33 +1,33 @@
1
1
  #!/usr/bin/env node
2
- import{Telegraf as so}from"telegraf";import{promises as me}from"fs";import{join as Dt}from"path";var Ee=class{sessions=new Map;sessionData=new Map;options;constructor(e){this.options={dataDir:e.dataDir||"./data/telegram-sessions",defaultModel:e.defaultModel||"sonnet",apiKey:e.apiKey,settingSources:e.settingSources,thinking:e.thinking,effort:e.effort,createSession:e.createSession}}getSessionIfExists(e){return this.sessions.get(e)}async getSession(e){let n=this.sessions.get(e);if(!n){let o=this.sessionData.get(e)||{chatId:e,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},s={model:o.model,apiKey:this.options.apiKey};this.options.settingSources?.length&&(s.settingSources=this.options.settingSources),this.options.thinking!==void 0&&(s.thinking=this.options.thinking),this.options.effort!==void 0&&(s.effort=this.options.effort),n=await this.options.createSession(s),this.sessions.set(e,n),this.sessionData.set(e,o)}let r=this.sessionData.get(e);return r&&(r.lastActivity=new Date().toISOString()),n}async resetSession(e){let n=this.sessions.get(e);n&&(await n.close(),this.sessions.delete(e));let r=this.sessionData.get(e);r&&(r.lastActivity=new Date().toISOString())}async switchModel(e,n){let r=this.sessions.get(e);r&&(await r.close(),this.sessions.delete(e));let o=this.sessionData.get(e);o?(o.model=n,o.lastActivity=new Date().toISOString()):(o={chatId:e,model:n,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},this.sessionData.set(e,o))}getModel(e){return this.sessionData.get(e)?.model||this.options.defaultModel}async loadSessions(){try{await me.mkdir(this.options.dataDir,{recursive:!0});let e=await me.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=Dt(this.options.dataDir,n),o=await me.readFile(r,"utf-8"),s=JSON.parse(o);this.sessionData.set(s.chatId,s)}}catch(e){e.code!=="ENOENT"&&console.error("Failed to load sessions:",e)}}async saveSessions(){try{await me.mkdir(this.options.dataDir,{recursive:!0});for(let[e,n]of this.sessionData.entries()){let r=Dt(this.options.dataDir,`${e}.json`);await me.writeFile(r,JSON.stringify(n,null,2))}}catch(e){console.error("Failed to save sessions:",e)}}async closeAll(){await this.saveSessions();let e=Array.from(this.sessions.values()).map(n=>n.close().catch(r=>console.error("Error closing session:",r)));await Promise.all(e),this.sessions.clear()}getSessionCount(){return this.sessions.size}getChatCount(){return this.sessionData.size}};function Ae(t,e=4096){if(t.length<=e)return[t];let n=[],r=t;for(;r.length>0;){if(r.length<=e){n.push(r);break}let o=e,s=r.lastIndexOf(`
3
- `,e);if(s>e-500&&s>0)o=s+1;else{let i=r.slice(0,e).match(/[.!?]\s+(?=[A-Z])/g);if(i&&i.length>0){let a=i[i.length-1];if(a){let l=r.lastIndexOf(a,e);l>e-200&&l>0&&(o=l+2)}}else{let a=r.lastIndexOf(" ",e);a>e-100&&a>0&&(o=a+1)}}n.push(r.slice(0,o).trim()),r=r.slice(o).trim()}return n}function et(t){let e=t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return e=e.replace(/^```[\w]*\n?([\s\S]*?)```/gm,"<pre>$1</pre>"),e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>"),e=e.replace(/__([^_]+)__/g,"<b>$1</b>"),e=e.replace(/\*([^*]+)\*/g,"<i>$1</i>"),e=e.replace(/_([^_]+)_/g,"<i>$1</i>"),e=e.replace(/~~([^~]+)~~/g,"<s>$1</s>"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,o)=>'<a href="'+o.replace(/&/g,"&amp;").replace(/"/g,"&quot;")+'">'+r+"</a>"),e=e.replace(/^#{1,6}\s+/gm,""),e}function O(t){return`\u274C Error: ${t instanceof Error?t.message:t}`}var Ot=[{cmd:"/start",desc:"Show welcome and this command list"},{cmd:"/help",desc:"Show this command list"},{cmd:"/clear",desc:"Clear conversation history (SDK /clear)"},{cmd:"/compact",desc:"Compact conversation history (summarize older messages)"},{cmd:"/model [opus|sonnet|haiku]",desc:"Switch Claude model"}];function Ft(t){let e=["\u{1F4CB} Bot commands (aligned with agent-afk CLI):","",...Ot.map(n=>` ${n.cmd}
2
+ import{Telegraf as ao}from"telegraf";import{promises as he}from"fs";import{join as Ft}from"path";var Te=class{sessions=new Map;sessionData=new Map;options;constructor(e){this.options={dataDir:e.dataDir||"./data/telegram-sessions",defaultModel:e.defaultModel||"sonnet",apiKey:e.apiKey,settingSources:e.settingSources,thinking:e.thinking,effort:e.effort,createSession:e.createSession}}getSessionIfExists(e){return this.sessions.get(e)}async getSession(e){let n=this.sessions.get(e);if(!n){let o=this.sessionData.get(e)||{chatId:e,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},s={model:o.model,apiKey:this.options.apiKey};this.options.settingSources?.length&&(s.settingSources=this.options.settingSources),this.options.thinking!==void 0&&(s.thinking=this.options.thinking),this.options.effort!==void 0&&(s.effort=this.options.effort),n=await this.options.createSession(s),this.sessions.set(e,n),this.sessionData.set(e,o)}let r=this.sessionData.get(e);return r&&(r.lastActivity=new Date().toISOString()),n}async resetSession(e){let n=this.sessions.get(e);n&&(await n.close(),this.sessions.delete(e));let r=this.sessionData.get(e);r&&(r.lastActivity=new Date().toISOString())}async switchModel(e,n){let r=this.sessions.get(e);r&&(await r.close(),this.sessions.delete(e));let o=this.sessionData.get(e);o?(o.model=n,o.lastActivity=new Date().toISOString()):(o={chatId:e,model:n,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()},this.sessionData.set(e,o))}getModel(e){return this.sessionData.get(e)?.model||this.options.defaultModel}async loadSessions(){try{await he.mkdir(this.options.dataDir,{recursive:!0});let e=await he.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=Ft(this.options.dataDir,n),o=await he.readFile(r,"utf-8"),s=JSON.parse(o);this.sessionData.set(s.chatId,s)}}catch(e){e.code!=="ENOENT"&&console.error("Failed to load sessions:",e)}}async saveSessions(){try{await he.mkdir(this.options.dataDir,{recursive:!0});for(let[e,n]of this.sessionData.entries()){let r=Ft(this.options.dataDir,`${e}.json`);await he.writeFile(r,JSON.stringify(n,null,2))}}catch(e){console.error("Failed to save sessions:",e)}}async closeAll(){await this.saveSessions();let e=Array.from(this.sessions.values()).map(n=>n.close().catch(r=>console.error("Error closing session:",r)));await Promise.all(e),this.sessions.clear()}getSessionCount(){return this.sessions.size}getChatCount(){return this.sessionData.size}};function Ie(t,e=4096){if(t.length<=e)return[t];let n=[],r=t;for(;r.length>0;){if(r.length<=e){n.push(r);break}let o=e,s=r.lastIndexOf(`
3
+ `,e);if(s>e-500&&s>0)o=s+1;else{let i=r.slice(0,e).match(/[.!?]\s+(?=[A-Z])/g);if(i&&i.length>0){let a=i[i.length-1];if(a){let l=r.lastIndexOf(a,e);l>e-200&&l>0&&(o=l+2)}}else{let a=r.lastIndexOf(" ",e);a>e-100&&a>0&&(o=a+1)}}n.push(r.slice(0,o).trim()),r=r.slice(o).trim()}return n}function nt(t){let e=t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return e=e.replace(/^```[\w]*\n?([\s\S]*?)```/gm,"<pre>$1</pre>"),e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>"),e=e.replace(/__([^_]+)__/g,"<b>$1</b>"),e=e.replace(/\*([^*]+)\*/g,"<i>$1</i>"),e=e.replace(/_([^_]+)_/g,"<i>$1</i>"),e=e.replace(/~~([^~]+)~~/g,"<s>$1</s>"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,o)=>'<a href="'+o.replace(/&/g,"&amp;").replace(/"/g,"&quot;")+'">'+r+"</a>"),e=e.replace(/^#{1,6}\s+/gm,""),e}function O(t){return`\u274C Error: ${t instanceof Error?t.message:t}`}var $t=[{cmd:"/start",desc:"Show welcome and this command list"},{cmd:"/help",desc:"Show this command list"},{cmd:"/clear",desc:"Clear conversation history (SDK /clear)"},{cmd:"/compact",desc:"Compact conversation history (summarize older messages)"},{cmd:"/model [opus|sonnet|haiku]",desc:"Switch Claude model"}];function Lt(t){let e=["\u{1F4CB} Bot commands (aligned with agent-afk CLI):","",...$t.map(n=>` ${n.cmd}
4
4
  ${n.desc}`)];return t&&t.length>0&&e.push("","\u{1F4CB} Session commands (from SDK, when using settingSources):","",...t.map(n=>` /${n.replace(/^\//,"")}`)),e.push("","Just send a message to chat with Claude."),e.join(`
5
- `)}function $t(){return`\u{1F44B} Welcome to Agent AFK Bot!
5
+ `)}function jt(){return`\u{1F44B} Welcome to Agent AFK Bot!
6
6
 
7
7
  I'm powered by Claude and can help you with various tasks.
8
8
 
9
9
  Available commands:
10
- ${Ot.map(e=>`${e.cmd} - ${e.desc}`).join(`
10
+ ${$t.map(e=>`${e.cmd} - ${e.desc}`).join(`
11
11
  `)}
12
12
 
13
- Just send me a message to get started!`}function Lt(t){return`${{opus:"\u{1F680}",sonnet:"\u26A1",haiku:"\u{1F338}"}[t]||"\u{1F916}"} Switched to Claude ${t.toUpperCase()}`}function Te(){return"\u{1F504} Conversation history cleared!"}function jt(t){if(!t)return"\u{1F4E6} Conversation compacted (older messages summarized).";let e=t.tokensSavedEstimate!==void 0&&t.tokensSavedEstimate>0?` (~${to(t.tokensSavedEstimate)} input tokens saved)`:"";return`\u{1F4E6} Compacted ${t.before} \u2192 ${t.after} messages${e}.`}function Ht(t){return t==="aborted"?"\u{1F4E6} Compaction cancelled.":t.startsWith("summarization-failed")?`\u26A0\uFE0F Compaction failed: ${t}. History unchanged.`:`\u{1F4E6} Nothing to compact (${t}).`}function to(t){return t>=1e3?`${Math.round(t/100)/10}k`:String(t)}async function tt(t){await t.reply($t())}async function nt(t,e){let n=t.chat?.id,r,o=n?e.getSessionIfExists(n):void 0;if(o)try{await Promise.race([o.waitForInitialization(),new Promise((i,a)=>setTimeout(()=>a(new Error("timeout")),2e3))]);let s=o.getSessionMetadata();s.slashCommands?.length&&(r=s.slashCommands)}catch{}await t.reply(Ft(r))}async function rt(t,e,n,r){let o=t.chat?.id;if(!o){await t.reply(O("Could not identify chat"));return}try{await e.resetSession(o),n.delete(o),await t.reply(Te())}catch(s){r("Clear error:",s),await t.reply(O(s))}}async function Ut(t,e,n){let r=t.chat?.id;if(!r){await t.reply(O("Could not identify chat"));return}try{let o=await e.getSession(r);await t.sendChatAction("typing").catch(()=>{});let s=await o.compact();s.compacted?await t.reply(jt({before:s.messagesBefore,after:s.messagesAfter,...s.tokensSavedEstimate!==void 0?{tokensSavedEstimate:s.tokensSavedEstimate}:{}})):await t.reply(Ht(s.reason??"unknown"))}catch(o){n("Compact error:",o),await t.reply(O(o))}}async function ot(t,e,n){let r=t.chat?.id;if(!r){await t.reply(O("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1);if(s.length===0){let c=e.getModel(r);await t.reply(`Current model: ${c.toUpperCase()}
13
+ Just send me a message to get started!`}function Ht(t){return`${{opus:"\u{1F680}",sonnet:"\u26A1",haiku:"\u{1F338}"}[t]||"\u{1F916}"} Switched to Claude ${t.toUpperCase()}`}function Ce(){return"\u{1F504} Conversation history cleared!"}function Ut(t){if(!t)return"\u{1F4E6} Conversation compacted (older messages summarized).";let e=t.tokensSavedEstimate!==void 0&&t.tokensSavedEstimate>0?` (~${ro(t.tokensSavedEstimate)} input tokens saved)`:"";return`\u{1F4E6} Compacted ${t.before} \u2192 ${t.after} messages${e}.`}function Nt(t){return t==="aborted"?"\u{1F4E6} Compaction cancelled.":t.startsWith("summarization-failed")?`\u26A0\uFE0F Compaction failed: ${t}. History unchanged.`:`\u{1F4E6} Nothing to compact (${t}).`}function ro(t){return t>=1e3?`${Math.round(t/100)/10}k`:String(t)}async function rt(t){await t.reply(jt())}async function ot(t,e){let n=t.chat?.id,r,o=n?e.getSessionIfExists(n):void 0;if(o)try{await Promise.race([o.waitForInitialization(),new Promise((i,a)=>setTimeout(()=>a(new Error("timeout")),2e3))]);let s=o.getSessionMetadata();s.slashCommands?.length&&(r=s.slashCommands)}catch{}await t.reply(Lt(r))}async function st(t,e,n,r){let o=t.chat?.id;if(!o){await t.reply(O("Could not identify chat"));return}try{await e.resetSession(o),n.delete(o),await t.reply(Ce())}catch(s){r("Clear error:",s),await t.reply(O(s))}}async function Bt(t,e,n){let r=t.chat?.id;if(!r){await t.reply(O("Could not identify chat"));return}try{let o=await e.getSession(r);await t.sendChatAction("typing").catch(()=>{});let s=await o.compact();s.compacted?await t.reply(Ut({before:s.messagesBefore,after:s.messagesAfter,...s.tokensSavedEstimate!==void 0?{tokensSavedEstimate:s.tokensSavedEstimate}:{}})):await t.reply(Nt(s.reason??"unknown"))}catch(o){n("Compact error:",o),await t.reply(O(o))}}async function it(t,e,n){let r=t.chat?.id;if(!r){await t.reply(O("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1);if(s.length===0){let c=e.getModel(r);await t.reply(`Current model: ${c.toUpperCase()}
14
14
 
15
15
  Usage: /model [opus|sonnet|haiku]`);return}let i=s[0];if(!i){await t.reply(O("Please specify a model: opus, sonnet, or haiku"));return}let a=i.toLowerCase();if(!["opus","sonnet","haiku"].includes(a)){await t.reply(O(`Invalid model: ${i}
16
- Valid options: opus, sonnet, haiku`));return}try{await e.switchModel(r,a),await t.reply(Lt(a))}catch(c){n("Model switch error:",c),await t.reply(O(c))}}function st(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("rate limit")||e.toLowerCase().includes("too many requests")}function it(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("network")||e.toLowerCase().includes("connect")||e.toLowerCase().includes("timeout")}var no=300,ro=9e4,oo=6e4;async function Nt(t,e,n,r){let o="",s=null,i=0,a=async(l,c=!1)=>{let d=et(l||"\u2026"),u=Date.now();if(!s){let f=Ae(d);s=await t.reply(f[0]??"\u2026",{parse_mode:"HTML"});return}if(!c&&u-i<no&&l.length<100)return;i=u;let p=Ae(d);try{await t.telegram.editMessageText(t.chat?.id,s.message_id,void 0,p[0]??d,{parse_mode:"HTML"})}catch{}};try{let l="sendMessageStream"in e&&typeof e.sendMessageStream=="function"?e.sendMessageStream(n):(async function*(){let f=await e.sendMessage(n,{stream:!1});yield{type:"message",message:f},yield{type:"done",metadata:f.metadata}})();await a("Thinking\u2026");let c=l[Symbol.asyncIterator](),d=!1,u=null,p=()=>{let f=d?oo:ro;return new Promise((g,h)=>{u=setTimeout(()=>{u=null,h(new Error(d?"Response timed out. Try sending a shorter message or try again.":"Request timed out. The agent may still be starting (first message can take a minute). Try again in a moment."))},f),c.next().then(m=>{u!=null&&(clearTimeout(u),u=null),g(m)},m=>{u!=null&&(clearTimeout(u),u=null),h(m)})})};for(;;){let f=await p();if(f.done)break;let g=f.value;if(d||(d=!0,console.log("\u{1F4E1} First stream event received:",g.type),r?.("First stream event received:",g.type)),g.type==="chunk"&&g.chunk.type==="content"&&(o+=g.chunk.content,await a(o)),g.type==="message"&&g.message.role==="assistant"&&(o=g.message.content,await a(o)),g.type==="progress"){let{description:h,summary:m,lastToolName:b}=g.progress,S=b?`
16
+ Valid options: opus, sonnet, haiku`));return}try{await e.switchModel(r,a),await t.reply(Ht(a))}catch(c){n("Model switch error:",c),await t.reply(O(c))}}function at(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("rate limit")||e.toLowerCase().includes("too many requests")}function lt(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("network")||e.toLowerCase().includes("connect")||e.toLowerCase().includes("timeout")}var oo=300,so=9e4,io=6e4;async function Kt(t,e,n,r){let o="",s=null,i=0,a=async(l,c=!1)=>{let d=nt(l||"\u2026"),u=Date.now();if(!s){let f=Ie(d);s=await t.reply(f[0]??"\u2026",{parse_mode:"HTML"});return}if(!c&&u-i<oo&&l.length<100)return;i=u;let p=Ie(d);try{await t.telegram.editMessageText(t.chat?.id,s.message_id,void 0,p[0]??d,{parse_mode:"HTML"})}catch{}};try{let l="sendMessageStream"in e&&typeof e.sendMessageStream=="function"?e.sendMessageStream(n):(async function*(){let f=await e.sendMessage(n,{stream:!1});yield{type:"message",message:f},yield{type:"done",metadata:f.metadata}})();await a("Thinking\u2026");let c=l[Symbol.asyncIterator](),d=!1,u=null,p=()=>{let f=d?io:so;return new Promise((g,h)=>{u=setTimeout(()=>{u=null,h(new Error(d?"Response timed out. Try sending a shorter message or try again.":"Request timed out. The agent may still be starting (first message can take a minute). Try again in a moment."))},f),c.next().then(m=>{u!=null&&(clearTimeout(u),u=null),g(m)},m=>{u!=null&&(clearTimeout(u),u=null),h(m)})})};for(;;){let f=await p();if(f.done)break;let g=f.value;if(d||(d=!0,console.log("\u{1F4E1} First stream event received:",g.type),r?.("First stream event received:",g.type)),g.type==="chunk"&&g.chunk.type==="content"&&(o+=g.chunk.content,await a(o)),g.type==="message"&&g.message.role==="assistant"&&(o=g.message.content,await a(o)),g.type==="progress"){let{description:h,summary:m,lastToolName:b}=g.progress,v=b?`
17
17
  \u25E6 ${h} (${b})`:`
18
- \u25E6 ${h}`;o+=S,m&&(o+=`
18
+ \u25E6 ${h}`;o+=v,m&&(o+=`
19
19
  ${m}`),await a(o)}if(g.type==="suggestion"&&(o+=`
20
20
 
21
- \u{1F4A1} ${g.suggestion}`,await a(o)),g.type==="done"){o.trim()&&await a(o,!0);break}if(g.type==="error")throw g.error}if(o&&s){let f=Ae(et(o));if(f.length>1)for(let g=1;g<f.length;g++){let h=f[g];h&&await t.reply(h,{parse_mode:"HTML"})}}}catch(l){throw r?.("Streaming error:",l),l}}async function Bt(t,e,n,r,o){if(!r.has(e))try{await Promise.race([n.waitForInitialization(),new Promise((a,l)=>setTimeout(()=>l(new Error("timeout")),5e3))]);let s=n.getSessionMetadata(),i=[{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"}];if(s.slashCommands?.length)for(let a of s.slashCommands){let l=a.replace(/^\//,"");i.push({command:l,description:`SDK command: ${l}`})}if(s.skills?.length)for(let a of s.skills)i.push({command:a,description:`Run ${a} skill`});await t.telegram.setMyCommands(i,{scope:{type:"chat",chat_id:e}}),r.add(e),o(`Registered ${i.length} commands for chat ${e}`)}catch(s){o(`Could not register dynamic commands for chat ${e}:`,s)}}var Ie=class{sessionManager;messageQueues=new Map;registeredCommandChats;log;bot;constructor(e,n,r,o){this.bot=e,this.sessionManager=n,this.registeredCommandChats=r,this.log=o}async handle(e){let n=e.chat?.id,r=e.message.text;if(!(!n||!r)&&(console.log(`\u{1F4EC} Message from chat ID: ${n}`),!r.startsWith("/")))try{let o=await this.sessionManager.getSession(n);if(Bt(this.bot,n,o,this.registeredCommandChats,this.log).catch(s=>this.log("Failed to register chat commands:",s)),o.state!=="idle"){this.enqueueMessage(n,e,r),await e.reply("Message queued.");return}await this.processOne(n,e,r)}catch(o){console.error("\u274C Message handling error:",o),this.log("Message handling error:",o);let s=o;if((s?.message??"").includes("session is busy")){this.enqueueMessage(n,e,r),await e.reply("Message queued.");return}st(o)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):it(o)?await e.reply("\u{1F310} Network error. Please check your connection and try again."):await e.reply(O(s))}}async processClearDirect(e,n){try{await this.sessionManager.resetSession(e),this.registeredCommandChats.delete(e),await n.reply(Te())}catch(r){this.log("Clear error:",r),await n.reply(O(r))}}enqueueMessage(e,n,r){let o=this.messageQueues.get(e);o||(o=[],this.messageQueues.set(e,o)),o.push({type:"message",ctx:n,text:r})}enqueueClear(e,n){let r=this.messageQueues.get(e);r||(r=[],this.messageQueues.set(e,r)),r.push({type:"clear",ctx:n})}async processOne(e,n,r){try{let o=await this.sessionManager.getSession(e);await n.sendChatAction("typing").catch(()=>{}),await Nt(n,o,r,this.log)}catch(o){console.error("\u274C Message handling error:",o),this.log("Message handling error:",o);let s=o;st(o)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):it(o)?await n.reply("\u{1F310} Network error. Please check your connection and try again."):await n.reply(O(s))}finally{this.drainQueue(e)}}async drainQueue(e){let n=this.messageQueues.get(e);if(!n?.length)return;let r=n.shift();r.type==="message"?await this.processOne(e,r.ctx,r.text):await this.processClearDirect(e,r.ctx)}};function Kt(t,e=()=>{}){let n=new Set;if(!t)return n;for(let r of t.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){e("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}function Gt(t,e=()=>{}){return async(n,r)=>{let o=n.chat?.id;if(o===void 0||!t.has(o)){e("[allowlist] Rejecting update from chat:",o??"<unknown>");return}await r()}}var Ce=class{bot;sessionManager;options;running=!1;registeredCommandChats=new Set;messageHandler;constructor(e){this.options=e,this.bot=new so(e.botToken),this.sessionManager=new Ee(e),this.messageHandler=new Ie(this.bot,this.sessionManager,this.registeredCommandChats,this.log.bind(this)),this.setupHandlers()}setupHandlers(){this.bot.use(Gt(this.options.allowedChatIds,this.log.bind(this))),this.bot.command("start",e=>tt(e)),this.bot.command("help",e=>nt(e,this.sessionManager)),this.bot.command("clear",async e=>{let n=e.chat?.id;if(!n){await e.reply(O("Could not identify chat"));return}(await this.sessionManager.getSession(n)).state!=="idle"?(this.messageHandler.enqueueClear(n,e),await e.reply("Clear queued.")):await rt(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}),this.bot.command("compact",e=>Ut(e,this.sessionManager,this.log.bind(this))),this.bot.command("model",e=>ot(e,this.sessionManager,this.log.bind(this))),this.bot.on("text",e=>this.messageHandler.handle(e)),this.bot.catch((e,n)=>{this.log("Bot error:",e),n.reply(O("An unexpected error occurred. Please try again.")).catch(r=>this.log("Failed to send error message:",r))})}async start(){if(this.running)throw new Error("Bot is already running");this.log("Loading sessions..."),await this.sessionManager.loadSessions(),this.log("Starting bot..."),await this.bot.launch(),this.log("Registering bot commands..."),await this.bot.telegram.setMyCommands([{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"}]),this.running=!0,this.log("Bot started successfully");let e=async n=>{this.log(`Received ${n}, shutting down...`),await this.stop(),process.exit(0)};process.once("SIGINT",()=>e("SIGINT")),process.once("SIGTERM",()=>e("SIGTERM"))}async stop(){if(this.running){this.log("Stopping bot..."),this.running=!1,this.log("Closing sessions..."),await this.sessionManager.closeAll(),this.log("Stopping bot polling...");try{this.bot.stop()}catch(e){this.log("Error stopping bot (may not have been started):",e)}this.log("Bot stopped")}}getStats(){return{running:this.running,activeSessions:this.sessionManager.getSessionCount(),totalChats:this.sessionManager.getChatCount()}}async handleStart(e){return tt(e)}async handleHelp(e){return nt(e,this.sessionManager)}async handleClear(e){let n=e.chat?.id;if(!n){await e.reply(O("Could not identify chat"));return}if((await this.sessionManager.getSession(n)).state!=="idle")this.messageHandler.enqueueClear(n,e),await e.reply("Clear queued.");else return rt(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}async handleMessage(e){return this.messageHandler.handle(e)}async handleModelSwitch(e){return ot(e,this.sessionManager,this.log.bind(this))}log(...e){this.options.verbose&&console.log("[TelegramBot]",...e)}};function io(){return process.env.AFK_DEBUG==="1"||process.env.DEBUG==="1"}function A(...t){io()&&console.log(...t)}var G=class extends Error{constructor(e){super(e),this.name="AbortError"}},Me=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},U=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause)}event;reason;cause};var ge=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field};var _e=class{queue=[];waiters=[];closed=!1;error=null;push(e){if(this.closed)throw new Error("Cannot push to closed queue");if(process.env.AFK_CODEX_DEBUG&&console.log("[queue] push:",e.type),A("\u{1F4E6} MessageQueue.push: event type=",e.type,"waiters=",this.waiters.length,"queue size=",this.queue.length),this.waiters.length>0){let n=this.waiters.shift();A("\u{1F4E6} MessageQueue.push: Resolving waiter immediately"),n?.({value:e,done:!1})}else this.queue.push(e),A("\u{1F4E6} MessageQueue.push: Added to queue, new size=",this.queue.length)}complete(){for(this.closed=!0;this.waiters.length>0;)this.waiters.shift()?.({value:void 0,done:!0})}fail(e){this.error=e,this.closed=!0;let n={type:"error",error:e};if(this.waiters.length>0)for(this.waiters.shift()?.({value:n,done:!1});this.waiters.length>0;)this.waiters.shift()?.({value:void 0,done:!0});else this.queue.push(n)}isClosed(){return this.closed}hasError(){return this.error}size(){return this.queue.length}async*[Symbol.asyncIterator](){for(A("\u{1F4E6} MessageQueue: Iterator started");;){if(this.queue.length>0){let n=this.queue.shift();if(A("\u{1F4E6} MessageQueue: Yielding queued event, type=",n?.type),n&&(yield n,n.type==="error")){A("\u{1F4E6} MessageQueue: Stopping after error");return}continue}if(this.closed){A("\u{1F4E6} MessageQueue: Closed and empty, stopping");return}A("\u{1F4E6} MessageQueue: Waiting for next event...");let e=await new Promise(n=>{this.waiters.push(n)});if(A("\u{1F4E6} MessageQueue: Got result, done=",e.done,"type=",e.value?.type),e.done)return;if(yield e.value,e.value.type==="error"){A("\u{1F4E6} MessageQueue: Stopping after error");return}}}};import ra from"@anthropic-ai/sdk";var ao="claude-code-20250219,oauth-2025-04-20",lo="claude-cli/1.0.0 (external, cli)",co="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function zt(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Vt(t,e){return e==="oauth"?{authToken:t}:{apiKey:t}}function at(t,e,n){return t!=="oauth"?{}:{"anthropic-beta":ao,"x-app":"cli","User-Agent":lo,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function qt(t){return t!=="oauth"?null:[{type:"text",text:co}]}import{randomUUID as Et}from"node:crypto";function Re(){let t=process.env.AFK_DISABLE_PROMPT_CACHE;if(t===void 0||t.length===0)return!0;let e=t.toLowerCase();return!(e==="1"||e==="true"||e==="yes"||e==="on")}function De(){let t=process.env.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":"1h"}function Wt(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Jt(n,e);return r===n?t:[...t.slice(0,-1),r]}function Yt(t,e){if(t.length===0)return t;let n=t[t.length-1],r=uo(n,e);return r===n?t:[...t.slice(0,-1),r]}function uo(t,e){let n=t.content;if(typeof n=="string")return n.length===0?t:{...t,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:e}}]};if(!Array.isArray(n)||n.length===0)return t;let r=n[n.length-1],o=Jt(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function Jt(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}import{randomUUID as mo}from"node:crypto";function Qt(t,e){if(!t)return{stopReason:e??null};let n={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null};return t.cache_read_input_tokens!=null&&(n.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(n.cacheCreationTokens=t.cache_creation_input_tokens),n.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n}function Xt(t,e){let n=(c,d)=>{if(!(c==null&&d==null))return(c??0)+(d??0)},r={stopReason:e.stopReason??t.stopReason??null},o=n(t.inputTokens,e.inputTokens);o!==void 0&&(r.inputTokens=o);let s=n(t.outputTokens,e.outputTokens);s!==void 0&&(r.outputTokens=s);let i=n(t.cachedInputTokens,e.cachedInputTokens);i!==void 0&&(r.cachedInputTokens=i);let a=n(t.cacheCreationTokens,e.cacheCreationTokens);a!==void 0&&(r.cacheCreationTokens=a);let l=n(t.totalTokens,e.totalTokens);return l!==void 0&&(r.totalTokens=l),r}function po(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function fo(t,e,n){let r=[],o=[];for(let a of t)a&&(a.kind==="text"?(r.push({type:"text",text:a.text}),o.push(a.text)):a.kind==="thinking"?r.push({type:"thinking",thinking:a.thinking,signature:a.signature}):r.push({type:"tool_use",id:a.id,name:a.name,input:po(a.partialJson)}));let s=a=>a.type==="tool_use",i=r.filter(s);return{stopReason:e,assistantBlocks:r,toolUseBlocks:i,usage:n,text:o.join("")}}async function*Zt(t,e){let n=[],r=null,o=null,s=!1;try{for await(let i of t){switch(i.type){case"message_start":{let a=i.message?.usage;a&&(o={...a});break}case"content_block_start":{let a=i.content_block;a.type==="text"?n[i.index]={kind:"text",text:""}:a.type==="thinking"?n[i.index]={kind:"thinking",thinking:"",signature:""}:a.type==="tool_use"&&(n[i.index]={kind:"tool_use",id:a.id,name:a.name,partialJson:""});break}case"content_block_delta":{let a=n[i.index],l=i.delta;l.type==="text_delta"?(a&&a.kind==="text"&&(a.text+=l.text),yield{kind:"event",event:{type:"delta.text",text:l.text,sessionId:e.sessionId}}):l.type==="input_json_delta"?a&&a.kind==="tool_use"&&(a.partialJson+=l.partial_json):l.type==="thinking_delta"?(a&&a.kind==="thinking"&&(a.thinking+=l.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:l.thinking,sessionId:e.sessionId}}):l.type==="signature_delta"&&a&&a.kind==="thinking"&&(a.signature=l.signature);break}case"content_block_stop":{let a=n[i.index];a&&a.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:a.name,toolUseIds:[a.id],sessionId:e.sessionId}});break}case"message_delta":{i.delta&&i.delta.stop_reason!==void 0&&(r=i.delta.stop_reason);let a=i.usage;a&&(o!==null?(o.output_tokens=a.output_tokens,a.cache_creation_input_tokens!=null&&(o.cache_creation_input_tokens=a.cache_creation_input_tokens),a.cache_read_input_tokens!=null&&(o.cache_read_input_tokens=a.cache_read_input_tokens),a.input_tokens!=null&&(o.input_tokens=a.input_tokens)):o={cache_creation:null,cache_creation_input_tokens:a.cache_creation_input_tokens??null,cache_read_input_tokens:a.cache_read_input_tokens??null,inference_geo:null,input_tokens:a.input_tokens??0,output_tokens:a.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{s=!0;break}default:break}if(s)break}}catch(i){yield{kind:"event",event:{type:"error",error:i instanceof Error?i:new Error(String(i))}};return}yield{kind:"turn-result",result:fo(n,r,o)}}var go=0;function ho(t){if(!t||typeof t!="object")return"";let e=t,n=e.file_path??e.path??e.filePath;if(typeof n=="string")return" "+n;let r=e.command??e.cmd;if(typeof r=="string"){let s=r.split(`
22
- `)[0];return" "+(s.length>80?s.slice(0,77)+"\u2026":s)}let o=e.query??e.pattern??e.url??e.description;return typeof o=="string"?" "+o:""}async function*en(t){let e=t.maxToolUseIterations??go,n={stopReason:null},r=0,o=mo(),s=Date.now();for(;;){if(t.signal.aborted)return;let i=Re()?Yt(t.messages,De()):t.messages,a={model:t.model,max_tokens:t.maxTokens,messages:i,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools}:{}},l;try{l=await Promise.resolve(t.client.messages.create(a,{headers:t.headers,signal:t.signal}))}catch(m){if(t.signal.aborted)return;yield{type:"error",error:m instanceof Error?m:new Error(String(m))};return}let c=null,d=!1;try{for await(let m of Zt(l,t.ctx))if(m.kind==="event"){if(m.event.type==="error"){yield m.event,d=!0;break}yield m.event}else{c=m.result;break}}catch(m){if(t.signal.aborted)return;yield{type:"error",error:m instanceof Error?m:new Error(String(m))};return}if(d)return;if(c===null){yield{type:"turn.completed",usage:n,sessionId:t.ctx.sessionId};return}if(n=Xt(n,Qt(c.usage,c.stopReason)),c.stopReason!=="tool_use"){c.text.length>0&&(yield{type:"assistant.message",text:c.text,sessionId:t.ctx.sessionId},c.text.length<=200&&(yield{type:"suggestion",suggestion:c.text,sessionId:t.ctx.sessionId})),yield{type:"turn.completed",usage:n,sessionId:t.ctx.sessionId};return}t.messages.push({role:"assistant",content:c.assistantBlocks});let u=[];for(let m of c.toolUseBlocks)u.push({id:m.id,name:m.name,input:m.input,signal:t.signal}),yield{type:"tool.use.start",toolUseId:m.id,toolName:m.name,toolInput:ho(m.input),sessionId:t.ctx.sessionId};if(t.signal.aborted)return;let p;if(t.toolDispatcher.executeBatch)p=await t.toolDispatcher.executeBatch(u);else{p=[];for(let m of u){if(t.signal.aborted){p.push({content:"Tool call aborted",isError:!0});continue}try{p.push(await t.toolDispatcher.execute(m))}catch(b){let S=b instanceof Error?b.message:String(b);p.push({content:`Tool execution threw: ${S}`,isError:!0})}}}let f=[];for(let m=0;m<u.length;m++){let b=u[m],S=p[m];yield{type:"tool.output",toolUseId:b.id,content:S.content,...S.isError===!0?{isError:!0}:{},sessionId:t.ctx.sessionId},f.push({type:"tool_result",tool_use_id:b.id,content:S.content,...S.isError===!0?{is_error:!0}:{}})}let g={role:"user",content:f};t.messages.push(g),r+=1;let h=c.toolUseBlocks[c.toolUseBlocks.length-1];if(yield{type:"progress",progress:{taskId:o,description:"Tool-use loop",summary:`Iteration ${r}: used ${h?.name??"unknown"}`,lastToolName:h?.name,totalTokens:n.totalTokens??0,toolUses:r,durationMs:Date.now()-s},sessionId:t.ctx.sessionId},e>0&&r>=e){yield{type:"turn.completed",usage:{...n,stopReason:"tool_use_loop_capped"},sessionId:t.ctx.sessionId};return}}}var yo=["You are a conversation-summarization assistant. The user will paste a","prior conversation between a user and an AI assistant that includes tool","calls and tool results. Produce a concise but complete summary that lets","the AI continue the conversation without losing track.","","Preserve, in this priority order:","1. The user's original intent, explicit asks, constraints, corrections,"," and preferences stated during the conversation.","2. Tool decisions and their outcomes \u2014 file paths read or written, shell"," commands run, search queries, URLs fetched, code edits made, tests"," run, errors observed, and whether each action succeeded or failed.","3. Current state: what has been completed, what remains unresolved, and"," the safest next action.","4. Open questions, pending decisions, blockers, and assumptions.","5. Key facts the assistant discovered (function locations, schemas,"," observed behaviors, important external findings).","","Drop prose narration, conversational filler, and exploratory dead-ends.","Drop verbatim tool output unless an exact snippet, error, path, command,","or result is needed for continuation.","Do not invent details. If something is uncertain, mark it explicitly.","Output plain text, no markdown headers. Aim for ~250 words; use up to","~400 only when needed to preserve tool state or unresolved tasks."].join(`
23
- `),tn="[Compacted summary of earlier conversation]",nn="Acknowledged. Continuing from the summary above.";function bo(t){if(t.role!=="user")return!1;let e=t.content;if(typeof e=="string")return!0;if(!Array.isArray(e))return!1;for(let n of e)if(n.type==="tool_result")return!1;return!0}function rn(t,e){if(e<=0)return t.length;let n=0;for(let r=t.length-1;r>=0;r--){let o=t[r];if(o&&bo(o)&&(n+=1,n===e))return r}return-1}function on(t,e,n){let r=vo(t);return{model:e,max_tokens:n,system:yo,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
21
+ \u{1F4A1} ${g.suggestion}`,await a(o)),g.type==="done"){o.trim()&&await a(o,!0);break}if(g.type==="error")throw g.error}if(o&&s){let f=Ie(nt(o));if(f.length>1)for(let g=1;g<f.length;g++){let h=f[g];h&&await t.reply(h,{parse_mode:"HTML"})}}}catch(l){throw r?.("Streaming error:",l),l}}async function Gt(t,e,n,r,o){if(!r.has(e))try{await Promise.race([n.waitForInitialization(),new Promise((a,l)=>setTimeout(()=>l(new Error("timeout")),5e3))]);let s=n.getSessionMetadata(),i=[{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"}];if(s.slashCommands?.length)for(let a of s.slashCommands){let l=a.replace(/^\//,"");i.push({command:l,description:`SDK command: ${l}`})}if(s.skills?.length)for(let a of s.skills)i.push({command:a,description:`Run ${a} skill`});await t.telegram.setMyCommands(i,{scope:{type:"chat",chat_id:e}}),r.add(e),o(`Registered ${i.length} commands for chat ${e}`)}catch(s){o(`Could not register dynamic commands for chat ${e}:`,s)}}var Me=class{sessionManager;messageQueues=new Map;registeredCommandChats;log;bot;constructor(e,n,r,o){this.bot=e,this.sessionManager=n,this.registeredCommandChats=r,this.log=o}async handle(e){let n=e.chat?.id,r=e.message.text;if(!(!n||!r)&&(console.log(`\u{1F4EC} Message from chat ID: ${n}`),!r.startsWith("/")))try{let o=await this.sessionManager.getSession(n);if(Gt(this.bot,n,o,this.registeredCommandChats,this.log).catch(s=>this.log("Failed to register chat commands:",s)),o.state!=="idle"){this.enqueueMessage(n,e,r),await e.reply("Message queued.");return}await this.processOne(n,e,r)}catch(o){console.error("\u274C Message handling error:",o),this.log("Message handling error:",o);let s=o;if((s?.message??"").includes("session is busy")){this.enqueueMessage(n,e,r),await e.reply("Message queued.");return}at(o)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):lt(o)?await e.reply("\u{1F310} Network error. Please check your connection and try again."):await e.reply(O(s))}}async processClearDirect(e,n){try{await this.sessionManager.resetSession(e),this.registeredCommandChats.delete(e),await n.reply(Ce())}catch(r){this.log("Clear error:",r),await n.reply(O(r))}}enqueueMessage(e,n,r){let o=this.messageQueues.get(e);o||(o=[],this.messageQueues.set(e,o)),o.push({type:"message",ctx:n,text:r})}enqueueClear(e,n){let r=this.messageQueues.get(e);r||(r=[],this.messageQueues.set(e,r)),r.push({type:"clear",ctx:n})}async processOne(e,n,r){try{let o=await this.sessionManager.getSession(e);await n.sendChatAction("typing").catch(()=>{}),await Kt(n,o,r,this.log)}catch(o){console.error("\u274C Message handling error:",o),this.log("Message handling error:",o);let s=o;at(o)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):lt(o)?await n.reply("\u{1F310} Network error. Please check your connection and try again."):await n.reply(O(s))}finally{this.drainQueue(e)}}async drainQueue(e){let n=this.messageQueues.get(e);if(!n?.length)return;let r=n.shift();r.type==="message"?await this.processOne(e,r.ctx,r.text):await this.processClearDirect(e,r.ctx)}};function zt(t,e=()=>{}){let n=new Set;if(!t)return n;for(let r of t.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){e("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}function Vt(t,e=()=>{}){return async(n,r)=>{let o=n.chat?.id;if(o===void 0||!t.has(o)){e("[allowlist] Rejecting update from chat:",o??"<unknown>");return}await r()}}var _e=class{bot;sessionManager;options;running=!1;registeredCommandChats=new Set;messageHandler;constructor(e){this.options=e,this.bot=new ao(e.botToken),this.sessionManager=new Te(e),this.messageHandler=new Me(this.bot,this.sessionManager,this.registeredCommandChats,this.log.bind(this)),this.setupHandlers()}setupHandlers(){this.bot.use(Vt(this.options.allowedChatIds,this.log.bind(this))),this.bot.command("start",e=>rt(e)),this.bot.command("help",e=>ot(e,this.sessionManager)),this.bot.command("clear",async e=>{let n=e.chat?.id;if(!n){await e.reply(O("Could not identify chat"));return}(await this.sessionManager.getSession(n)).state!=="idle"?(this.messageHandler.enqueueClear(n,e),await e.reply("Clear queued.")):await st(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}),this.bot.command("compact",e=>Bt(e,this.sessionManager,this.log.bind(this))),this.bot.command("model",e=>it(e,this.sessionManager,this.log.bind(this))),this.bot.on("text",e=>this.messageHandler.handle(e)),this.bot.catch((e,n)=>{this.log("Bot error:",e),n.reply(O("An unexpected error occurred. Please try again.")).catch(r=>this.log("Failed to send error message:",r))})}async start(){if(this.running)throw new Error("Bot is already running");this.log("Loading sessions..."),await this.sessionManager.loadSessions(),this.log("Starting bot..."),await this.bot.launch(),this.log("Registering bot commands..."),await this.bot.telegram.setMyCommands([{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"}]),this.running=!0,this.log("Bot started successfully");let e=async n=>{this.log(`Received ${n}, shutting down...`),await this.stop(),process.exit(0)};process.once("SIGINT",()=>e("SIGINT")),process.once("SIGTERM",()=>e("SIGTERM"))}async stop(){if(this.running){this.log("Stopping bot..."),this.running=!1,this.log("Closing sessions..."),await this.sessionManager.closeAll(),this.log("Stopping bot polling...");try{this.bot.stop()}catch(e){this.log("Error stopping bot (may not have been started):",e)}this.log("Bot stopped")}}getStats(){return{running:this.running,activeSessions:this.sessionManager.getSessionCount(),totalChats:this.sessionManager.getChatCount()}}async handleStart(e){return rt(e)}async handleHelp(e){return ot(e,this.sessionManager)}async handleClear(e){let n=e.chat?.id;if(!n){await e.reply(O("Could not identify chat"));return}if((await this.sessionManager.getSession(n)).state!=="idle")this.messageHandler.enqueueClear(n,e),await e.reply("Clear queued.");else return st(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}async handleMessage(e){return this.messageHandler.handle(e)}async handleModelSwitch(e){return it(e,this.sessionManager,this.log.bind(this))}log(...e){this.options.verbose&&console.log("[TelegramBot]",...e)}};function lo(){return process.env.AFK_DEBUG==="1"||process.env.DEBUG==="1"}function A(...t){lo()&&console.log(...t)}var G=class extends Error{constructor(e){super(e),this.name="AbortError"}},Re=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},U=class extends Error{constructor(n,r,o,s){super(n);this.event=r;this.reason=o;this.name="HookBlockedError",s?.cause!==void 0&&(this.cause=s.cause)}event;reason;cause};var ye=class extends Error{constructor(n,r,o){super(o??`${n} provider does not support AgentConfig.${r}.`);this.provider=n;this.field=r;this.name="UnsupportedProviderConfigError"}provider;field};var De=class{queue=[];waiters=[];closed=!1;error=null;push(e){if(this.closed)throw new Error("Cannot push to closed queue");if(process.env.AFK_CODEX_DEBUG&&console.log("[queue] push:",e.type),A("\u{1F4E6} MessageQueue.push: event type=",e.type,"waiters=",this.waiters.length,"queue size=",this.queue.length),this.waiters.length>0){let n=this.waiters.shift();A("\u{1F4E6} MessageQueue.push: Resolving waiter immediately"),n?.({value:e,done:!1})}else this.queue.push(e),A("\u{1F4E6} MessageQueue.push: Added to queue, new size=",this.queue.length)}complete(){for(this.closed=!0;this.waiters.length>0;)this.waiters.shift()?.({value:void 0,done:!0})}fail(e){this.error=e,this.closed=!0;let n={type:"error",error:e};if(this.waiters.length>0)for(this.waiters.shift()?.({value:n,done:!1});this.waiters.length>0;)this.waiters.shift()?.({value:void 0,done:!0});else this.queue.push(n)}isClosed(){return this.closed}hasError(){return this.error}size(){return this.queue.length}async*[Symbol.asyncIterator](){for(A("\u{1F4E6} MessageQueue: Iterator started");;){if(this.queue.length>0){let n=this.queue.shift();if(A("\u{1F4E6} MessageQueue: Yielding queued event, type=",n?.type),n&&(yield n,n.type==="error")){A("\u{1F4E6} MessageQueue: Stopping after error");return}continue}if(this.closed){A("\u{1F4E6} MessageQueue: Closed and empty, stopping");return}A("\u{1F4E6} MessageQueue: Waiting for next event...");let e=await new Promise(n=>{this.waiters.push(n)});if(A("\u{1F4E6} MessageQueue: Got result, done=",e.done,"type=",e.value?.type),e.done)return;if(yield e.value,e.value.type==="error"){A("\u{1F4E6} MessageQueue: Stopping after error");return}}}};import sa from"@anthropic-ai/sdk";var co="claude-code-20250219,oauth-2025-04-20",uo="claude-cli/1.0.0 (external, cli)",po="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function qt(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Wt(t,e){return e==="oauth"?{authToken:t}:{apiKey:t}}function ct(t,e,n){return t!=="oauth"?{}:{"anthropic-beta":co,"x-app":"cli","User-Agent":uo,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Yt(t){return t!=="oauth"?null:[{type:"text",text:po}]}import{randomUUID as Tt}from"node:crypto";function Oe(){let t=process.env.AFK_DISABLE_PROMPT_CACHE;if(t===void 0||t.length===0)return!0;let e=t.toLowerCase();return!(e==="1"||e==="true"||e==="yes"||e==="on")}function Fe(){let t=process.env.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":"1h"}function Jt(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Xt(n,e);return r===n?t:[...t.slice(0,-1),r]}function Qt(t,e){if(t.length===0)return t;let n=t[t.length-1],r=fo(n,e);return r===n?t:[...t.slice(0,-1),r]}function fo(t,e){let n=t.content;if(typeof n=="string")return n.length===0?t:{...t,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:e}}]};if(!Array.isArray(n)||n.length===0)return t;let r=n[n.length-1],o=Xt(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function Xt(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}import{randomUUID as ho}from"node:crypto";function Zt(t,e){if(!t)return{stopReason:e??null};let n={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null};return t.cache_read_input_tokens!=null&&(n.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(n.cacheCreationTokens=t.cache_creation_input_tokens),n.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n}function en(t,e){let n=(c,d)=>{if(!(c==null&&d==null))return(c??0)+(d??0)},r={stopReason:e.stopReason??t.stopReason??null},o=n(t.inputTokens,e.inputTokens);o!==void 0&&(r.inputTokens=o);let s=n(t.outputTokens,e.outputTokens);s!==void 0&&(r.outputTokens=s);let i=n(t.cachedInputTokens,e.cachedInputTokens);i!==void 0&&(r.cachedInputTokens=i);let a=n(t.cacheCreationTokens,e.cacheCreationTokens);a!==void 0&&(r.cacheCreationTokens=a);let l=n(t.totalTokens,e.totalTokens);return l!==void 0&&(r.totalTokens=l),r}function mo(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function go(t,e,n){let r=[],o=[];for(let a of t)a&&(a.kind==="text"?(r.push({type:"text",text:a.text}),o.push(a.text)):a.kind==="thinking"?r.push({type:"thinking",thinking:a.thinking,signature:a.signature}):r.push({type:"tool_use",id:a.id,name:a.name,input:mo(a.partialJson)}));let s=a=>a.type==="tool_use",i=r.filter(s);return{stopReason:e,assistantBlocks:r,toolUseBlocks:i,usage:n,text:o.join("")}}async function*tn(t,e){let n=[],r=null,o=null,s=!1;try{for await(let i of t){switch(i.type){case"message_start":{let a=i.message?.usage;a&&(o={...a});break}case"content_block_start":{let a=i.content_block;a.type==="text"?n[i.index]={kind:"text",text:""}:a.type==="thinking"?n[i.index]={kind:"thinking",thinking:"",signature:""}:a.type==="tool_use"&&(n[i.index]={kind:"tool_use",id:a.id,name:a.name,partialJson:""});break}case"content_block_delta":{let a=n[i.index],l=i.delta;l.type==="text_delta"?(a&&a.kind==="text"&&(a.text+=l.text),yield{kind:"event",event:{type:"delta.text",text:l.text,sessionId:e.sessionId}}):l.type==="input_json_delta"?a&&a.kind==="tool_use"&&(a.partialJson+=l.partial_json):l.type==="thinking_delta"?(a&&a.kind==="thinking"&&(a.thinking+=l.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:l.thinking,sessionId:e.sessionId}}):l.type==="signature_delta"&&a&&a.kind==="thinking"&&(a.signature=l.signature);break}case"content_block_stop":{let a=n[i.index];a&&a.kind==="tool_use"&&(yield{kind:"event",event:{type:"tool.use",summary:a.name,toolUseIds:[a.id],sessionId:e.sessionId}});break}case"message_delta":{i.delta&&i.delta.stop_reason!==void 0&&(r=i.delta.stop_reason);let a=i.usage;a&&(o!==null?(o.output_tokens=a.output_tokens,a.cache_creation_input_tokens!=null&&(o.cache_creation_input_tokens=a.cache_creation_input_tokens),a.cache_read_input_tokens!=null&&(o.cache_read_input_tokens=a.cache_read_input_tokens),a.input_tokens!=null&&(o.input_tokens=a.input_tokens)):o={cache_creation:null,cache_creation_input_tokens:a.cache_creation_input_tokens??null,cache_read_input_tokens:a.cache_read_input_tokens??null,inference_geo:null,input_tokens:a.input_tokens??0,output_tokens:a.output_tokens,server_tool_use:null,service_tier:null});break}case"message_stop":{s=!0;break}default:break}if(s)break}}catch(i){yield{kind:"event",event:{type:"error",error:i instanceof Error?i:new Error(String(i))}};return}yield{kind:"turn-result",result:go(n,r,o)}}var yo=0;function bo(t){if(!t||typeof t!="object")return"";let e=t,n=e.file_path??e.path??e.filePath;if(typeof n=="string")return" "+n;let r=e.command??e.cmd;if(typeof r=="string"){let s=r.split(`
22
+ `)[0];return" "+(s.length>80?s.slice(0,77)+"\u2026":s)}let o=e.query??e.pattern??e.url??e.description;return typeof o=="string"?" "+o:""}async function*nn(t){let e=t.maxToolUseIterations??yo,n={stopReason:null},r=0,o=ho(),s=Date.now();for(;;){if(t.signal.aborted)return;let i=Oe()?Qt(t.messages,Fe()):t.messages,a={model:t.model,max_tokens:t.maxTokens,messages:i,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools}:{}},l;try{l=await Promise.resolve(t.client.messages.create(a,{headers:t.headers,signal:t.signal}))}catch(m){if(t.signal.aborted)return;yield{type:"error",error:m instanceof Error?m:new Error(String(m))};return}let c=null,d=!1;try{for await(let m of tn(l,t.ctx))if(m.kind==="event"){if(m.event.type==="error"){yield m.event,d=!0;break}yield m.event}else{c=m.result;break}}catch(m){if(t.signal.aborted)return;yield{type:"error",error:m instanceof Error?m:new Error(String(m))};return}if(d)return;if(c===null){yield{type:"turn.completed",usage:n,sessionId:t.ctx.sessionId};return}if(n=en(n,Zt(c.usage,c.stopReason)),c.stopReason!=="tool_use"){c.text.length>0&&(yield{type:"assistant.message",text:c.text,sessionId:t.ctx.sessionId},c.text.length<=200&&(yield{type:"suggestion",suggestion:c.text,sessionId:t.ctx.sessionId})),yield{type:"turn.completed",usage:n,sessionId:t.ctx.sessionId};return}t.messages.push({role:"assistant",content:c.assistantBlocks});let u=[];for(let m of c.toolUseBlocks)u.push({id:m.id,name:m.name,input:m.input,signal:t.signal}),yield{type:"tool.use.start",toolUseId:m.id,toolName:m.name,toolInput:bo(m.input),sessionId:t.ctx.sessionId};if(t.signal.aborted)return;let p;if(t.toolDispatcher.executeBatch)p=await t.toolDispatcher.executeBatch(u);else{p=[];for(let m of u){if(t.signal.aborted){p.push({content:"Tool call aborted",isError:!0});continue}try{p.push(await t.toolDispatcher.execute(m))}catch(b){let v=b instanceof Error?b.message:String(b);p.push({content:`Tool execution threw: ${v}`,isError:!0})}}}let f=[];for(let m=0;m<u.length;m++){let b=u[m],v=p[m];yield{type:"tool.output",toolUseId:b.id,content:v.content,...v.isError===!0?{isError:!0}:{},sessionId:t.ctx.sessionId},f.push({type:"tool_result",tool_use_id:b.id,content:v.content,...v.isError===!0?{is_error:!0}:{}})}let g={role:"user",content:f};t.messages.push(g),r+=1;let h=c.toolUseBlocks[c.toolUseBlocks.length-1];if(yield{type:"progress",progress:{taskId:o,description:"Tool-use loop",summary:`Iteration ${r}: used ${h?.name??"unknown"}`,lastToolName:h?.name,totalTokens:n.totalTokens??0,toolUses:r,durationMs:Date.now()-s},sessionId:t.ctx.sessionId},e>0&&r>=e){yield{type:"turn.completed",usage:{...n,stopReason:"tool_use_loop_capped"},sessionId:t.ctx.sessionId};return}}}var vo=["You are a conversation-summarization assistant. The user will paste a","prior conversation between a user and an AI assistant that includes tool","calls and tool results. Produce a concise but complete summary that lets","the AI continue the conversation without losing track.","","Preserve, in this priority order:","1. The user's original intent, explicit asks, constraints, corrections,"," and preferences stated during the conversation.","2. Tool decisions and their outcomes \u2014 file paths read or written, shell"," commands run, search queries, URLs fetched, code edits made, tests"," run, errors observed, and whether each action succeeded or failed.","3. Current state: what has been completed, what remains unresolved, and"," the safest next action.","4. Open questions, pending decisions, blockers, and assumptions.","5. Key facts the assistant discovered (function locations, schemas,"," observed behaviors, important external findings).","","Drop prose narration, conversational filler, and exploratory dead-ends.","Drop verbatim tool output unless an exact snippet, error, path, command,","or result is needed for continuation.","Do not invent details. If something is uncertain, mark it explicitly.","Output plain text, no markdown headers. Aim for ~250 words; use up to","~400 only when needed to preserve tool state or unresolved tasks."].join(`
23
+ `),rn="[Compacted summary of earlier conversation]",on="Acknowledged. Continuing from the summary above.";function wo(t){if(t.role!=="user")return!1;let e=t.content;if(typeof e=="string")return!0;if(!Array.isArray(e))return!1;for(let n of e)if(n.type==="tool_result")return!1;return!0}function sn(t,e){if(e<=0)return t.length;let n=0;for(let r=t.length-1;r>=0;r--){let o=t[r];if(o&&wo(o)&&(n+=1,n===e))return r}return-1}function an(t,e,n){let r=ko(t);return{model:e,max_tokens:n,system:vo,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
24
24
 
25
25
  <transcript>
26
26
  `+r+`
27
- </transcript>`}],stream:!0}}function sn(t,e,n){return[{role:"user",content:tn+`
27
+ </transcript>`}],stream:!0}}function ln(t,e,n){return[{role:"user",content:rn+`
28
28
 
29
- `+n},{role:"assistant",content:nn},...t.slice(e)]}function an(t,e,n){let r=wo(t.slice(0,e)),o=tn.length+2+n.length+nn.length,s=Math.max(0,r-o);return Math.round(s/4)}function vo(t){let e=[];for(let n of t){let r=n.role==="user"?"User":"Assistant";if(e.push(r+":"),typeof n.content=="string")e.push(n.content);else if(Array.isArray(n.content))for(let o of n.content){let s=o.type;if(s==="text"&&"text"in o)e.push(o.text);else if(s==="tool_use"){let i=o.name??"unknown",a=ln(o.input);e.push(`[tool call: ${i} ${a}]`)}else if(s==="tool_result"){let i=o.content;e.push(`[tool result: ${cn(i)}]`)}else s==="image"?e.push("[image]"):s==="document"&&e.push("[document]")}e.push("")}return e.join(`
30
- `).trim()}function ln(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function cn(t){if(typeof t=="string")return t.length>320?t.slice(0,317)+"...":t;if(Array.isArray(t)){let e=[];for(let r of t)r.type==="text"&&"text"in r&&e.push(r.text);let n=e.join(" ");return n.length>320?n.slice(0,317)+"...":n}return""}function wo(t){let e=0;for(let n of t)if(typeof n.content=="string")e+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content){let o=r.type;o==="text"&&"text"in r?e+=r.text.length:o==="tool_use"?e+=ln(r.input).length:o==="tool_result"&&(e+=cn(r.content).length)}return e}import{z as I}from"zod";import{mkdir as Dn,appendFile as On}from"fs/promises";import{join as be}from"path";var dn={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
29
+ `+n},{role:"assistant",content:on},...t.slice(e)]}function cn(t,e,n){let r=So(t.slice(0,e)),o=rn.length+2+n.length+on.length,s=Math.max(0,r-o);return Math.round(s/4)}function ko(t){let e=[];for(let n of t){let r=n.role==="user"?"User":"Assistant";if(e.push(r+":"),typeof n.content=="string")e.push(n.content);else if(Array.isArray(n.content))for(let o of n.content){let s=o.type;if(s==="text"&&"text"in o)e.push(o.text);else if(s==="tool_use"){let i=o.name??"unknown",a=dn(o.input);e.push(`[tool call: ${i} ${a}]`)}else if(s==="tool_result"){let i=o.content;e.push(`[tool result: ${un(i)}]`)}else s==="image"?e.push("[image]"):s==="document"&&e.push("[document]")}e.push("")}return e.join(`
30
+ `).trim()}function dn(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function un(t){if(typeof t=="string")return t.length>320?t.slice(0,317)+"...":t;if(Array.isArray(t)){let e=[];for(let r of t)r.type==="text"&&"text"in r&&e.push(r.text);let n=e.join(" ");return n.length>320?n.slice(0,317)+"...":n}return""}function So(t){let e=0;for(let n of t)if(typeof n.content=="string")e+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content){let o=r.type;o==="text"&&"text"in r?e+=r.text.length:o==="tool_use"?e+=dn(r.input).length:o==="tool_result"&&(e+=un(r.content).length)}return e}import{z as I}from"zod";import{mkdir as Fn,appendFile as $n}from"fs/promises";import{join as we}from"path";var pn={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
31
31
 
32
32
  You are an inspector auditing skills for correct type categorization. Skills come from two sources:
33
33
  - **User-scope** \u2014 authored directly by the user under \`~/.afk/skills/<name>/SKILL.md\`
@@ -495,7 +495,7 @@ description: "<one-line description, 50-100 words, emphasizing the force multipl
495
495
  Return the generated SKILL.md as a complete markdown string, ready to write to disk.
496
496
  `,"qualify-rework.md":`## Rework on SALVAGE feedback
497
497
 
498
- You received SALVAGE feedback on a skill draft. Your job is to refine it based on the feedback and re-qualify:
498
+ You received SALVAGE feedback on a skill draft. Your job is to produce a structurally improved variant \u2014 not a wording polish.
499
499
 
500
500
  **Feedback from qualify:**
501
501
  {feedback}
@@ -503,11 +503,11 @@ You received SALVAGE feedback on a skill draft. Your job is to refine it based o
503
503
  **Original skill draft:**
504
504
  {original_skill}
505
505
 
506
- **Rework plan:**
507
- 1. Analyze the feedback \u2014 identify specific issues: missing detail, unclear orchestration, weak motivation, incorrect conventions
508
- 2. Refine the skill draft to address these issues
509
- 3. Preserve the core insight and orchestration pattern; improve clarity and convention compliance
510
- 4. Return the revised SKILL.md (complete, ready to qualify again)
506
+ **Rework process:**
507
+ 1. **Extract failures** \u2014 identify every rubric dimension qualify scored \u22642 (Stage 1) or 0\u20131 (Stage 2). List each with its score and qualify's stated reason.
508
+ 2. **Design machinery fixes** \u2014 for each failed dimension, propose a concrete architectural change (add sub-agent dispatch, add a gate/checkpoint, add worktree isolation, add phased execution, add verification step). Do not polish wording \u2014 change the skill's operational structure.
509
+ 3. **Prioritize** \u2014 pick the single fix that most improves the weakest dimension while naturally pulling up adjacent ones.
510
+ 4. **Rebuild** \u2014 rewrite the full SKILL.md incorporating that fix. Preserve the core insight; change the machinery.
511
511
 
512
512
  **Output:**
513
513
  Return only the revised SKILL.md markdown block. No preamble, no explanation \u2014 just the refined skill definition.
@@ -819,9 +819,9 @@ Field semantics:
819
819
  - \`status_reason\` \u2014 short reason when \`FAIL\`; omit when \`PASS\`.
820
820
  - \`issues\` \u2014 concrete blockers with file:line citations where possible. Empty array when \`PASS\`.
821
821
  - \`summary\` \u2014 optional narrative; the orchestrator may surface it to the user. Keep it concise.
822
- `}};function T(t){let e=dn[t];if(!e){let n=Object.keys(dn).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+t+". "+r)}return e}var Oe=new Map;function W(t){Oe.set(t.name,t)}function z(t){let e=Oe.get(t);if(e)return e;let n=Array.from(Oe.keys()).sort(),r=n.length>0?`
823
- Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}`)}function un(){return Array.from(Oe.keys()).sort()}var Fe=class{nodes=new Map;register(e,n){this.nodes.has(e)||this.nodes.set(e,{controller:n,children:new Set,listeners:new Set,cascading:!1})}has(e){return this.nodes.has(e)}getController(e){return this.nodes.get(e)?.controller}linkChild(e,n){let r=this.nodes.get(e),o=this.nodes.get(n);if(!r)throw new Error(`AbortGraph: parent ${e} not registered`);if(!o)throw new Error(`AbortGraph: child ${n} not registered`);if(o.parentId=e,r.children.add(n),r.controller.signal.aborted){o.controller.signal.aborted||(o.cascading=!0,o.controller.abort(r.controller.signal.reason));return}r.controller.signal.addEventListener("abort",()=>{let s=this.nodes.get(n);!s||s.parentId!==e||s.controller.signal.aborted||(s.cascading=!0,s.controller.abort(r.controller.signal.reason))},{once:!0}),o.controller.signal.addEventListener("abort",()=>{let s=this.nodes.get(n);if(!s||s.parentId!==e||s.cascading)return;let i=this.nodes.get(e);if(!i)return;let a={parentId:e,childId:n,reason:s.controller.signal.reason};for(let l of i.listeners)try{l(a)}catch{}},{once:!0})}onChildAborted(e,n){let r=this.nodes.get(e);if(!r)throw new Error(`AbortGraph: ${e} not registered`);return r.listeners.add(n),()=>{r.listeners.delete(n)}}abort(e,n){let r=this.nodes.get(e);if(!r||r.controller.signal.aborted)return;let o=[],s=[...r.children],i=new Set;for(;s.length;){let a=s.shift();if(i.has(a))continue;i.add(a);let l=this.nodes.get(a);if(l){l.cascading=!0,o.push(a);for(let c of l.children)s.push(c)}}r.controller.abort(n);for(let a of o){let l=this.nodes.get(a);l&&!l.controller.signal.aborted&&l.controller.abort(n)}}dispose(e){let n=this.nodes.get(e);if(n){n.parentId&&this.nodes.get(n.parentId)?.children.delete(e);for(let r of n.children){let o=this.nodes.get(r);o&&(o.parentId=void 0)}this.nodes.delete(e)}}};var $e=0,lt=5e3;async function Le(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{r=setTimeout(()=>{let a=n.label?` (${n.label})`:"",l=new Me(`Operation timed out after ${e}ms${a}`,e);n.controller&&!n.controller.signal.aborted&&n.controller.abort(l),i(l)},e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}async function pn(t,e,n={}){t&&await t.dispatch(e,n.signal)}async function fn(t,e,n={}){if(!t)return{};try{return await t.dispatch(e,n.signal)}catch(r){return r instanceof U||r instanceof G?(A(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(A(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{})}}import{mkdir as ko,writeFile as So}from"fs/promises";import{join as mn}from"path";function gn(){return process.env.HOME||process.env.USERPROFILE||"~"}function xo(){return mn(gn(),".claude","agent-framework","routing-decisions.jsonl")}async function hn(t){if(!(process.env.VITEST||process.env.NODE_ENV==="test"))try{let e=mn(gn(),".claude","agent-framework");await ko(e,{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,surface:"afk",...t})+`
824
- `;await So(xo(),r,{flag:"a"})}catch{}}import{AsyncLocalStorage as Po}from"node:async_hooks";var Eo=new Po;function le(){return Eo.getStore()}function yn(t){let e=Ao(t);return e!==void 0?e:To(t)}function Ao(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return bn(n.trim())}function To(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=Io(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=bn(r);if(o!==void 0)return o}}function Io(t,e){let n=0,r=!1,o=!1;for(let s=e;s>=0;s--){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function bn(t){try{return JSON.parse(t)}catch{return}}function vn(t,e,n,r){if(!r)return{id:t,status:e,message:n};let o=yn(n.content),s=r.safeParse(o);return s.success?{id:t,status:e,message:n,output:s.data}:{id:t,status:"failed",message:n,error:new Error(`structured output did not match schema: ${s.error.message}`,{cause:s.error}),schemaError:s.error}}function wn(t,e,n){let r=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:r}}function C(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}var je=class{constructor(e,n,r,o,s,i,a,l,c,d,u,p,f){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=d;this.agentType=u;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;get status(){return this.currentStatus}async run(e){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let n=Date.now(),r=Le(this.streamToFinalMessage(e),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=r;try{let o=await r;return this.lastMessage=o.content,this.lastDurationMs=Date.now()-n,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",this.onTerminal(),o}catch(o){throw this.lastDurationMs=Date.now()-n,this.currentStatus!=="cancelled"&&(this.currentStatus="failed",this.latestTerminalStatus="failed"),this.onTerminal(),o}finally{this.inFlight=null}}async streamToFinalMessage(e){let n,r="",o,s=this.progressSink??le(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let a of this.session.sendMessageStream(e))if(s&&s(a,i),a.type==="chunk"&&a.chunk.type==="content"&&(r+=a.chunk.content),a.type==="message")n=a.message;else if(a.type==="error"){o=a.error;break}else if(a.type==="done")break;if(o)throw o;if(n)return n;if(r.length>0)return{role:"assistant",content:r,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(e){try{let n=await this.run(e);return vn(this.id,this.currentStatus,n,this.outputSchema)}catch(n){return wn(this.id,this.currentStatus,n)}}runInBackground(e,n){this.runToResult(e).then(r=>{n?.(r)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled";try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async teardown(){if(this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async dispatchStopAndRelease(e){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await fn(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs});if(n.injectContext&&this.parentInputStreamRef)if(this.parentAbortSignal?.aborted)A(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){A(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}};var k=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;abortGraph=new Fe;rootId;rootController;counter=0;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),e.parentAbortSignal){let n=e.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}abortAll(e){this.abortGraph.abort(this.rootId,e)}async forkSubagent(e){let n=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry;o&&await pn(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...e.config,resume:r,forkSession:r?!0:e.config.forkSession,abortSignal:s.signal,hookRegistry:e.config.hookRegistry??this.hookRegistry,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0)},a=new Z(i),l=e.parent.getInputStreamRef?.(),c=e.parent.abortSignal,d=this.progressSink??le(),u=new je(n,a,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??$e,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},l,c,e.idPrefix,d,e.parent.sessionId);return this.active.set(n,u),await hn({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,parent_session_id:e.parent.sessionId}),u}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}};async function He(t,e={}){let{failFast:n=!0,teardown:r=!0}=e;if(t.length===0)return[];let o=new Array(t.length),s=new Set(t.map((a,l)=>l)),i=t.map((a,l)=>a.handle.runToResult(a.prompt).then(c=>{if(o[l]=c,s.delete(l),n&&c.status!=="succeeded")for(let d of s){let u=t[d];u&&u.handle.status==="running"&&u.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(t.map(a=>a.handle.teardown())),o}import{fileURLToPath as Co}from"node:url";import{dirname as Mo}from"node:path";var _o=Co(import.meta.url),gc=Mo(_o),L={name:"research-agent",systemPrompt:`---
822
+ `}};function T(t){let e=pn[t];if(!e){let n=Object.keys(pn).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+t+". "+r)}return e}var $e=new Map;function Y(t){$e.set(t.name,t)}function z(t){let e=$e.get(t);if(e)return e;let n=Array.from($e.keys()).sort(),r=n.length>0?`
823
+ Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}`)}function fn(){return Array.from($e.keys()).sort()}var Le=class{nodes=new Map;register(e,n){this.nodes.has(e)||this.nodes.set(e,{controller:n,children:new Set,listeners:new Set,cascading:!1})}has(e){return this.nodes.has(e)}getController(e){return this.nodes.get(e)?.controller}linkChild(e,n){let r=this.nodes.get(e),o=this.nodes.get(n);if(!r)throw new Error(`AbortGraph: parent ${e} not registered`);if(!o)throw new Error(`AbortGraph: child ${n} not registered`);if(o.parentId=e,r.children.add(n),r.controller.signal.aborted){o.controller.signal.aborted||(o.cascading=!0,o.controller.abort(r.controller.signal.reason));return}r.controller.signal.addEventListener("abort",()=>{let s=this.nodes.get(n);!s||s.parentId!==e||s.controller.signal.aborted||(s.cascading=!0,s.controller.abort(r.controller.signal.reason))},{once:!0}),o.controller.signal.addEventListener("abort",()=>{let s=this.nodes.get(n);if(!s||s.parentId!==e||s.cascading)return;let i=this.nodes.get(e);if(!i)return;let a={parentId:e,childId:n,reason:s.controller.signal.reason};for(let l of i.listeners)try{l(a)}catch{}},{once:!0})}onChildAborted(e,n){let r=this.nodes.get(e);if(!r)throw new Error(`AbortGraph: ${e} not registered`);return r.listeners.add(n),()=>{r.listeners.delete(n)}}abort(e,n){let r=this.nodes.get(e);if(!r||r.controller.signal.aborted)return;let o=[],s=[...r.children],i=new Set;for(;s.length;){let a=s.shift();if(i.has(a))continue;i.add(a);let l=this.nodes.get(a);if(l){l.cascading=!0,o.push(a);for(let c of l.children)s.push(c)}}r.controller.abort(n);for(let a of o){let l=this.nodes.get(a);l&&!l.controller.signal.aborted&&l.controller.abort(n)}}dispose(e){let n=this.nodes.get(e);if(n){n.parentId&&this.nodes.get(n.parentId)?.children.delete(e);for(let r of n.children){let o=this.nodes.get(r);o&&(o.parentId=void 0)}this.nodes.delete(e)}}};var je=0,dt=5e3;async function He(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{r=setTimeout(()=>{let a=n.label?` (${n.label})`:"",l=new Re(`Operation timed out after ${e}ms${a}`,e);n.controller&&!n.controller.signal.aborted&&n.controller.abort(l),i(l)},e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}async function mn(t,e,n={}){t&&await t.dispatch(e,n.signal)}async function gn(t,e,n={}){if(!t)return{};try{return await t.dispatch(e,n.signal)}catch(r){return r instanceof U||r instanceof G?(A(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(A(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{})}}import{mkdir as xo,writeFile as Eo}from"fs/promises";import{join as hn}from"path";function yn(){return process.env.HOME||process.env.USERPROFILE||"~"}function Po(){return hn(yn(),".claude","agent-framework","routing-decisions.jsonl")}async function bn(t){if(!(process.env.VITEST||process.env.NODE_ENV==="test"))try{let e=hn(yn(),".claude","agent-framework");await xo(e,{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,surface:"afk",...t})+`
824
+ `;await Eo(Po(),r,{flag:"a"})}catch{}}import{AsyncLocalStorage as Ao}from"node:async_hooks";var To=new Ao;function de(){return To.getStore()}function vn(t){let e=Io(t);return e!==void 0?e:Co(t)}function Io(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return wn(n.trim())}function Co(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=Mo(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=wn(r);if(o!==void 0)return o}}function Mo(t,e){let n=0,r=!1,o=!1;for(let s=e;s>=0;s--){let i=t[s];if(o){o=!1;continue}if(r){if(i==="\\"){o=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="}")n++;else if(i==="{"&&(n--,n===0))return s}return-1}function wn(t){try{return JSON.parse(t)}catch{return}}function kn(t,e,n,r){if(!r)return{id:t,status:e,message:n};let o=vn(n.content),s=r.safeParse(o);return s.success?{id:t,status:e,message:n,output:s.data}:{id:t,status:"failed",message:n,error:new Error(`structured output did not match schema: ${s.error.message}`,{cause:s.error}),schemaError:s.error}}function Sn(t,e,n){let r=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:r}}function C(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}var Ue=class{constructor(e,n,r,o,s,i,a,l,c,d,u,p,f){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=d;this.agentType=u;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;get status(){return this.currentStatus}async run(e){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let n=Date.now(),r=He(this.streamToFinalMessage(e),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=r;try{let o=await r;return this.lastMessage=o.content,this.lastDurationMs=Date.now()-n,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",this.onTerminal(),o}catch(o){throw this.lastDurationMs=Date.now()-n,this.currentStatus!=="cancelled"&&(this.currentStatus="failed",this.latestTerminalStatus="failed"),this.onTerminal(),o}finally{this.inFlight=null}}async streamToFinalMessage(e){let n,r="",o,s=this.progressSink??de(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let a of this.session.sendMessageStream(e))if(s&&s(a,i),a.type==="chunk"&&a.chunk.type==="content"&&(r+=a.chunk.content),a.type==="message")n=a.message;else if(a.type==="error"){o=a.error;break}else if(a.type==="done")break;if(o)throw o;if(n)return n;if(r.length>0)return{role:"assistant",content:r,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(e){try{let n=await this.run(e);return kn(this.id,this.currentStatus,n,this.outputSchema)}catch(n){return Sn(this.id,this.currentStatus,n)}}runInBackground(e,n){this.runToResult(e).then(r=>{n?.(r)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled";try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async teardown(){if(this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async dispatchStopAndRelease(e){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await gn(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs});if(n.injectContext&&this.parentInputStreamRef)if(this.parentAbortSignal?.aborted)A(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){A(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}};var S=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;abortGraph=new Le;rootId;rootController;counter=0;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),e.parentAbortSignal){let n=e.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}abortAll(e){this.abortGraph.abort(this.rootId,e)}async forkSubagent(e){let n=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry;o&&await mn(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...e.config,resume:r,forkSession:r?!0:e.config.forkSession,abortSignal:s.signal,apiKey:e.config.apiKey||this.parentApiKey,hookRegistry:e.config.hookRegistry??this.hookRegistry,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0)},a=new te(i),l=e.parent.getInputStreamRef?.(),c=e.parent.abortSignal,d=this.progressSink??de(),u=new Ue(n,a,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??je,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},l,c,e.idPrefix,d,e.parent.sessionId);return this.active.set(n,u),await bn({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,parent_session_id:e.parent.sessionId}),u}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}};async function Ne(t,e={}){let{failFast:n=!0,teardown:r=!0}=e;if(t.length===0)return[];let o=new Array(t.length),s=new Set(t.map((a,l)=>l)),i=t.map((a,l)=>a.handle.runToResult(a.prompt).then(c=>{if(o[l]=c,s.delete(l),n&&c.status!=="succeeded")for(let d of s){let u=t[d];u&&u.handle.status==="running"&&u.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(t.map(a=>a.handle.teardown())),o}import{fileURLToPath as _o}from"node:url";import{dirname as Ro}from"node:path";var Do=_o(import.meta.url),yc=Ro(Do),L={name:"research-agent",systemPrompt:`---
825
825
  name: research-agent
826
826
  description: Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to \`git-investigator\`. Use when the dispatched task is findings-only.
827
827
  model: sonnet
@@ -871,16 +871,16 @@ Unless the dispatcher specifies a different schema, return:
871
871
  \`\`\`
872
872
 
873
873
  If \`scope_check\` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through \`research-agent\`.
874
- `,sourcePath:"agent-framework-private/agents/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:"Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to `git-investigator`. Use when the dispatched task is findings-only."};import{join as N,dirname as bc}from"path";import{homedir as ct}from"os";function ee(){return N(ct(),".afk")}function ce(){return N(ee(),"plugins")}function Ro(){return N(process.cwd(),".afk")}function he(){return N(Ro(),"plugins")}function Ue(){return N(ce(),".index.json")}function kn(){return N(ee(),"config")}function Do(){return N(ee(),"state")}function Sn(){return N(Do(),"sessions")}function xn(){return N(kn(),"afk.env")}function dt(){return N(kn(),"afk.config.json")}function Pn(){return N(ct(),".afk.env")}function ut(){return N(ct(),".afk.config.json")}import{existsSync as te,readdirSync as No,readFileSync as Bo}from"fs";import{join as Y}from"path";import{existsSync as pt,readFileSync as $o,readdirSync as Lo,statSync as jo}from"fs";import{join as ye,resolve as An}from"path";import{existsSync as Oo,mkdirSync as Sc,readFileSync as Fo,renameSync as xc,writeFileSync as Pc,unlinkSync as Ec}from"fs";function En(t=Ue()){if(!Oo(t))return Ne();try{let e=Fo(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Ne();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Ne()}catch{return Ne()}}function Ne(){return{version:2,plugins:{},marketplaces:{}}}var Ho=5,Tn="cache";function q(t=ce()){if(!pt(t))return[];let e=t===ce()?Ue():ye(t,".index.json"),n=En(e),r=[];return In(t,t,0,r,new Set,n.plugins),r}function In(t,e,n,r,o,s){if(n>Ho||o.has(e))return;if(o.add(e),pt(ye(e,".claude-plugin","plugin.json"))){let a=ft(t,e);if(a===null){r.push({type:"local",path:e});return}if(a.layout==="cache"){let c=s[a.key];if(!c||c.enabled===!1)return;r.push({type:"local",path:e});return}let l=s[a.key];if(l&&l.enabled===!1)return;r.push({type:"local",path:e});return}let i;try{i=Lo(e)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=ye(e,a),c;try{c=jo(l)}catch{continue}c.isDirectory()&&In(t,l,n+1,r,o,s)}}function ft(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===Tn&&r.length>=3){let s=r[1];if(s){let i=ye(t,Tn,s),l=Uo(i,e)??r[2];if(l)return{layout:"cache",key:`${s}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function Uo(t,e){let n=ye(t,".claude-plugin","marketplace.json");if(!pt(n))return null;let r;try{r=JSON.parse($o(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=An(e);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&An(t,a.source)===s)return a.name}return null}var Cn=["command","agent"];function Mn(t=ee()){let e=[],n=Y(t,"skills");if(te(n))for(let r of Be(n)){let o=Y(n,r,"SKILL.md");te(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of Cn){let o=Y(t,`${r}s`);if(te(o))for(let s of Be(o))s.endsWith(".md")&&e.push({path:Y(o,s),type:r,source:"user"})}return e}function _n(t=ce()){if(!te(t))return[];let e=[],n=q(t);for(let r of n){let s=ft(t,r.path)?.key,i=Y(r.path,"skills");if(te(i))for(let a of Be(i)){let l=Y(i,a,"SKILL.md");if(!te(l))continue;let c={path:l,type:"skill",source:"plugin"};s&&(c.plugin_key=s),e.push(c)}for(let a of Cn){let l=Y(r.path,`${a}s`);if(te(l))for(let c of Be(l)){if(!c.endsWith(".md"))continue;let d={path:Y(l,c),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function Rn(t=Y(ee(),"settings.json")){if(!te(t))return[];try{let e=Bo(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function Be(t){try{return No(t).filter(e=>!e.startsWith("."))}catch{return[]}}var $n=I.object({path:I.string(),type:I.enum(["skill","command","agent","hook"]),source:I.enum(["user","plugin"]),plugin_key:I.string().optional(),verdict:I.enum(["correct","misfit","outlier"]),recommended_type:I.string(),rationale:I.string(),confidence:I.enum(["high","med","low"])}),Fn=I.record(I.string(),I.record(I.string(),I.number())),Wc=I.object({inventory:I.object({user:Fn,plugin:Fn}),misfits:I.array($n),briefs_written:I.number(),total_artifacts:I.number()}),Ko=I.object({writeBriefs:I.boolean().optional(),scope:I.enum(["user","plugin","all"]).optional()}),Go=["skill","command","agent"],Ln=["skill","command","agent","hook"];function zo(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function Vo(t){let e=()=>{let s={};for(let i of Ln)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function qo(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function Wo(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
875
- `)}function Yo(t,e){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${t}\``),n.push(""),e.length===0)return n.push("(no hooks discovered)"),n.join(`
874
+ `,sourcePath:"agent-framework-private/agents/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:"Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to `git-investigator`. Use when the dispatched task is findings-only."};import{join as N,dirname as wc}from"path";import{homedir as ut}from"os";function ne(){return N(ut(),".afk")}function ue(){return N(ne(),"plugins")}function Oo(){return N(process.cwd(),".afk")}function be(){return N(Oo(),"plugins")}function Be(){return N(ue(),".index.json")}function xn(){return N(ne(),"config")}function Fo(){return N(ne(),"state")}function En(){return N(Fo(),"sessions")}function Pn(){return N(xn(),"afk.env")}function pt(){return N(xn(),"afk.config.json")}function An(){return N(ut(),".afk.env")}function ft(){return N(ut(),".afk.config.json")}import{existsSync as re,readdirSync as Ko,readFileSync as Go}from"fs";import{join as J}from"path";import{existsSync as mt,readFileSync as jo,readdirSync as Ho,statSync as Uo}from"fs";import{join as ve,resolve as In}from"path";import{existsSync as $o,mkdirSync as Ec,readFileSync as Lo,renameSync as Pc,writeFileSync as Ac,unlinkSync as Tc}from"fs";function Tn(t=Be()){if(!$o(t))return Ke();try{let e=Lo(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Ke();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Ke()}catch{return Ke()}}function Ke(){return{version:2,plugins:{},marketplaces:{}}}var No=5,Cn="cache";function q(t=ue()){if(!mt(t))return[];let e=t===ue()?Be():ve(t,".index.json"),n=Tn(e),r=[];return Mn(t,t,0,r,new Set,n.plugins),r}function Mn(t,e,n,r,o,s){if(n>No||o.has(e))return;if(o.add(e),mt(ve(e,".claude-plugin","plugin.json"))){let a=gt(t,e);if(a===null){r.push({type:"local",path:e});return}if(a.layout==="cache"){let c=s[a.key];if(!c||c.enabled===!1)return;r.push({type:"local",path:e});return}let l=s[a.key];if(l&&l.enabled===!1)return;r.push({type:"local",path:e});return}let i;try{i=Ho(e)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=ve(e,a),c;try{c=Uo(l)}catch{continue}c.isDirectory()&&Mn(t,l,n+1,r,o,s)}}function gt(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===Cn&&r.length>=3){let s=r[1];if(s){let i=ve(t,Cn,s),l=Bo(i,e)??r[2];if(l)return{layout:"cache",key:`${s}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function Bo(t,e){let n=ve(t,".claude-plugin","marketplace.json");if(!mt(n))return null;let r;try{r=JSON.parse(jo(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=In(e);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&In(t,a.source)===s)return a.name}return null}var _n=["command","agent"];function Rn(t=ne()){let e=[],n=J(t,"skills");if(re(n))for(let r of Ge(n)){let o=J(n,r,"SKILL.md");re(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of _n){let o=J(t,`${r}s`);if(re(o))for(let s of Ge(o))s.endsWith(".md")&&e.push({path:J(o,s),type:r,source:"user"})}return e}function Dn(t=ue()){if(!re(t))return[];let e=[],n=q(t);for(let r of n){let s=gt(t,r.path)?.key,i=J(r.path,"skills");if(re(i))for(let a of Ge(i)){let l=J(i,a,"SKILL.md");if(!re(l))continue;let c={path:l,type:"skill",source:"plugin"};s&&(c.plugin_key=s),e.push(c)}for(let a of _n){let l=J(r.path,`${a}s`);if(re(l))for(let c of Ge(l)){if(!c.endsWith(".md"))continue;let d={path:J(l,c),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function On(t=J(ne(),"settings.json")){if(!re(t))return[];try{let e=Go(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function Ge(t){try{return Ko(t).filter(e=>!e.startsWith("."))}catch{return[]}}var jn=I.object({path:I.string(),type:I.enum(["skill","command","agent","hook"]),source:I.enum(["user","plugin"]),plugin_key:I.string().optional(),verdict:I.enum(["correct","misfit","outlier"]),recommended_type:I.string(),rationale:I.string(),confidence:I.enum(["high","med","low"])}),Ln=I.record(I.string(),I.record(I.string(),I.number())),Jc=I.object({inventory:I.object({user:Ln,plugin:Ln}),misfits:I.array(jn),briefs_written:I.number(),total_artifacts:I.number()}),zo=I.object({writeBriefs:I.boolean().optional(),scope:I.enum(["user","plugin","all"]).optional()}),Vo=["skill","command","agent"],Hn=["skill","command","agent","hook"];function qo(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function Wo(t){let e=()=>{let s={};for(let i of Hn)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function Yo(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function Jo(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
875
+ `)}function Qo(t,e){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${t}\``),n.push(""),e.length===0)return n.push("(no hooks discovered)"),n.join(`
876
876
  `);for(let r of e){let o=`${r.event}-${r.index}`;n.push(`### Hook \`${o}\``),n.push(""),n.push("```json"),n.push(JSON.stringify(r.raw,null,2)),n.push("```"),n.push("")}return n.join(`
877
- `)}function Jo(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function Qo(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Ko.parse(n),o=r.writeBriefs??!0,s=r.scope??"all",i=zo(s);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let a=e.sessionId,l=T("audit-fit"),c={skill:l["01-skill-inspector.md"],command:l["02-command-inspector.md"],agent:l["03-agent-inspector.md"],hook:l["04-hook-inspector.md"]};for(let w of Ln)if(!c[w])throw new Error(`audit-fit skill missing inspector prompt for ${w}`);let d=i.runUserDiscovery?Mn():[],u=i.runPluginDiscovery?_n():[],p={skill:[],command:[],agent:[]};for(let w of[...d,...u])p[w.type].push(w);let f=new k,g=()=>async w=>L.allowedTools.includes(w)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${w} not allowed for audit-fit inspectors. Allowed tools: ${L.allowedTools.join(", ")}`},h=[];for(let w of Go){let P=p[w];if(P.length===0)continue;let y=c[w];y&&h.push({type:w,prompt:`${y}
878
- ${Wo(P)}`,artifacts:P,runPrompt:`Inspect every ${w} listed in the artifact section.`})}if(i.runHookInspector){let w=c.hook;if(w){let P=be(ee(),"settings.json"),y=Rn(P);h.push({type:"hook",prompt:`${w}
879
- ${Yo(P,y)}`,artifacts:[],runPrompt:`Inspect every hook listed in the Discovered hooks section. Settings file: ${P}.`})}}let m=[];if(h.length>0){let w=await Promise.all(h.map(E=>f.forkSubagent({parent:{sessionId:a},config:{model:"sonnet",systemPrompt:`${L.systemPrompt}
877
+ `)}function Xo(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function Zo(t,e,n){let r=n?.apiKey,o=typeof t=="object"&&t!==null?t:{},s=zo.parse(o),i=s.writeBriefs??!0,a=s.scope??"all",l=qo(a);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let c=e.sessionId,d=T("audit-fit"),u={skill:d["01-skill-inspector.md"],command:d["02-command-inspector.md"],agent:d["03-agent-inspector.md"],hook:d["04-hook-inspector.md"]};for(let k of Hn)if(!u[k])throw new Error(`audit-fit skill missing inspector prompt for ${k}`);let p=l.runUserDiscovery?Rn():[],f=l.runPluginDiscovery?Dn():[],g={skill:[],command:[],agent:[]};for(let k of[...p,...f])g[k.type].push(k);let h=new S({apiKey:r}),m=()=>async k=>L.allowedTools.includes(k)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${k} not allowed for audit-fit inspectors. Allowed tools: ${L.allowedTools.join(", ")}`},b=[];for(let k of Vo){let E=g[k];if(E.length===0)continue;let y=u[k];y&&b.push({type:k,prompt:`${y}
878
+ ${Jo(E)}`,artifacts:E,runPrompt:`Inspect every ${k} listed in the artifact section.`})}if(l.runHookInspector){let k=u.hook;if(k){let E=we(ne(),"settings.json"),y=On(E);b.push({type:"hook",prompt:`${k}
879
+ ${Qo(E,y)}`,artifacts:[],runPrompt:`Inspect every hook listed in the Discovered hooks section. Settings file: ${E}.`})}}let v=[];if(b.length>0){let k=await Promise.all(b.map(P=>h.forkSubagent({parent:{sessionId:c},config:{model:"sonnet",systemPrompt:`${L.systemPrompt}
880
880
 
881
- ${E.prompt}`,canUseTool:g()},idPrefix:`inspector-${E.type}`,outputSchema:I.array($n)}))),P=await He(h.map((E,j)=>{let D=w[j];if(!D)throw new Error(`audit-fit: missing handle for ${E.type} inspector`);return{handle:D,prompt:E.runPrompt}}),{failFast:!1}),y=[];for(let E=0;E<P.length;E++){let j=P[E],D=h[E];if(!D)continue;let oe=Jo(D.type,j);if(oe.kind==="failure"){y.push(oe.message);continue}let Ze=new Map;for(let H of D.artifacts)Ze.set(H.path,H.source);for(let H of oe.output){if(D.type==="hook"){if(H.source!=="user"){y.push(`${D.type}: hook verdict has source=${H.source} (must be 'user')`);continue}}else{let se=Ze.get(H.path);if(se===void 0){y.push(`${D.type}: verdict for unknown path ${H.path} (not in discovered list)`);continue}if(H.source!==se){y.push(`${D.type}: verdict source mismatch for ${H.path} (expected ${se}, got ${H.source})`);continue}}m.push(H)}}if(y.length>0){let E=y.map(j=>` - ${j}`).join(`
881
+ ${P.prompt}`,canUseTool:m()},idPrefix:`inspector-${P.type}`,outputSchema:I.array(jn)}))),E=await Ne(b.map((P,j)=>{let D=k[j];if(!D)throw new Error(`audit-fit: missing handle for ${P.type} inspector`);return{handle:D,prompt:P.runPrompt}}),{failFast:!1}),y=[];for(let P=0;P<E.length;P++){let j=E[P],D=b[P];if(!D)continue;let ie=Xo(D.type,j);if(ie.kind==="failure"){y.push(ie.message);continue}let tt=new Map;for(let H of D.artifacts)tt.set(H.path,H.source);for(let H of ie.output){if(D.type==="hook"){if(H.source!=="user"){y.push(`${D.type}: hook verdict has source=${H.source} (must be 'user')`);continue}}else{let ae=tt.get(H.path);if(ae===void 0){y.push(`${D.type}: verdict for unknown path ${H.path} (not in discovered list)`);continue}if(H.source!==ae){y.push(`${D.type}: verdict source mismatch for ${H.path} (expected ${ae}, got ${H.source})`);continue}}v.push(H)}}if(y.length>0){let P=y.map(j=>` - ${j}`).join(`
882
882
  `);throw new Error(`audit-fit: ${y.length} inspector failure(s):
883
- ${E}`)}}let{inventory:b,misfits:S}=Vo(m),F=0;if(o){let w=process.env.HOME||process.env.USERPROFILE||"~",P=be(w,".claude","agent-framework","briefs");await Dn(P,{recursive:!0});for(let y of S.filter(qo)){let E=y.path.replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,30),j=be(P,`audit-fit-${E}.md`),D=`---
883
+ ${P}`)}}let{inventory:F,misfits:W}=Wo(v),B=0;if(i){let k=process.env.HOME||process.env.USERPROFILE||"~",E=we(k,".claude","agent-framework","briefs");await Fn(E,{recursive:!0});for(let y of W.filter(Yo)){let P=y.path.replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,30),j=we(E,`audit-fit-${P}.md`),D=`---
884
884
  theme: audit-fit
885
885
  session_count: 1
886
886
  ---
@@ -902,41 +902,41 @@ ${y.rationale}
902
902
 
903
903
  ---
904
904
  Generated by audit-fit on ${new Date().toISOString().split(".")[0]}Z
905
- `;await On(j,D),F++}}let R=process.env.HOME||process.env.USERPROFILE||"~",x=be(R,".claude","agent-framework");await Dn(x,{recursive:!0});let M=w=>{let P=0;for(let y of Object.values(w))for(let E of Object.values(y))P+=E;return P},_=w=>{let P=b.user[w]??{},y=b.plugin[w]??{},E=j=>Object.values(j).reduce((D,oe)=>D+oe,0);return E(P)+E(y)},B={timestamp:new Date().toISOString(),surface:"afk",scope:s,total_artifacts:m.length,misfits_count:S.length,briefs_written:F,by_source:{user:M(b.user),plugin:M(b.plugin)},by_type:{skill:_("skill"),command:_("command"),agent:_("agent"),hook:_("hook")}},K=be(x,"audit-fit-telemetry.jsonl");return await On(K,JSON.stringify(B)+`
906
- `),{inventory:b,misfits:S,briefs_written:F,total_artifacts:m.length}}var Xo={name:"audit-fit",description:"Audit ~/.afk artifacts (skills, commands, agents, hooks) for correct type categorization. Walks user-scope dirs (~/.afk/{skills,commands,agents}/) and every plugin installed under ~/.afk/plugins/ (flat and marketplace-cache layouts), plus ~/.afk/settings.json for hooks. Dispatches per-type inspectors in parallel, applies decision heuristics (progressive-disclosure value, isolation need, deterministic vs. reasoning), flags misfits. Generates migration briefs only for user-scope misfits (plugin misfits are inventory-only \u2014 refactoring vendored plugin code is the maintainer's job). Optional `scope` input filters to `user`, `plugin`, or `all` (default). Use for inventory audits after bulk authoring, imports, or periodic hygiene.",handler:Qo,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"]};W(Xo);import{z as v}from"zod";import{execFile as ns}from"node:child_process";import{promisify as rs}from"node:util";import{tmpdir as os}from"node:os";import{join as ss}from"node:path";function jn(t){return t.confidence<.5?{verify:!0,reason:`low confidence (${t.confidence.toFixed(2)} < ${.5})`}:t.boundary_flag&&t.boundary_flag.length>0?{verify:!0,reason:`boundary flag set: ${t.boundary_flag}`}:t.coverage_gaps&&t.coverage_gaps.length>0?{verify:!0,reason:`coverage gap${t.coverage_gaps.length===1?"":"s"}: ${t.coverage_gaps.length} unresolved`}:{verify:!1,reason:`confidence ${t.confidence.toFixed(2)} with no gaps or boundary`}}import{fileURLToPath as Zo}from"node:url";import{dirname as es}from"node:path";var ts=Zo(import.meta.url),ed=es(ts),mt={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\nmodel: sonnet\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"agent-framework-private/agents/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"};function gt(t){let e={description:t.description,prompt:t.systemPrompt};return t.allowedTools&&(e.tools=[...t.allowedTools]),t.model&&(e.model=t.model),e}var Hn=rs(ns),Bn=v.object({id:v.string(),claim:v.string(),confidence:v.number().min(0).max(1),evidence_sources:v.array(v.string()),location:v.string().optional(),proposed_fix:v.string().optional(),coverage_gaps:v.array(v.string()).optional(),boundary_flag:v.string().optional()}),is=v.object({hypothesis_id:v.string(),claim:v.string(),verdict:v.enum(["VERIFIED","REFUTED","INCONCLUSIVE"]),evidence:v.string(),gate_reason:v.string()}),Kn=v.object({hypothesis_id:v.string(),reproducer_passed:v.boolean(),regressions:v.array(v.string()),confidence:v.number().min(0).max(1),verification_log:v.string()}),yd=v.object({reproducer:v.string().optional(),hypotheses:v.array(Bn),premise_verifications:v.array(is).optional(),winner:v.object({hypothesis_id:v.string(),verification_log:v.string(),proposed_fix:v.string()}).optional(),verification_results:v.array(Kn).optional()});async function as(t,e){let n=t.map(l=>({hypothesis:l,decision:jn(l)})).filter(l=>l.decision.verify);if(n.length===0)return{premise_verifications:[],hypotheses_to_test:t};let r=[],o;try{r=await e(n.map(l=>l.hypothesis.claim))}catch(l){o=l instanceof Error?l.message:String(l)}let s=n.map((l,c)=>{let d=r[c];return o!==void 0?{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:`shadow-verify dispatch failed: ${o}`,gate_reason:l.decision.reason}:d?{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:d.verdict,evidence:d.evidence,gate_reason:l.decision.reason}:{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:"no verifier result for this claim",gate_reason:l.decision.reason}}),i=new Set(s.filter(l=>l.verdict==="REFUTED").map(l=>l.hypothesis_id)),a=i.size===0?t:t.filter(l=>!i.has(l.id));return{premise_verifications:s,hypotheses_to_test:a}}async function ls(t,e){let n=(()=>{if(typeof t=="string")return{failure:t,repoPath:process.cwd(),context:"",maxHypotheses:4};if(typeof t=="object"&&t!==null){let y=t;if(typeof y.failure=="string")return{failure:y.failure,repoPath:y.repoPath||process.cwd(),context:y.context||"",maxHypotheses:Math.min(y.maxHypotheses||4,4)}}throw new Error("diagnose handler requires input.failure (string) or a string argument")})();if(!e?.sessionId)throw new Error("diagnose requires a parent session with sessionId");let r=e.sessionId,o=T("diagnose"),s=o["system.md"],i=o["research.md"],a=o["hypothesis.md"],l=o["verify.md"];if(!s||!i||!a||!l)throw new Error("diagnose skill missing required prompts (system.md, research.md, hypothesis.md, verify.md)");let c=new k,d=cs(n.context),u=`${L.systemPrompt}
905
+ `;await $n(j,D),B++}}let _=process.env.HOME||process.env.USERPROFILE||"~",x=we(_,".claude","agent-framework");await Fn(x,{recursive:!0});let R=k=>{let E=0;for(let y of Object.values(k))for(let P of Object.values(y))E+=P;return E},M=k=>{let E=F.user[k]??{},y=F.plugin[k]??{},P=j=>Object.values(j).reduce((D,ie)=>D+ie,0);return P(E)+P(y)},K={timestamp:new Date().toISOString(),surface:"afk",scope:a,total_artifacts:v.length,misfits_count:W.length,briefs_written:B,by_source:{user:R(F.user),plugin:R(F.plugin)},by_type:{skill:M("skill"),command:M("command"),agent:M("agent"),hook:M("hook")}},ee=we(x,"audit-fit-telemetry.jsonl");return await $n(ee,JSON.stringify(K)+`
906
+ `),{inventory:F,misfits:W,briefs_written:B,total_artifacts:v.length}}var es={name:"audit-fit",description:"Audit ~/.afk artifacts (skills, commands, agents, hooks) for correct type categorization. Walks user-scope dirs (~/.afk/{skills,commands,agents}/) and every plugin installed under ~/.afk/plugins/ (flat and marketplace-cache layouts), plus ~/.afk/settings.json for hooks. Dispatches per-type inspectors in parallel, applies decision heuristics (progressive-disclosure value, isolation need, deterministic vs. reasoning), flags misfits. Generates migration briefs only for user-scope misfits (plugin misfits are inventory-only \u2014 refactoring vendored plugin code is the maintainer's job). Optional `scope` input filters to `user`, `plugin`, or `all` (default). Use for inventory audits after bulk authoring, imports, or periodic hygiene.",handler:Zo,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"]};Y(es);import{z as w}from"zod";import{execFile as os}from"node:child_process";import{promisify as ss}from"node:util";import{tmpdir as is}from"node:os";import{join as as}from"node:path";function Un(t){return t.confidence<.5?{verify:!0,reason:`low confidence (${t.confidence.toFixed(2)} < ${.5})`}:t.boundary_flag&&t.boundary_flag.length>0?{verify:!0,reason:`boundary flag set: ${t.boundary_flag}`}:t.coverage_gaps&&t.coverage_gaps.length>0?{verify:!0,reason:`coverage gap${t.coverage_gaps.length===1?"":"s"}: ${t.coverage_gaps.length} unresolved`}:{verify:!1,reason:`confidence ${t.confidence.toFixed(2)} with no gaps or boundary`}}import{fileURLToPath as ts}from"node:url";import{dirname as ns}from"node:path";var rs=ts(import.meta.url),nd=ns(rs),ht={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\nmodel: sonnet\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"agent-framework-private/agents/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"};function yt(t){let e={description:t.description,prompt:t.systemPrompt};return t.allowedTools&&(e.tools=[...t.allowedTools]),t.model&&(e.model=t.model),e}var Nn=ss(os),Gn=w.object({id:w.string(),claim:w.string(),confidence:w.number().min(0).max(1),evidence_sources:w.array(w.string()),location:w.string().optional(),proposed_fix:w.string().optional(),coverage_gaps:w.array(w.string()).optional(),boundary_flag:w.string().optional()}),ls=w.object({hypothesis_id:w.string(),claim:w.string(),verdict:w.enum(["VERIFIED","REFUTED","INCONCLUSIVE"]),evidence:w.string(),gate_reason:w.string()}),zn=w.object({hypothesis_id:w.string(),reproducer_passed:w.boolean(),regressions:w.array(w.string()),confidence:w.number().min(0).max(1),verification_log:w.string()}),vd=w.object({reproducer:w.string().optional(),hypotheses:w.array(Gn),premise_verifications:w.array(ls).optional(),winner:w.object({hypothesis_id:w.string(),verification_log:w.string(),proposed_fix:w.string()}).optional(),verification_results:w.array(zn).optional()});async function cs(t,e){let n=t.map(l=>({hypothesis:l,decision:Un(l)})).filter(l=>l.decision.verify);if(n.length===0)return{premise_verifications:[],hypotheses_to_test:t};let r=[],o;try{r=await e(n.map(l=>l.hypothesis.claim))}catch(l){o=l instanceof Error?l.message:String(l)}let s=n.map((l,c)=>{let d=r[c];return o!==void 0?{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:`shadow-verify dispatch failed: ${o}`,gate_reason:l.decision.reason}:d?{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:d.verdict,evidence:d.evidence,gate_reason:l.decision.reason}:{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:"no verifier result for this claim",gate_reason:l.decision.reason}}),i=new Set(s.filter(l=>l.verdict==="REFUTED").map(l=>l.hypothesis_id)),a=i.size===0?t:t.filter(l=>!i.has(l.id));return{premise_verifications:s,hypotheses_to_test:a}}async function ds(t,e,n){let r=n?.apiKey,o=(()=>{if(typeof t=="string")return{failure:t,repoPath:process.cwd(),context:"",maxHypotheses:4};if(typeof t=="object"&&t!==null){let y=t;if(typeof y.failure=="string")return{failure:y.failure,repoPath:y.repoPath||process.cwd(),context:y.context||"",maxHypotheses:Math.min(y.maxHypotheses||4,4)}}throw new Error("diagnose handler requires input.failure (string) or a string argument")})();if(!e?.sessionId)throw new Error("diagnose requires a parent session with sessionId");let s=e.sessionId,i=T("diagnose"),a=i["system.md"],l=i["research.md"],c=i["hypothesis.md"],d=i["verify.md"];if(!a||!l||!c||!d)throw new Error("diagnose skill missing required prompts (system.md, research.md, hypothesis.md, verify.md)");let u=new S({apiKey:r}),p=us(o.context),f=`${L.systemPrompt}
907
907
 
908
- ${i}
908
+ ${l}
909
909
 
910
910
  Focus: CODEBASE
911
- Failure: ${n.failure}${n.context?`
912
- Context: ${n.context}`:""}`,p=`${L.systemPrompt}
911
+ Failure: ${o.failure}${o.context?`
912
+ Context: ${o.context}`:""}`,g=`${L.systemPrompt}
913
913
 
914
- ${i}
914
+ ${l}
915
915
 
916
916
  Focus: GIT HISTORY
917
- Failure: ${n.failure}${n.context?`
918
- Context: ${n.context}`:""}
917
+ Failure: ${o.failure}${o.context?`
918
+ Context: ${o.context}`:""}
919
919
 
920
- Repo: ${n.repoPath}`,f=await c.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:u,canUseTool:Un()},idPrefix:"diagnose-codebase-research"}),g=await c.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:p,cwd:n.repoPath,agents:{"git-investigator":gt(mt)},canUseTool:ds()},idPrefix:"diagnose-git-research"}),[h,m]=await He([{handle:f,prompt:"Analyze the codebase for potential causes of this failure."},{handle:g,prompt:"Analyze git history for recent changes that could cause this failure."}],{failFast:!1}),b={codebase:h?.output||h?.message||"No output",git:m?.output||m?.message||"No output"},S=await c.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:`${s}
920
+ Repo: ${o.repoPath}`,h=await u.forkSubagent({parent:{sessionId:s},config:{model:"sonnet",systemPrompt:f,canUseTool:Bn()},idPrefix:"diagnose-codebase-research"}),m=await u.forkSubagent({parent:{sessionId:s},config:{model:"sonnet",systemPrompt:g,cwd:o.repoPath,agents:{"git-investigator":yt(ht)},canUseTool:ps()},idPrefix:"diagnose-git-research"}),[b,v]=await Ne([{handle:h,prompt:"Analyze the codebase for potential causes of this failure."},{handle:m,prompt:"Analyze git history for recent changes that could cause this failure."}],{failFast:!1}),F={codebase:b?.output||b?.message||"No output",git:v?.output||v?.message||"No output"},W=await u.forkSubagent({parent:{sessionId:s},config:{model:"sonnet",systemPrompt:`${a}
921
921
 
922
- ${a}`,canUseTool:Un()},idPrefix:"diagnose-hypothesis-synthesis",outputSchema:v.object({hypotheses:v.array(Bn)})}),F=`Given these research findings, synthesize 2\u20134 hypotheses (max 4):
922
+ ${c}`,canUseTool:Bn()},idPrefix:"diagnose-hypothesis-synthesis",outputSchema:w.object({hypotheses:w.array(Gn)})}),B=`Given these research findings, synthesize 2\u20134 hypotheses (max 4):
923
923
 
924
924
  CODEBASE RESEARCH:
925
- ${JSON.stringify(b.codebase,null,2)}
925
+ ${JSON.stringify(F.codebase,null,2)}
926
926
 
927
927
  GIT RESEARCH:
928
- ${JSON.stringify(b.git,null,2)}
928
+ ${JSON.stringify(F.git,null,2)}
929
929
 
930
- Original failure: ${n.failure}`,R;try{R=await S.runToResult(F)}finally{await S.teardown().catch(()=>{})}if(R.status!=="succeeded"||!R.output)throw new Error(`hypothesis synthesis failed: ${C(R)}`);let x=R.output.hypotheses.slice(0,n.maxHypotheses);if(x.length===0)return{reproducer:d,hypotheses:[],verification_results:[]};let{premise_verifications:M,hypotheses_to_test:_}=await as(x,async y=>{let E=z("shadow-verify");if(!E)throw new Error("shadow-verify skill not registered");return(await E.handler({claims:y,context:`Original failure: ${n.failure}`},e)).verifications});if(_.length===0)return{reproducer:d,hypotheses:x,premise_verifications:M,verification_results:[]};let B=d||n.failure,K=_.map(y=>us(y,B,n.repoPath,r,l,c)),w=await Promise.all(K),P=w.find(y=>y.reproducer_passed);return{reproducer:d,hypotheses:x,premise_verifications:M.length>0?M:void 0,winner:P?{hypothesis_id:P.hypothesis_id,verification_log:P.verification_log,proposed_fix:x.find(y=>y.id===P.hypothesis_id)?.proposed_fix||""}:void 0,verification_results:w}}function cs(t){if(!t)return;let e=[/test:\s*(.+)/i,/command:\s*(.+)/i,/reproducer:\s*(.+)/i,/failing test:\s*(.+)/i];for(let n of e){let r=t.match(n);if(r)return r[1]}}function Un(){return async t=>L.allowedTools.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed. Allowed tools: ${L.allowedTools.join(", ")}`}}var Nn=[...L.allowedTools,"Agent"];function ds(){return async t=>Nn.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed for git orchestrator. Allowed tools: ${Nn.join(", ")}`}}async function us(t,e,n,r,o,s){let i=ss(os(),`diagnose-hyp-${t.id}-${Date.now()}`),a;try{await Hn("git",["worktree","add","--detach",i,"HEAD"],{cwd:n}),a=await s.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:`${o}
930
+ Original failure: ${o.failure}`,_;try{_=await W.runToResult(B)}finally{await W.teardown().catch(()=>{})}if(_.status!=="succeeded"||!_.output)throw new Error(`hypothesis synthesis failed: ${C(_)}`);let x=_.output.hypotheses.slice(0,o.maxHypotheses);if(x.length===0)return{reproducer:p,hypotheses:[],verification_results:[]};let{premise_verifications:R,hypotheses_to_test:M}=await cs(x,async y=>{let P=z("shadow-verify");if(!P)throw new Error("shadow-verify skill not registered");return(await P.handler({claims:y,context:`Original failure: ${o.failure}`},e)).verifications});if(M.length===0)return{reproducer:p,hypotheses:x,premise_verifications:R,verification_results:[]};let K=p||o.failure,ee=M.map(y=>fs(y,K,o.repoPath,s,d,u)),k=await Promise.all(ee),E=k.find(y=>y.reproducer_passed);return{reproducer:p,hypotheses:x,premise_verifications:R.length>0?R:void 0,winner:E?{hypothesis_id:E.hypothesis_id,verification_log:E.verification_log,proposed_fix:x.find(y=>y.id===E.hypothesis_id)?.proposed_fix||""}:void 0,verification_results:k}}function us(t){if(!t)return;let e=[/test:\s*(.+)/i,/command:\s*(.+)/i,/reproducer:\s*(.+)/i,/failing test:\s*(.+)/i];for(let n of e){let r=t.match(n);if(r)return r[1]}}function Bn(){return async t=>L.allowedTools.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed. Allowed tools: ${L.allowedTools.join(", ")}`}}var Kn=[...L.allowedTools,"Agent"];function ps(){return async t=>Kn.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed for git orchestrator. Allowed tools: ${Kn.join(", ")}`}}async function fs(t,e,n,r,o,s){let i=as(is(),`diagnose-hyp-${t.id}-${Date.now()}`),a;try{await Nn("git",["worktree","add","--detach",i,"HEAD"],{cwd:n}),a=await s.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:`${o}
931
931
 
932
- You are testing in an isolated worktree at: ${i}`,canUseTool:ps()},idPrefix:`diagnose-verifier-${t.id}`,outputSchema:Kn});let l=`Test this hypothesis:
932
+ You are testing in an isolated worktree at: ${i}`,canUseTool:ms()},idPrefix:`diagnose-verifier-${t.id}`,outputSchema:zn});let l=`Test this hypothesis:
933
933
 
934
934
  Claim: ${t.claim}
935
935
  Location: ${t.location||"unknown"}
936
936
  Proposed fix: ${t.proposed_fix||"unknown"}
937
937
  Reproducer: ${e}
938
938
 
939
- Working directory (isolated): ${i}`,c=await a.runToResult(l);return c.status!=="succeeded"||!c.output?{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Verification failed: ${C(c)}`}:c.output}catch(l){return{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Error during verification: ${l instanceof Error?l.message:String(l)}`}}finally{if(a)try{await a.teardown()}catch{}try{await Hn("git",["worktree","remove","--force",i],{cwd:n})}catch{}}}function ps(){let t=["Edit","Write","Bash","Agent","Task"];return async e=>t.includes(e)?{behavior:"deny",message:`Tool ${e} not allowed in worktree verification. Verification is read-only.`}:L.allowedTools.includes(e)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${e} not allowed. Allowed tools: ${L.allowedTools.join(", ")}`}}var fs={name:"diagnose",description:"Parallel root-cause analysis for bugs and failing tests \u2014 forks research subagents, synthesizes hypotheses, and validates each in isolated worktrees",handler:ls,argumentHint:"<bug-or-failing-test>",whenToUse:"When a test is failing, a bug is reported, or behavior is unexplained \u2014 runs parallel root-cause analysis with hypothesis sub-agents."};W(fs);import{z as V}from"zod";import{execFile as As}from"child_process";import{promisify as Ts}from"util";import{mkdir as Xn,writeFile as Zn}from"fs/promises";import{existsSync as Qn}from"fs";import{join as ne}from"path";import{fileURLToPath as Is}from"url";import{fileURLToPath as ms}from"node:url";import{dirname as gs}from"node:path";var hs=ms(import.meta.url),Sd=gs(hs),ht={name:"qualify",systemPrompt:`---
939
+ Working directory (isolated): ${i}`,c=await a.runToResult(l);return c.status!=="succeeded"||!c.output?{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Verification failed: ${C(c)}`}:c.output}catch(l){return{hypothesis_id:t.id,reproducer_passed:!1,regressions:[],confidence:0,verification_log:`Error during verification: ${l instanceof Error?l.message:String(l)}`}}finally{if(a)try{await a.teardown()}catch{}try{await Nn("git",["worktree","remove","--force",i],{cwd:n})}catch{}}}function ms(){let t=["Edit","Write","Bash","Agent","Task"];return async e=>t.includes(e)?{behavior:"deny",message:`Tool ${e} not allowed in worktree verification. Verification is read-only.`}:L.allowedTools.includes(e)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${e} not allowed. Allowed tools: ${L.allowedTools.join(", ")}`}}var gs={name:"diagnose",description:"Parallel root-cause analysis for bugs and failing tests \u2014 forks research subagents, synthesizes hypotheses, and validates each in isolated worktrees",handler:ds,argumentHint:"<bug-or-failing-test>",whenToUse:"When a test is failing, a bug is reported, or behavior is unexplained \u2014 runs parallel root-cause analysis with hypothesis sub-agents."};Y(gs);import{z as V}from"zod";import{execFile as Is}from"child_process";import{promisify as Cs}from"util";import{mkdir as er,writeFile as tr}from"fs/promises";import{existsSync as Zn}from"fs";import{join as oe}from"path";import{fileURLToPath as Ms}from"url";import{fileURLToPath as hs}from"node:url";import{dirname as ys}from"node:path";var bs=hs(import.meta.url),Ed=ys(bs),bt={name:"qualify",systemPrompt:`---
940
940
  name: qualify
941
941
  description: Gate proposed plugin skills. Approve only real force multipliers. Reject reminders, checklists, best-practice nudges, and generic execution advice. Invoke when evaluating whether a proposed skill deserves top-level status in this plugin.
942
942
  model: sonnet
@@ -1124,6 +1124,18 @@ Where it belongs if not APPROVE.
1124
1124
  ### Rewrite
1125
1125
  Include only if SALVAGE.
1126
1126
 
1127
+ **Format**: For each rubric dimension that triggered the downgrade (Stage 1 \u22642, or Stage 2 dimensions scoring 0\u20131), document:
1128
+ - **Dimension**: name
1129
+ - **Current failure**: one sentence \u2014 what the candidate is missing
1130
+ - **Concrete fix**: one sentence \u2014 what machinery change addresses it (not wording \u2014 machinery: sub-agents, hooks, gates, worktrees, phases)
1131
+ - **Predicted impact**: which rubric score improves, and to what
1132
+
1133
+ Pick the **single strongest combined fix** that addresses the highest-impact dimension. If multiple dimensions failed, prioritize the one whose fix naturally pulls up the others.
1134
+
1135
+ **Discipline**: One rewrite per SALVAGE verdict. If the rewrite lands in SALVAGE again on re-evaluation, the candidate is architecturally misaligned \u2014 escalate to REJECT with placement guidance rather than iterating further.
1136
+
1137
+ **Reference**: See the Stage-2 downgrade calibration example above \u2014 it demonstrates the target specificity: "raise Bounded Damage (dry-run/draft-PR instead of push), Default Reversibility (require confirmation), Assumption Exposure (surface what tests assume before acting)."
1138
+
1127
1139
  ### Emit telemetry
1128
1140
 
1129
1141
  After producing the output above, append one JSONL line to the qualify ledger so scores become a queryable corpus. Do this for every verdict \u2014 APPROVE, SALVAGE, and REJECT \u2014 the ledger is a decision record, not a success log.
@@ -1157,31 +1169,31 @@ If the append fails (permissions, disk full, unwritable path), do not retry and
1157
1169
  - Stage 1 alone would land at SALVAGE (rule 8). Rule 6 fires because Stage 2 \u22648 \u2192 downgrade one tier \u2192 **REJECT**. Rewrite target: raise Bounded Damage (dry-run/draft-PR instead of push), Default Reversibility (require confirmation), Assumption Exposure (surface what tests assume before acting).
1158
1170
 
1159
1171
  Be skeptical. Protect the plugin from fluff. Stage 2 catches patterns that are strong when they work and catastrophic when they don't.
1160
- `,sourcePath:"agent-framework-local/agents/qualify.md"};import{fileURLToPath as ys}from"node:url";import{dirname as bs}from"node:path";var vs=ys(import.meta.url),Td=bs(vs);import{mkdir as Gn,writeFile as zn}from"fs/promises";import{join as Ke}from"path";function ie(){return process.env.HOME||process.env.USERPROFILE||"~"}function ws(){return Ke(ie(),".claude","agent-framework","forge-telemetry.jsonl")}async function J(t){let e=ws(),n=Ke(ie(),".claude","agent-framework");await Gn(n,{recursive:!0});let r=new Date().toISOString().split(".")[0]+"Z",o={timestamp:r,surface:"atlas",...t},s=JSON.stringify(o)+`
1161
- `;return await zn(e,s,{flag:"a"}),r}async function Vn(){let t=Ke(ie(),".claude","agent-framework","ceiling-ledger"),e=Ke(t,"forge-thaw-history.jsonl");await Gn(t,{recursive:!0});let r={timestamp:new Date().toISOString().split(".")[0]+"Z",surface:"atlas",event:"forge.thaw_override",thaw_triggered:!0},o=JSON.stringify(r)+`
1162
- `;await zn(e,o,{flag:"a"})}import{readFile as qn,readdir as ks,writeFile as Ss,mkdir as xs,unlink as Ps}from"fs/promises";import{join as ve}from"path";import{existsSync as Es}from"fs";function yt(){return ve(ie(),".claude","agent-framework","briefs")}async function Wn(t){let e=ve(yt(),t+".md"),n=await qn(e,"utf-8");return{id:t,content:n}}async function Yn(){let t=yt();return Es(t)?(await ks(t,{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".md")).map(r=>r.name.slice(0,-3)):[]}async function bt(t,e){let n=yt(),r=ve(n,t+".md"),o=ve(n,e),s=ve(o,t+".md");await xs(o,{recursive:!0});let i=await qn(r,"utf-8");await Ss(s,i,"utf-8"),await Ps(r)}function Jn(t){let e=t.split(`
1172
+ `,sourcePath:"agent-framework-local/agents/qualify.md"};import{fileURLToPath as vs}from"node:url";import{dirname as ws}from"node:path";var ks=vs(import.meta.url),Cd=ws(ks);import{mkdir as Vn,writeFile as qn}from"fs/promises";import{join as ze}from"path";function le(){return process.env.HOME||process.env.USERPROFILE||"~"}function Ss(){return ze(le(),".claude","agent-framework","forge-telemetry.jsonl")}async function Q(t){let e=Ss(),n=ze(le(),".claude","agent-framework");await Vn(n,{recursive:!0});let r=new Date().toISOString().split(".")[0]+"Z",o={timestamp:r,surface:"atlas",...t},s=JSON.stringify(o)+`
1173
+ `;return await qn(e,s,{flag:"a"}),r}async function Wn(){let t=ze(le(),".claude","agent-framework","ceiling-ledger"),e=ze(t,"forge-thaw-history.jsonl");await Vn(t,{recursive:!0});let r={timestamp:new Date().toISOString().split(".")[0]+"Z",surface:"atlas",event:"forge.thaw_override",thaw_triggered:!0},o=JSON.stringify(r)+`
1174
+ `;await qn(e,o,{flag:"a"})}import{readFile as Yn,readdir as xs,writeFile as Es,mkdir as Ps,unlink as As}from"fs/promises";import{join as ke}from"path";import{existsSync as Ts}from"fs";function vt(){return ke(le(),".claude","agent-framework","briefs")}async function Jn(t){let e=ke(vt(),t+".md"),n=await Yn(e,"utf-8");return{id:t,content:n}}async function Qn(){let t=vt();return Ts(t)?(await xs(t,{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".md")).map(r=>r.name.slice(0,-3)):[]}async function wt(t,e){let n=vt(),r=ke(n,t+".md"),o=ke(n,e),s=ke(o,t+".md");await Ps(o,{recursive:!0});let i=await Yn(r,"utf-8");await Es(s,i,"utf-8"),await As(r)}function Xn(t){let e=t.split(`
1163
1175
  `).map(l=>l.trim()).filter(l=>l),n=e.find(l=>/^(APPROVE|SALVAGE|REJECT)/.test(l));if(!n)return{verdict:"REJECT",feedback:t};let r=n.match(/^(APPROVE|SALVAGE|REJECT)/)?.[1];if(!r)return{verdict:"REJECT",feedback:t};let o=t.match(/score:\s*(\d+)/i),s=o&&o[1]?parseInt(o[1],10):void 0,i=e.indexOf(n),a=e.slice(i+1).join(`
1164
- `).trim();return{verdict:r,score:s,feedback:a||n}}var Cs=Ts(As);function Ms(){let t=process.env.AFK_EVAL_HARNESS_ROOT;if(t){let o=ne(t,"scripts","eval-harness","runner.py");if(Qn(o))return o}let e=Is(import.meta.url),n=ne(e,"../../../.."),r=ne(n,"..","awa-private","scripts","eval-harness","runner.py");if(Qn(r))return r;throw new Error(`Could not find eval-harness runner.py. Tried: ${r}`)}function _s(t){return ne(t,"..","..","..","plugins","awa-private")}function Rs(){let t=process.env.HOME||process.env.USERPROFILE||"~";return ne(t,".claude","agent-framework","ceiling-ledger")}function Ds(t){let e=t.split(`
1165
- `),n=[],r=/^\s+✗\s+(\S+):/;for(let o of e){let s=o.match(r);s&&s[1]&&n.push(s[1])}return n}async function Os(t){let e=Rs(),n=ne(e,"qualifications.jsonl");await Xn(e,{recursive:!0});let o=new Date().toISOString().split(".")[0]+"Z",i=JSON.stringify({timestamp:o,surface:"atlas",refers_to_run_id:t,source:"forge-gate-check-ts"})+`
1166
- `;return await Zn(n,i,{flag:"a"}),o}async function Fs(){let t;try{t=Ms()}catch(l){throw new Error(`Failed to resolve eval-harness runner.py: ${l instanceof Error?l.message:String(l)}`)}let e=_s(t),n="",r="",o=0;try{let l=await Cs("python3",[t,"--plugin-root",e],{timeout:6e4});n=l.stdout||"",r=l.stderr||"",o=0}catch(l){let c=l;if(n=c.stdout||"",r=c.stderr||"",o=typeof c.code=="number"?c.code:1,c.code==="ENOENT"||r&&r.includes("No such file"))throw new Error(`eval-harness runner.py not found at ${t}.`)}let s=o===0?"OPEN":"CLOSED",i=s==="CLOSED"?Ds(n):void 0,a;if(s==="OPEN"){let l=new Date().toISOString().split(".")[0]+"Z";a=await Os(l)}return{gate_status:s,exit_code:o,stdout:n,stderr:r||void 0,tasks_failed:i,ledger_entry_ref:a}}var $s=V.object({iteration:V.number().int().positive(),verdict:V.enum(["APPROVE","SALVAGE","REJECT"]),score:V.number().optional(),feedback:V.string()}),iu=V.object({status:V.enum(["APPROVED","REJECTED","GATE_CLOSED","MAX_ITERATIONS"]),skill_path:V.string().optional(),qualify_verdicts:V.array($s),brief_id:V.string().optional(),telemetry_ref:V.string()});async function Ls(t,e){let n=typeof t=="string"?{brief:t}:typeof t=="object"&&t!==null?t:{},r=n.brief,o=n.forceThaw??!1,s=n.maxIterations??3,i="",a=[],l="REJECTED",c,d;try{let u=await Fs();if(u.gate_status==="CLOSED"&&!o)return i=await J({event:"forge.gate_check",gate_status:"CLOSED"}),{status:"GATE_CLOSED",qualify_verdicts:[],telemetry_ref:i};o&&u.gate_status==="CLOSED"&&(await Vn(),i=await J({event:"forge.thaw_override",gate_status:"CLOSED"})),i=await J({event:"forge.gate_check",gate_status:"OPEN"});let p="",f=!1;if(r)p=r,f=!0;else{let x=await Yn();if(x.length>0){let M=x[0],_=await Wn(M);p=_.content,d=_.id,f=!0}else{if(!e?.sessionId)throw new Error("forge requires parent session for gap discovery");let _=T("forge")["gap-discovery.md"];if(!_)throw new Error("forge skill missing gap-discovery.md prompt");let w=await(await new k().forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:_},idPrefix:"forge-gap-discovery"})).runToResult("Identify the most impactful skill gap.");if(w.status!=="succeeded")throw new Error(`gap discovery failed: ${C(w)}`);if(p=w.message?.content||"",!p)throw new Error("gap discovery returned no concept")}}if(i=await J({event:"forge.brief_loaded",used_brief:f,brief_id:d||null}),!e?.sessionId)throw new Error("forge requires parent session for skill generation");let g=T("forge"),h=g["generate.md"],m=g["system.md"];if(!h)throw new Error("forge skill missing generate.md prompt");if(!m)throw new Error("forge skill missing system.md prompt");let F=await(await new k().forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:m},idPrefix:"forge-generate"})).runToResult(`Generate a new amplifier skill based on this concept:
1176
+ `).trim();return{verdict:r,score:s,feedback:a||n}}var _s=Cs(Is);function Rs(){let t=process.env.AFK_EVAL_HARNESS_ROOT;if(t){let o=oe(t,"scripts","eval-harness","runner.py");if(Zn(o))return o}let e=Ms(import.meta.url),n=oe(e,"../../../.."),r=oe(n,"..","awa-private","scripts","eval-harness","runner.py");if(Zn(r))return r;throw new Error(`Could not find eval-harness runner.py. Tried: ${r}`)}function Ds(t){return oe(t,"..","..","..","plugins","awa-private")}function Os(){let t=process.env.HOME||process.env.USERPROFILE||"~";return oe(t,".claude","agent-framework","ceiling-ledger")}function Fs(t){let e=t.split(`
1177
+ `),n=[],r=/^\s+✗\s+(\S+):/;for(let o of e){let s=o.match(r);s&&s[1]&&n.push(s[1])}return n}async function $s(t){let e=Os(),n=oe(e,"qualifications.jsonl");await er(e,{recursive:!0});let o=new Date().toISOString().split(".")[0]+"Z",i=JSON.stringify({timestamp:o,surface:"atlas",refers_to_run_id:t,source:"forge-gate-check-ts"})+`
1178
+ `;return await tr(n,i,{flag:"a"}),o}async function Ls(){let t;try{t=Rs()}catch(l){throw new Error(`Failed to resolve eval-harness runner.py: ${l instanceof Error?l.message:String(l)}`)}let e=Ds(t),n="",r="",o=0;try{let l=await _s("python3",[t,"--plugin-root",e],{timeout:6e4});n=l.stdout||"",r=l.stderr||"",o=0}catch(l){let c=l;if(n=c.stdout||"",r=c.stderr||"",o=typeof c.code=="number"?c.code:1,c.code==="ENOENT"||r&&r.includes("No such file"))throw new Error(`eval-harness runner.py not found at ${t}.`)}let s=o===0?"OPEN":"CLOSED",i=s==="CLOSED"?Fs(n):void 0,a;if(s==="OPEN"){let l=new Date().toISOString().split(".")[0]+"Z";a=await $s(l)}return{gate_status:s,exit_code:o,stdout:n,stderr:r||void 0,tasks_failed:i,ledger_entry_ref:a}}var js=V.object({iteration:V.number().int().positive(),verdict:V.enum(["APPROVE","SALVAGE","REJECT"]),score:V.number().optional(),feedback:V.string()}),lu=V.object({status:V.enum(["APPROVED","REJECTED","GATE_CLOSED","MAX_ITERATIONS"]),skill_path:V.string().optional(),qualify_verdicts:V.array(js),brief_id:V.string().optional(),telemetry_ref:V.string()});async function Hs(t,e,n){let r=n?.apiKey,o=typeof t=="string"?{brief:t}:typeof t=="object"&&t!==null?t:{},s=o.brief,i=o.forceThaw??!1,a=o.maxIterations??3,l="",c=[],d="REJECTED",u,p;try{let f=await Ls();if(f.gate_status==="CLOSED"&&!i)return l=await Q({event:"forge.gate_check",gate_status:"CLOSED"}),{status:"GATE_CLOSED",qualify_verdicts:[],telemetry_ref:l};i&&f.gate_status==="CLOSED"&&(await Wn(),l=await Q({event:"forge.thaw_override",gate_status:"CLOSED"})),l=await Q({event:"forge.gate_check",gate_status:"OPEN"});let g="",h=!1;if(s)g=s,h=!0;else{let x=await Qn();if(x.length>0){let R=x[0],M=await Jn(R);g=M.content,p=M.id,h=!0}else{if(!e?.sessionId)throw new Error("forge requires parent session for gap discovery");let M=T("forge")["gap-discovery.md"];if(!M)throw new Error("forge skill missing gap-discovery.md prompt");let k=await(await new S({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:M},idPrefix:"forge-gap-discovery"})).runToResult("Identify the most impactful skill gap.");if(k.status!=="succeeded")throw new Error(`gap discovery failed: ${C(k)}`);if(g=k.message?.content||"",!g)throw new Error("gap discovery returned no concept")}}if(l=await Q({event:"forge.brief_loaded",used_brief:h,brief_id:p||null}),!e?.sessionId)throw new Error("forge requires parent session for skill generation");let m=T("forge"),b=m["generate.md"],v=m["system.md"];if(!b)throw new Error("forge skill missing generate.md prompt");if(!v)throw new Error("forge skill missing system.md prompt");let B=await(await new S({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:v},idPrefix:"forge-generate"})).runToResult(`Generate a new amplifier skill based on this concept:
1167
1179
 
1168
- ${p}`);if(F.status!=="succeeded")throw new Error(`skill generation failed: ${C(F)}`);let R=F.message?.content||"";if(!R)throw new Error("skill generation returned no output");for(let x=1;x<=s;x++){let M=ht.systemPrompt;if(!M)throw new Error("qualify agent missing system prompt");let K=await(await new k().forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:M},idPrefix:`forge-qualify-${x}`})).runToResult(`Evaluate this amplifier skill against the force-multiplier criteria:
1180
+ ${g}`);if(B.status!=="succeeded")throw new Error(`skill generation failed: ${C(B)}`);let _=B.message?.content||"";if(!_)throw new Error("skill generation returned no output");for(let x=1;x<=a;x++){let R=bt.systemPrompt;if(!R)throw new Error("qualify agent missing system prompt");let ee=await(await new S({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:R},idPrefix:`forge-qualify-${x}`})).runToResult(`Evaluate this amplifier skill against the force-multiplier criteria:
1169
1181
 
1170
- ${R}`);if(K.status!=="succeeded")throw new Error(`qualify iteration ${x} failed: ${C(K)}`);let w=K.message?.content||"",{verdict:P,score:y,feedback:E}=Jn(w),j={iteration:x,verdict:P,score:y,feedback:E};if(a.push(j),i=await J({event:"forge.qualify_iteration",iteration:x,verdict:P,score:y||null}),P==="APPROVE"){l="APPROVED";break}else if(P==="SALVAGE"&&x<s){let D=g["qualify-rework.md"];if(!D)throw new Error("forge skill missing qualify-rework.md prompt");let oe=D.replace("{feedback}",E).replace("{original_skill}",R),se=await(await new k().forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:oe},idPrefix:`forge-rework-${x}`})).runToResult("Refine the skill based on the feedback.");if(se.status!=="succeeded")throw new Error(`rework iteration ${x} failed: ${C(se)}`);if(R=se.message?.content||"",!R)throw new Error(`rework iteration ${x} returned no output`)}else P==="REJECT"&&x>=s&&(l="MAX_ITERATIONS")}if(l==="APPROVED"){let x=R.match(/^name:\s*([^\n]+)/m),M=x&&x[1]?x[1].trim().replace(/^["']|["']$/g,""):"unknown",_=ne(ie(),".claude","agent-framework-local","skills",M);await Xn(_,{recursive:!0});let B=ne(_,"SKILL.md");await Zn(B,R,"utf-8"),c=B,f&&d&&await bt(d,"consumed"),i=await J({event:"forge.complete",status:"APPROVED",skill_name:M,iterations:a.length})}else l==="MAX_ITERATIONS"&&(f&&d&&await bt(d,"failed"),i=await J({event:"forge.complete",status:"MAX_ITERATIONS",iterations:a.length}))}catch(u){throw i=await J({event:"forge.error",error:u instanceof Error?u.message:String(u)}),u}return{status:l,skill_path:c,qualify_verdicts:a,brief_id:d,telemetry_ref:i}}var js={name:"forge",description:'Creates new amplifier skills gated by forge-gate-check, with autonomous gap discovery, skill generation, and qualify iteration loop \u22643\xD7. Writes approved skills and appends telemetry to shared JSONL with surface: "atlas".',handler:Ls,argumentHint:"[--brief <path>]",whenToUse:"When the user wants to grow the plugin with a new amplifier skill \u2014 autonomously generates and validates one.",flags:["--brief"]};W(js);var Hs={name:"bash",description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run in the user's default shell. Long-running commands should use timeout_ms. Output is capped at ~100KB; excess is truncated with a notice.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds (default 120000, max 600000). The command is killed if it exceeds this duration."}},required:["command"]}},Us={name:"read_file",description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},Ns={name:"write_file",description:"Write content to a file, creating it if it does not exist or overwriting if it does. Parent directories are created automatically. Prefer edit_file for modifying existing files \u2014 use write_file only for new files or complete rewrites.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"The full content to write to the file."}},required:["file_path","content"]}},Bs={name:"edit_file",description:"Perform an exact string replacement in a file. Finds old_string and replaces it with new_string. The edit fails if old_string is not found or matches multiple locations (unless replace_all is true). Always use read_file first to verify the exact content before editing.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit."},old_string:{type:"string",description:"The exact string to find and replace. Must match file content exactly."},new_string:{type:"string",description:"The replacement string."},replace_all:{type:"boolean",description:"If true, replace all occurrences. If false (default), fail when multiple matches exist."}},required:["file_path","old_string","new_string"]}},Ks={name:"glob",description:'Find files matching a glob pattern. Returns matching file paths, capped at 500 results. Use for discovering files before reading them. Patterns follow standard glob syntax (e.g., "src/**/*.ts", "*.json").',input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "src/**/*.ts").'},path:{type:"string",description:"Base directory to search from. Defaults to the current working directory."}},required:["pattern"]}},Gs={name:"grep",description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Uses grep -rn (or ripgrep if available). Output is capped to prevent overflow. Use for finding symbols, strings, or patterns across the codebase.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (basic regex by default)."},path:{type:"string",description:"Directory or file to search. Defaults to current working directory."},include:{type:"string",description:'File glob to restrict search (e.g., "*.ts"). Passed as --include to grep.'}},required:["pattern"]}},zs={name:"list_directory",description:"List the contents of a directory. Returns file and subdirectory names with type annotations (directories end with /). Use for exploring project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the directory to list."}},required:["path"]}},er={name:"agent",description:"Dispatch a subtask to an independent agent session. The agent runs with its own conversation context and tool access. Use for tasks that benefit from isolated context (research, parallel work, specialized focus). The agent runs to completion and returns its final response.",input_schema:{type:"object",properties:{prompt:{type:"string",description:"The task for the agent to perform."},model:{type:"string",description:"Model for the agent. Defaults to parent session model. Override per-call to right-size cost vs. capability \u2014 `haiku` (cheapest/fastest), `sonnet` (general-use), `opus` (most capable). Append `_1m` (e.g. `sonnet_1m`) for 1M-context variants. Full model IDs are also accepted."},max_turns:{type:"number",description:"Maximum conversation turns (default 10, max 50)."},id_prefix:{type:"string",description:"Label prefix for log correlation."}},required:["prompt"]}},tr={name:"skill",description:"Invoke a registered skill by name. Skills are specialized capabilities that dispatch subagents with domain-specific prompts. Check the system prompt for the list of available skills and their descriptions.",input_schema:{type:"object",properties:{name:{type:"string",description:'Skill name (e.g., "mint", "diagnose", "shadow-verify").'},arguments:{type:"string",description:"Arguments to pass to the skill."}},required:["name"]}},Ge=[Hs,Us,Ns,Bs,Ks,Gs,zs],we=Ge.map(t=>t.name);import{readFileSync as ei,existsSync as ir}from"fs";import{join as ar}from"path";import{config as ti}from"dotenv";var nr={opus:"claude-opus-4-7",opus_1m:"claude-opus-4-7",sonnet:"claude-sonnet-4-6",sonnet_1m:"claude-sonnet-4-6",haiku:"claude-haiku-4-5-20251001"};function ze(t){return t in nr}function rr(t){let e=nr[t];if(!e)throw new Error(`Invalid model: ${t}`);return e}function ae(t){if(t!==void 0)return typeof t=="string"&&ze(t)?rr(t):t}import{execFileSync as Vs}from"child_process";import{existsSync as qs,readFileSync as Ws}from"fs";import{homedir as Ys,userInfo as Js}from"os";import{join as Qs}from"path";function or(){let t=Xs();if(t===void 0)return;let e=Zs(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}function Xs(){if(process.platform==="darwin")try{return Vs("security",["find-generic-password","-s","Claude Code-credentials","-a",Js().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=Qs(Ys(),".claude",".credentials.json");if(!qs(t))return;try{return Ws(t,"utf-8")}catch{return}}}function Zs(t){let e;try{e=JSON.parse(t)}catch{return}if(typeof e!="object"||e===null)return;let n=e.claudeAiOauth;if(typeof n!="object"||n===null)return;let r=n,o=r.accessToken;if(typeof o!="string"||o.length===0)return;let s=r.expiresAt,i={accessToken:o};return typeof s=="number"&&(i.expiresAt=s),i}var Ve={model:"sonnet",maxTokens:4096,temperature:1},sr=!1;function vt(){return process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||or()}function ni(){if(!sr){let r=[ar(process.cwd(),".env"),xn(),Pn()];for(let o of r)if(ir(o)){ti({path:o});break}sr=!0}let t={},e=vt();e!==void 0&&(t.apiKey=e);let n=process.env.AFK_MODEL??process.env.CLAUDE_MODEL;if(n){let r=n.toLowerCase();t.model=ze(r)?r:n}if(process.env.AFK_MAX_TOKENS&&(t.maxTokens=parseInt(process.env.AFK_MAX_TOKENS,10)),process.env.AFK_TEMPERATURE&&(t.temperature=parseFloat(process.env.AFK_TEMPERATURE)),process.env.AFK_SYSTEM_PROMPT&&(t.systemPrompt=process.env.AFK_SYSTEM_PROMPT),process.env.AFK_AUTO_ROUTING){let r=process.env.AFK_AUTO_ROUTING.toLowerCase()==="true";t.autoRouting={interactive:r,chat:r,telegram:r,daemon:r}}return t}function ri(){let t=[ar(process.cwd(),"afk.config.json"),dt(),ut()];for(let e of t)if(ir(e))try{let n=ei(e,"utf-8"),r=JSON.parse(n),o={};if(typeof r.model=="string"&&r.model.length>0&&(o.model=(ze(r.model),r.model)),typeof r.maxTokens=="number"&&(o.maxTokens=r.maxTokens),typeof r.temperature=="number"&&(o.temperature=r.temperature),r.systemPrompt&&(o.systemPrompt=r.systemPrompt),r.autoRouting&&typeof r.autoRouting=="object"){let s={};typeof r.autoRouting.interactive=="boolean"&&(s.interactive=r.autoRouting.interactive),typeof r.autoRouting.chat=="boolean"&&(s.chat=r.autoRouting.chat),typeof r.autoRouting.telegram=="boolean"&&(s.telegram=r.autoRouting.telegram),typeof r.autoRouting.daemon=="boolean"&&(s.daemon=r.autoRouting.daemon),o.autoRouting=s}if(r.daemon&&typeof r.daemon=="object"){let s={};typeof r.daemon.task=="string"&&(s.task=r.daemon.task),typeof r.daemon.taskId=="string"&&(s.taskId=r.daemon.taskId),o.daemon=s}return o}catch(n){console.error(`Warning: Failed to parse ${e}:`,n)}return{}}function lr(t){let e=ni(),n=ri(),r={...Ve,...e,...n,...t};return{model:r.model??Ve.model,maxTokens:r.maxTokens??Ve.maxTokens,temperature:r.temperature??Ve.temperature,...r.apiKey!==void 0?{apiKey:r.apiKey}:{},...r.systemPrompt!==void 0?{systemPrompt:r.systemPrompt}:{},...r.autoRouting!==void 0?{autoRouting:r.autoRouting}:{},...r.daemon!==void 0?{daemon:r.daemon}:{}}}function $(){return vt()}function wt(){let t=process.env.AFK_DEFAULT_SUBAGENT_MODEL;return!t||t.length===0?"sonnet":t}function oi(t){if(t===void 0)return;if(t==="max")return Number.POSITIVE_INFINITY;if(t===""||t==="NaN")throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Expected a positive integer or 'max'.`);if(!/^\d+$/.test(t))throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Expected a positive integer or 'max'.`);let e=Number(t);if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Must be a positive integer.`);return e}function cr(){return oi(process.env.AFK_MAX_OUTPUT_TOKENS)}async function dr(t,e){let r=T("mint")["spec.md"];if(!r)throw new Error("mint skill missing spec.md prompt");let i=await(await new k().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:$()},idPrefix:"mint-spec"})).runToResult(`Create a detailed specification for: ${t}`);if(i.status!=="succeeded"||!i.message)throw new Error(`spec phase failed: ${C(i)}`);return i.message.content}async function ur(t,e){let r=T("mint")["research.md"];if(!r)throw new Error("mint skill missing research.md prompt");let i=await(await new k().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:$()},idPrefix:"mint-research"})).runToResult(`Gather context and research for this specification:
1182
+ ${_}`);if(ee.status!=="succeeded")throw new Error(`qualify iteration ${x} failed: ${C(ee)}`);let k=ee.message?.content||"",{verdict:E,score:y,feedback:P}=Xn(k),j={iteration:x,verdict:E,score:y,feedback:P};if(c.push(j),l=await Q({event:"forge.qualify_iteration",iteration:x,verdict:E,score:y||null}),E==="APPROVE"){d="APPROVED";break}else if(E==="SALVAGE"&&x<a){let D=m["qualify-rework.md"];if(!D)throw new Error("forge skill missing qualify-rework.md prompt");let ie=D.replace("{feedback}",P).replace("{original_skill}",_),ae=await(await new S({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:ie},idPrefix:`forge-rework-${x}`})).runToResult("Refine the skill based on the feedback.");if(ae.status!=="succeeded")throw new Error(`rework iteration ${x} failed: ${C(ae)}`);if(_=ae.message?.content||"",!_)throw new Error(`rework iteration ${x} returned no output`)}else E==="REJECT"&&x>=a&&(d="MAX_ITERATIONS")}if(d==="APPROVED"){let x=_.match(/^name:\s*([^\n]+)/m),R=x&&x[1]?x[1].trim().replace(/^["']|["']$/g,""):"unknown",M=oe(le(),".claude","agent-framework-local","skills",R);await er(M,{recursive:!0});let K=oe(M,"SKILL.md");await tr(K,_,"utf-8"),u=K,h&&p&&await wt(p,"consumed"),l=await Q({event:"forge.complete",status:"APPROVED",skill_name:R,iterations:c.length})}else d==="MAX_ITERATIONS"&&(h&&p&&await wt(p,"failed"),l=await Q({event:"forge.complete",status:"MAX_ITERATIONS",iterations:c.length}))}catch(f){throw l=await Q({event:"forge.error",error:f instanceof Error?f.message:String(f)}),f}return{status:d,skill_path:u,qualify_verdicts:c,brief_id:p,telemetry_ref:l}}var Us={name:"forge",description:'Creates new amplifier skills gated by forge-gate-check, with autonomous gap discovery, skill generation, and qualify iteration loop \u22643\xD7. Writes approved skills and appends telemetry to shared JSONL with surface: "atlas".',handler:Hs,argumentHint:"[--brief <path>]",whenToUse:"When the user wants to grow the plugin with a new amplifier skill \u2014 autonomously generates and validates one.",flags:["--brief"]};Y(Us);var Ns={name:"bash",description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run in the user's default shell. Long-running commands should use timeout_ms. Output is capped at ~100KB; excess is truncated with a notice.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds (default 120000, max 600000). The command is killed if it exceeds this duration."}},required:["command"]}},Bs={name:"read_file",description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},Ks={name:"write_file",description:"Write content to a file, creating it if it does not exist or overwriting if it does. Parent directories are created automatically. Prefer edit_file for modifying existing files \u2014 use write_file only for new files or complete rewrites.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"The full content to write to the file."}},required:["file_path","content"]}},Gs={name:"edit_file",description:"Perform an exact string replacement in a file. Finds old_string and replaces it with new_string. The edit fails if old_string is not found or matches multiple locations (unless replace_all is true). Always use read_file first to verify the exact content before editing.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit."},old_string:{type:"string",description:"The exact string to find and replace. Must match file content exactly."},new_string:{type:"string",description:"The replacement string."},replace_all:{type:"boolean",description:"If true, replace all occurrences. If false (default), fail when multiple matches exist."}},required:["file_path","old_string","new_string"]}},zs={name:"glob",description:'Find files matching a glob pattern. Returns matching file paths, capped at 500 results. Use for discovering files before reading them. Patterns follow standard glob syntax (e.g., "src/**/*.ts", "*.json").',input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "src/**/*.ts").'},path:{type:"string",description:"Base directory to search from. Defaults to the current working directory."}},required:["pattern"]}},Vs={name:"grep",description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Uses grep -rn (or ripgrep if available). Output is capped to prevent overflow. Use for finding symbols, strings, or patterns across the codebase.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (basic regex by default)."},path:{type:"string",description:"Directory or file to search. Defaults to current working directory."},include:{type:"string",description:'File glob to restrict search (e.g., "*.ts"). Passed as --include to grep.'}},required:["pattern"]}},qs={name:"list_directory",description:"List the contents of a directory. Returns file and subdirectory names with type annotations (directories end with /). Use for exploring project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the directory to list."}},required:["path"]}},nr={name:"agent",description:"Dispatch a subtask to an independent agent session. The agent runs with its own conversation context and tool access. Use for tasks that benefit from isolated context (research, parallel work, specialized focus). The agent runs to completion and returns its final response.",input_schema:{type:"object",properties:{prompt:{type:"string",description:"The task for the agent to perform."},model:{type:"string",description:"Model for the agent. Defaults to parent session model. Override per-call to right-size cost vs. capability \u2014 `haiku` (cheapest/fastest), `sonnet` (general-use), `opus` (most capable). Append `_1m` (e.g. `sonnet_1m`) for 1M-context variants. Full model IDs are also accepted."},max_turns:{type:"number",description:"Maximum conversation turns (default 10, max 50)."},id_prefix:{type:"string",description:"Label prefix for log correlation."}},required:["prompt"]}},rr={name:"skill",description:"Invoke a registered skill by name. Skills are specialized capabilities that dispatch subagents with domain-specific prompts. Check the system prompt for the list of available skills and their descriptions.",input_schema:{type:"object",properties:{name:{type:"string",description:'Skill name (e.g., "mint", "diagnose", "shadow-verify").'},arguments:{type:"string",description:"Arguments to pass to the skill."}},required:["name"]}},Ve=[Ns,Bs,Ks,Gs,zs,Vs,qs],Se=Ve.map(t=>t.name);import{readFileSync as ni,existsSync as lr}from"fs";import{join as cr}from"path";import{config as ri}from"dotenv";var or={opus:"claude-opus-4-7",opus_1m:"claude-opus-4-7",sonnet:"claude-sonnet-4-6",sonnet_1m:"claude-sonnet-4-6",haiku:"claude-haiku-4-5-20251001"};function qe(t){return t in or}function sr(t){let e=or[t];if(!e)throw new Error(`Invalid model: ${t}`);return e}function ce(t){if(t!==void 0)return typeof t=="string"&&qe(t)?sr(t):t}import{execFileSync as Ws}from"child_process";import{existsSync as Ys,readFileSync as Js}from"fs";import{homedir as Qs,userInfo as Xs}from"os";import{join as Zs}from"path";function ir(){let t=ei();if(t===void 0)return;let e=ti(t);if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt<=Date.now()){process.stderr.write("agent-afk: Claude Code OAuth token in keychain is expired. Run `claude login` to refresh.\n");return}return e.accessToken}}function ei(){if(process.platform==="darwin")try{return Ws("security",["find-generic-password","-s","Claude Code-credentials","-a",Xs().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=Zs(Qs(),".claude",".credentials.json");if(!Ys(t))return;try{return Js(t,"utf-8")}catch{return}}}function ti(t){let e;try{e=JSON.parse(t)}catch{return}if(typeof e!="object"||e===null)return;let n=e.claudeAiOauth;if(typeof n!="object"||n===null)return;let r=n,o=r.accessToken;if(typeof o!="string"||o.length===0)return;let s=r.expiresAt,i={accessToken:o};return typeof s=="number"&&(i.expiresAt=s),i}var We={model:"sonnet",maxTokens:4096,temperature:1},ar=!1;function kt(){return process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||ir()}function oi(){if(!ar){let r=[cr(process.cwd(),".env"),Pn(),An()];for(let o of r)if(lr(o)){ri({path:o});break}ar=!0}let t={},e=kt();e!==void 0&&(t.apiKey=e);let n=process.env.AFK_MODEL??process.env.CLAUDE_MODEL;if(n){let r=n.toLowerCase();t.model=qe(r)?r:n}if(process.env.AFK_MAX_TOKENS&&(t.maxTokens=parseInt(process.env.AFK_MAX_TOKENS,10)),process.env.AFK_TEMPERATURE&&(t.temperature=parseFloat(process.env.AFK_TEMPERATURE)),process.env.AFK_SYSTEM_PROMPT&&(t.systemPrompt=process.env.AFK_SYSTEM_PROMPT),process.env.AFK_AUTO_ROUTING){let r=process.env.AFK_AUTO_ROUTING.toLowerCase()==="true";t.autoRouting={interactive:r,chat:r,telegram:r,daemon:r}}return t}function si(){let t=[cr(process.cwd(),"afk.config.json"),pt(),ft()];for(let e of t)if(lr(e))try{let n=ni(e,"utf-8"),r=JSON.parse(n),o={};if(typeof r.model=="string"&&r.model.length>0&&(o.model=(qe(r.model),r.model)),typeof r.maxTokens=="number"&&(o.maxTokens=r.maxTokens),typeof r.temperature=="number"&&(o.temperature=r.temperature),r.systemPrompt&&(o.systemPrompt=r.systemPrompt),r.autoRouting&&typeof r.autoRouting=="object"){let s={};typeof r.autoRouting.interactive=="boolean"&&(s.interactive=r.autoRouting.interactive),typeof r.autoRouting.chat=="boolean"&&(s.chat=r.autoRouting.chat),typeof r.autoRouting.telegram=="boolean"&&(s.telegram=r.autoRouting.telegram),typeof r.autoRouting.daemon=="boolean"&&(s.daemon=r.autoRouting.daemon),o.autoRouting=s}if(r.daemon&&typeof r.daemon=="object"){let s={};typeof r.daemon.task=="string"&&(s.task=r.daemon.task),typeof r.daemon.taskId=="string"&&(s.taskId=r.daemon.taskId),o.daemon=s}return o}catch(n){console.error(`Warning: Failed to parse ${e}:`,n)}return{}}function dr(t){let e=oi(),n=si(),r={...We,...e,...n,...t};return{model:r.model??We.model,maxTokens:r.maxTokens??We.maxTokens,temperature:r.temperature??We.temperature,...r.apiKey!==void 0?{apiKey:r.apiKey}:{},...r.systemPrompt!==void 0?{systemPrompt:r.systemPrompt}:{},...r.autoRouting!==void 0?{autoRouting:r.autoRouting}:{},...r.daemon!==void 0?{daemon:r.daemon}:{}}}function $(){return kt()}function St(){let t=process.env.AFK_DEFAULT_SUBAGENT_MODEL;return!t||t.length===0?"sonnet":t}function ii(t){if(t===void 0)return;if(t==="max")return Number.POSITIVE_INFINITY;if(t===""||t==="NaN")throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Expected a positive integer or 'max'.`);if(!/^\d+$/.test(t))throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Expected a positive integer or 'max'.`);let e=Number(t);if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Must be a positive integer.`);return e}function ur(){return ii(process.env.AFK_MAX_OUTPUT_TOKENS)}async function pr(t,e){let r=T("mint")["spec.md"];if(!r)throw new Error("mint skill missing spec.md prompt");let i=await(await new S().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:$()},idPrefix:"mint-spec"})).runToResult(`Create a detailed specification for: ${t}`);if(i.status!=="succeeded"||!i.message)throw new Error(`spec phase failed: ${C(i)}`);return i.message.content}async function fr(t,e){let r=T("mint")["research.md"];if(!r)throw new Error("mint skill missing research.md prompt");let i=await(await new S().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:$()},idPrefix:"mint-research"})).runToResult(`Gather context and research for this specification:
1171
1183
 
1172
- ${t}`);if(i.status!=="succeeded"||!i.message)throw new Error(`research phase failed: ${C(i)}`);return i.message.content}async function pr(t,e,n){let o=T("mint")["plan.md"];if(!o)throw new Error("mint skill missing plan.md prompt");let i=await new k().forkSubagent({parent:{sessionId:n},config:{model:"sonnet",systemPrompt:o,apiKey:$()},idPrefix:"mint-plan"}),a=`Specification:
1184
+ ${t}`);if(i.status!=="succeeded"||!i.message)throw new Error(`research phase failed: ${C(i)}`);return i.message.content}async function mr(t,e,n){let o=T("mint")["plan.md"];if(!o)throw new Error("mint skill missing plan.md prompt");let i=await new S().forkSubagent({parent:{sessionId:n},config:{model:"sonnet",systemPrompt:o,apiKey:$()},idPrefix:"mint-plan"}),a=`Specification:
1173
1185
  ${t}
1174
1186
 
1175
1187
  Research findings:
1176
1188
  ${e}
1177
1189
 
1178
- Create a detailed implementation plan based on the spec and research.`,l=await i.runToResult(a);if(l.status!=="succeeded"||!l.message)throw new Error(`plan phase failed: ${C(l)}`);return l.message.content}function si(t){let e=t.match(/\.\w+\s/g)||[],n=t.match(/Files?:\s*(.+?)(?:\n|$)/gi)||[],r=e.length;for(let o of n){let s=o.replace(/Files?:\s*/i,"").split(/[,;]/g).filter(i=>i.trim().length>0);r+=s.length}return r}async function fr(t,e){if(si(t)<3)return null;try{return await z("parallelize").handler({plan:t})}catch(r){return console.warn(`Parallelize dispatch failed: ${r instanceof Error?r.message:String(r)}`),null}}import{z as X}from"zod";function ue(t){let e=le();e&&e({type:"panel",spec:t},{subagentId:"__main__"})}var ii=X.object({status:X.enum(["PASS","FAIL"]),status_reason:X.string().optional(),files_changed:X.array(X.string()),tests_passed:X.boolean(),build_passed:X.boolean().optional(),verification_passed:X.boolean().optional(),notes:X.string()});async function mr(t,e,n){let o=T("mint")["build.md"];if(!o)throw new Error("mint skill missing build.md prompt");let i=await new k().forkSubagent({parent:{sessionId:n},config:{model:"sonnet",systemPrompt:o,apiKey:$()},idPrefix:"mint-build",outputSchema:ii}),a=`Implementation plan:
1190
+ Create a detailed implementation plan based on the spec and research.`,l=await i.runToResult(a);if(l.status!=="succeeded"||!l.message)throw new Error(`plan phase failed: ${C(l)}`);return l.message.content}function ai(t){let e=t.match(/\.\w+\s/g)||[],n=t.match(/Files?:\s*(.+?)(?:\n|$)/gi)||[],r=e.length;for(let o of n){let s=o.replace(/Files?:\s*/i,"").split(/[,;]/g).filter(i=>i.trim().length>0);r+=s.length}return r}async function gr(t,e){if(ai(t)<3)return null;try{return await z("parallelize").handler({plan:t})}catch(r){return console.warn(`Parallelize dispatch failed: ${r instanceof Error?r.message:String(r)}`),null}}import{z as Z}from"zod";function fe(t){let e=de();e&&e({type:"panel",spec:t},{subagentId:"__main__"})}var li=Z.object({status:Z.enum(["PASS","FAIL"]),status_reason:Z.string().optional(),files_changed:Z.array(Z.string()),tests_passed:Z.boolean(),build_passed:Z.boolean().optional(),verification_passed:Z.boolean().optional(),notes:Z.string()});async function hr(t,e,n){let o=T("mint")["build.md"];if(!o)throw new Error("mint skill missing build.md prompt");let i=await new S().forkSubagent({parent:{sessionId:n},config:{model:"sonnet",systemPrompt:o,apiKey:$()},idPrefix:"mint-build",outputSchema:li}),a=`Implementation plan:
1179
1191
  ${t}
1180
1192
 
1181
1193
  `+(e?`Wave orchestration plan:
1182
1194
  ${JSON.stringify(e,null,2)}
1183
1195
 
1184
- `:"")+"Execute the implementation plan following TDD (test-first) principles.",l=await i.runToResult(a);if(l.status!=="succeeded"||!l.output)throw new Error(`build phase failed: ${C(l)}`);let c=l.output,d={filesChanged:c.files_changed,testsPassed:c.tests_passed,notes:c.notes};return ue({kind:"checkpoint",title:"build",body:[`Files changed: ${d.filesChanged.length}`,`Tests: ${d.testsPassed?"passed":"failed"}`,"Next: verify"]}),d}import{z as pe}from"zod";var ai=pe.object({status:pe.enum(["PASS","FAIL"]),status_reason:pe.string().optional(),issues:pe.array(pe.string()).default([]),summary:pe.string().optional()});async function kt(t,e,n,r,o){let i=await new k().forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:o,apiKey:$()},idPrefix:`mint-verify-${t}`,outputSchema:ai}),a=`Plan:
1196
+ `:"")+"Execute the implementation plan following TDD (test-first) principles.",l=await i.runToResult(a);if(l.status!=="succeeded"||!l.output)throw new Error(`build phase failed: ${C(l)}`);let c=l.output,d={filesChanged:c.files_changed,testsPassed:c.tests_passed,notes:c.notes};return fe({kind:"checkpoint",title:"build",body:[`Files changed: ${d.filesChanged.length}`,`Tests: ${d.testsPassed?"passed":"failed"}`,"Next: verify"]}),d}import{z as me}from"zod";var ci=me.object({status:me.enum(["PASS","FAIL"]),status_reason:me.string().optional(),issues:me.array(me.string()).default([]),summary:me.string().optional()});async function xt(t,e,n,r,o){let i=await new S().forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:o,apiKey:$()},idPrefix:`mint-verify-${t}`,outputSchema:ci}),a=`Plan:
1185
1197
  ${e}
1186
1198
 
1187
1199
  Build results:
@@ -1189,12 +1201,12 @@ ${JSON.stringify(n,null,2)}
1189
1201
 
1190
1202
  Mode: ${t}
1191
1203
 
1192
- Run ${t} verification on the implementation.`,l;try{l=await i.runToResult(a)}finally{await i.teardown().catch(()=>{})}if(l.status!=="succeeded"||!l.output)return{passed:!1,issues:[`${t} verification failed: ${C(l)}`]};let c=l.output,d=c.status==="PASS";return{passed:d,issues:d?void 0:c.issues}}async function qe(t,e,n){let o=T("mint")["verify.md"];if(!o)throw new Error("mint skill missing verify.md prompt");let[s,i,a]=await Promise.all([kt("test",t,e,n,o),kt("lint",t,e,n,o),kt("design-review",t,e,n,o)]),l=[];s.issues&&l.push(...s.issues),i.issues&&l.push(...i.issues),a.issues&&l.push(...a.issues);let c={testsPassed:s.passed,lintPassed:i.passed,designReviewPassed:a.passed,...l.length>0?{issues:l}:{}},d=c.testsPassed&&c.lintPassed&&c.designReviewPassed,u=p=>p?"passed":"failed";return ue({kind:d?"checkpoint":"diagnosis",title:"verify",body:[`Tests: ${u(c.testsPassed)} \xB7 Lint: ${u(c.lintPassed)}`,`Design review: ${u(c.designReviewPassed)}`,...d?["Next: ship"]:[`Issues: ${l.length} (heal loop will retry)`]]}),c}async function gr(t,e,n,r,o){if(n.testsPassed&&n.lintPassed&&n.designReviewPassed)return{healed:!0,newHealIterations:r,newVerifyResults:n};if(r>=2)return{healed:!1,newHealIterations:r,newVerifyResults:n};try{let s=z("diagnose"),i=`Verification failures:
1204
+ Run ${t} verification on the implementation.`,l;try{l=await i.runToResult(a)}finally{await i.teardown().catch(()=>{})}if(l.status!=="succeeded"||!l.output)return{passed:!1,issues:[`${t} verification failed: ${C(l)}`]};let c=l.output,d=c.status==="PASS";return{passed:d,issues:d?void 0:c.issues}}async function Ye(t,e,n){let o=T("mint")["verify.md"];if(!o)throw new Error("mint skill missing verify.md prompt");let[s,i,a]=await Promise.all([xt("test",t,e,n,o),xt("lint",t,e,n,o),xt("design-review",t,e,n,o)]),l=[];s.issues&&l.push(...s.issues),i.issues&&l.push(...i.issues),a.issues&&l.push(...a.issues);let c={testsPassed:s.passed,lintPassed:i.passed,designReviewPassed:a.passed,...l.length>0?{issues:l}:{}},d=c.testsPassed&&c.lintPassed&&c.designReviewPassed,u=p=>p?"passed":"failed";return fe({kind:d?"checkpoint":"diagnosis",title:"verify",body:[`Tests: ${u(c.testsPassed)} \xB7 Lint: ${u(c.lintPassed)}`,`Design review: ${u(c.designReviewPassed)}`,...d?["Next: ship"]:[`Issues: ${l.length} (heal loop will retry)`]]}),c}async function yr(t,e,n,r,o){if(n.testsPassed&&n.lintPassed&&n.designReviewPassed)return{healed:!0,newHealIterations:r,newVerifyResults:n};if(r>=2)return{healed:!1,newHealIterations:r,newVerifyResults:n};try{let s=z("diagnose"),i=`Verification failures:
1193
1205
  Tests: ${n.testsPassed?"PASS":"FAIL"}
1194
1206
  Lint: ${n.lintPassed?"PASS":"FAIL"}
1195
1207
  Design: ${n.designReviewPassed?"PASS":"FAIL"}
1196
1208
  Issues: ${n.issues?.join(`
1197
- `)||"none"}`,a=await s.handler({failure:i,repoPath:process.cwd(),context:t}),l="";if(typeof a=="object"&&a!==null&&"winner"in a&&typeof a.winner=="object"&&a.winner!==null){let F=a.winner;typeof F.proposed_fix=="string"&&(l=F.proposed_fix)}let d=T("mint")["heal.md"];if(!d)throw new Error("mint skill missing heal.md prompt");let p=await new k().forkSubagent({parent:{sessionId:o.sessionId},config:{model:"sonnet",systemPrompt:d,apiKey:$()},idPrefix:"mint-heal"}),f=n.issues?.join(`
1209
+ `)||"none"}`,a=await s.handler({failure:i,repoPath:process.cwd(),context:t}),l="";if(typeof a=="object"&&a!==null&&"winner"in a&&typeof a.winner=="object"&&a.winner!==null){let F=a.winner;typeof F.proposed_fix=="string"&&(l=F.proposed_fix)}let d=T("mint")["heal.md"];if(!d)throw new Error("mint skill missing heal.md prompt");let p=await new S().forkSubagent({parent:{sessionId:o.sessionId},config:{model:"sonnet",systemPrompt:d,apiKey:$()},idPrefix:"mint-heal"}),f=n.issues?.join(`
1198
1210
  `)??"none",g=`Plan:
1199
1211
  ${t}
1200
1212
 
@@ -1204,7 +1216,7 @@ ${l}
1204
1216
  Verification issues:
1205
1217
  ${f}
1206
1218
 
1207
- Apply the fix and update the implementation.`,h=await p.runToResult(g);if(h.status!=="succeeded"||!h.message)throw new Error(`heal phase failed: ${C(h)}`);let m=/^\s*FIX_APPLIED:\s*(true|false)/im.exec(h.message.content)?.[1]?.toLowerCase()==="true",b=r+1;if(!m)return{healed:!1,newHealIterations:b,newVerifyResults:n};if(!o.sessionId)throw new Error("Parent session ID required for verification");let S=await qe(t,e,o.sessionId);return{healed:S.testsPassed&&S.lintPassed&&S.designReviewPassed,newHealIterations:b,newVerifyResults:S}}catch{return{healed:!1,newHealIterations:r+1,newVerifyResults:n}}}async function hr(t,e){let r=T("mint")["ship.md"];if(!r)throw new Error("mint skill missing ship.md prompt");let s=await new k().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:$()},idPrefix:"mint-ship"}),i=`Idea: ${t.idea}
1219
+ Apply the fix and update the implementation.`,h=await p.runToResult(g);if(h.status!=="succeeded"||!h.message)throw new Error(`heal phase failed: ${C(h)}`);let m=/^\s*FIX_APPLIED:\s*(true|false)/im.exec(h.message.content)?.[1]?.toLowerCase()==="true",b=r+1;if(!m)return{healed:!1,newHealIterations:b,newVerifyResults:n};if(!o.sessionId)throw new Error("Parent session ID required for verification");let v=await Ye(t,e,o.sessionId);return{healed:v.testsPassed&&v.lintPassed&&v.designReviewPassed,newHealIterations:b,newVerifyResults:v}}catch{return{healed:!1,newHealIterations:r+1,newVerifyResults:n}}}async function br(t,e){let r=T("mint")["ship.md"];if(!r)throw new Error("mint skill missing ship.md prompt");let s=await new S().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:$()},idPrefix:"mint-ship"}),i=`Idea: ${t.idea}
1208
1220
 
1209
1221
  Specification:
1210
1222
  ${t.spec}
@@ -1218,23 +1230,23 @@ ${JSON.stringify(t.buildResults,null,2)}
1218
1230
  Verification results:
1219
1231
  ${JSON.stringify(t.verifyResults,null,2)}
1220
1232
 
1221
- Create a ship-ready summary with next steps.`,a=await s.runToResult(i);if(a.status!=="succeeded"||!a.message)throw new Error(`ship phase failed: ${C(a)}`);let l=t.buildResults?.filesChanged.length??0,c=t.healIterations;return ue({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${l}`,`Heal iterations: ${c}`,`Idea: ${t.idea}`]}),a.message.content}import{existsSync as yr,mkdirSync as li,readFileSync as ci,unlinkSync as di,writeFileSync as ui}from"fs";import{dirname as pi,join as fi}from"path";function St(t){return fi(Sn(),t,"mint-state.json")}function br(t,e){let n=St(t);li(pi(n),{recursive:!0}),ui(n,JSON.stringify(e,null,2),"utf-8")}function mi(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.currentPhase=="string"&&typeof e.idea=="string"&&typeof e.spec=="string"&&typeof e.healIterations=="number"&&Array.isArray(e.history)}function vr(t){let e=St(t);if(!yr(e))return null;try{let n=JSON.parse(ci(e,"utf-8"));return mi(n)?n:null}catch{return null}}function xt(t){let e=St(t);if(yr(e))try{di(e)}catch{}}var gi=2,wr=/^\s*--continue(?:\s+(?:approved|yes|y))?\s*$/i,hi="To approve and run the rest of the pipeline, invoke /mint --continue approved (or call mint with {userApproved: true} \u2014 no idea field needed). The handler will reload the spec state from disk.";function re(t,e,n){t.history.push({phase:e,output:n,timestamp:Date.now()})}function yi(t){if(typeof t=="string")return wr.test(t)?{userApproved:!0}:{idea:t};if(typeof t=="object"&&t!==null){let e=t,n=typeof e.idea=="string"?e.idea:void 0;if(n!==void 0&&wr.test(n))return{userApproved:!0};if("idea"in e||"resumeFrom"in e||e.userApproved===!0)return e}throw new Error("mint handler requires input.idea (string), input as string, or {userApproved: true} to resume")}async function kr(t,e){if(!e.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let n=e.sessionId;try{t.currentPhase="research",t.research=await ur(t.spec,n),re(t,"research",t.research),t.currentPhase="plan",t.plan=await pr(t.spec,t.research,n),re(t,"plan",t.plan),t.currentPhase="parallelize",t.waveOrchestrationPlan=await fr(t.plan,e),re(t,"parallelize",JSON.stringify(t.waveOrchestrationPlan||"skipped")),t.currentPhase="build",t.buildResults=await mr(t.plan,t.waveOrchestrationPlan,n),re(t,"build",JSON.stringify(t.buildResults)),t.currentPhase="verify",t.verifyResults=await qe(t.plan,t.buildResults,n),re(t,"verify",JSON.stringify(t.verifyResults)),t.currentPhase="heal";let r=t.verifyResults.testsPassed&&t.verifyResults.lintPassed&&t.verifyResults.designReviewPassed;for(;!r&&t.healIterations<gi;){let s=await gr(t.plan,t.buildResults,t.verifyResults,t.healIterations,e);t.healIterations=s.newHealIterations,t.verifyResults=s.newVerifyResults,r=s.healed,re(t,"heal",`Iterations: ${t.healIterations}, Success: ${r}`)}if(!r)return{paused:!0,phase:"heal-failed",reason:`Heal capped at ${t.healIterations} iterations; still have failures`,state:t,nextStep:"Heal loop exhausted. Inspect verifyResults, fix manually, then re-invoke /mint with a fresh idea \u2014 resume is not supported from heal-failed."};t.currentPhase="ship";let o=await hr(t,n);return re(t,"ship",o),{completed:!0,artifact:o,state:t}}catch(r){throw new Error(`mint failed at ${t.currentPhase}: ${r}`)}}function Sr(t,e){return("completed"in e||e.phase==="heal-failed")&&xt(t),e}async function bi(t,e){let n=yi(t);if(!e?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let r=e.sessionId;if(n.userApproved){let i=n.resumeFrom??vr(r);if(!i)throw new Error("mint: no paused spec found for this session to continue. Run /mint <idea> first, then /mint --continue approved.");let a=await kr(i,e);return Sr(r,a)}if(!n.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");xt(r);let o={currentPhase:"spec",idea:n.idea,healIterations:0,history:[]};try{o.spec=await dr(n.idea,r),re(o,"spec",o.spec)}catch(i){throw new Error(`mint failed at spec: ${i}`)}if(!n.autoApprove)return br(r,o),{paused:!0,phase:"spec",spec:o.spec,state:o,nextStep:hi};let s=await kr(o,e);return Sr(r,s)}var vi={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:bi,argumentHint:"<idea> | --continue [approved]",whenToUse:"When the user wants a feature or refactor delivered end-to-end (spec \u2192 research \u2192 build \u2192 verify) in one ship-ready pass. After the spec phase pauses for approval, invoke `/mint --continue approved` (or call mint with `{userApproved: true}`) to resume \u2014 the handler reloads the spec state from disk.",flags:["--continue"]};W(vi);import{existsSync as wi,readdirSync as ki,readFileSync as Si,statSync as xi}from"fs";import{join as Pi}from"path";function Pt(t){let e=[];function n(r,o=0){if(o>10||!wi(r))return;let s;try{s=ki(r)}catch{return}for(let i of s){if(i.startsWith("."))continue;let a=Pi(r,i),l;try{l=xi(a)}catch{continue}if(l.isFile()&&i==="SKILL.md"){let c=Ei(a);c.name&&e.push(c)}else l.isDirectory()&&n(a,o+1)}}return n(t),e}function Ei(t){try{let e=Si(t,"utf-8");if(!e.startsWith(`---
1233
+ Create a ship-ready summary with next steps.`,a=await s.runToResult(i);if(a.status!=="succeeded"||!a.message)throw new Error(`ship phase failed: ${C(a)}`);let l=t.buildResults?.filesChanged.length??0,c=t.healIterations;return fe({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${l}`,`Heal iterations: ${c}`,`Idea: ${t.idea}`]}),a.message.content}import{existsSync as vr,mkdirSync as di,readFileSync as ui,unlinkSync as pi,writeFileSync as fi}from"fs";import{dirname as mi,join as gi}from"path";function Et(t){return gi(En(),t,"mint-state.json")}function wr(t,e){let n=Et(t);di(mi(n),{recursive:!0}),fi(n,JSON.stringify(e,null,2),"utf-8")}function hi(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.currentPhase=="string"&&typeof e.idea=="string"&&typeof e.spec=="string"&&typeof e.healIterations=="number"&&Array.isArray(e.history)}function kr(t){let e=Et(t);if(!vr(e))return null;try{let n=JSON.parse(ui(e,"utf-8"));return hi(n)?n:null}catch{return null}}function Pt(t){let e=Et(t);if(vr(e))try{pi(e)}catch{}}var yi=2,Sr=/^\s*--continue(?:\s+(?:approved|yes|y))?\s*$/i,bi="To approve and run the rest of the pipeline, invoke /mint --continue approved (or call mint with {userApproved: true} \u2014 no idea field needed). The handler will reload the spec state from disk.";function se(t,e,n){t.history.push({phase:e,output:n,timestamp:Date.now()})}function vi(t){if(typeof t=="string")return Sr.test(t)?{userApproved:!0}:{idea:t};if(typeof t=="object"&&t!==null){let e=t,n=typeof e.idea=="string"?e.idea:void 0;if(n!==void 0&&Sr.test(n))return{userApproved:!0};if("idea"in e||"resumeFrom"in e||e.userApproved===!0)return e}throw new Error("mint handler requires input.idea (string), input as string, or {userApproved: true} to resume")}async function xr(t,e){if(!e.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let n=e.sessionId;try{t.currentPhase="research",t.research=await fr(t.spec,n),se(t,"research",t.research),t.currentPhase="plan",t.plan=await mr(t.spec,t.research,n),se(t,"plan",t.plan),t.currentPhase="parallelize",t.waveOrchestrationPlan=await gr(t.plan,e),se(t,"parallelize",JSON.stringify(t.waveOrchestrationPlan||"skipped")),t.currentPhase="build",t.buildResults=await hr(t.plan,t.waveOrchestrationPlan,n),se(t,"build",JSON.stringify(t.buildResults)),t.currentPhase="verify",t.verifyResults=await Ye(t.plan,t.buildResults,n),se(t,"verify",JSON.stringify(t.verifyResults)),t.currentPhase="heal";let r=t.verifyResults.testsPassed&&t.verifyResults.lintPassed&&t.verifyResults.designReviewPassed;for(;!r&&t.healIterations<yi;){let s=await yr(t.plan,t.buildResults,t.verifyResults,t.healIterations,e);t.healIterations=s.newHealIterations,t.verifyResults=s.newVerifyResults,r=s.healed,se(t,"heal",`Iterations: ${t.healIterations}, Success: ${r}`)}if(!r)return{paused:!0,phase:"heal-failed",reason:`Heal capped at ${t.healIterations} iterations; still have failures`,state:t,nextStep:"Heal loop exhausted. Inspect verifyResults, fix manually, then re-invoke /mint with a fresh idea \u2014 resume is not supported from heal-failed."};t.currentPhase="ship";let o=await br(t,n);return se(t,"ship",o),{completed:!0,artifact:o,state:t}}catch(r){throw new Error(`mint failed at ${t.currentPhase}: ${r}`)}}function Er(t,e){return("completed"in e||e.phase==="heal-failed")&&Pt(t),e}async function wi(t,e){let n=vi(t);if(!e?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let r=e.sessionId;if(n.userApproved){let i=n.resumeFrom??kr(r);if(!i)throw new Error("mint: no paused spec found for this session to continue. Run /mint <idea> first, then /mint --continue approved.");let a=await xr(i,e);return Er(r,a)}if(!n.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");Pt(r);let o={currentPhase:"spec",idea:n.idea,healIterations:0,history:[]};try{o.spec=await pr(n.idea,r),se(o,"spec",o.spec)}catch(i){throw new Error(`mint failed at spec: ${i}`)}if(!n.autoApprove)return wr(r,o),{paused:!0,phase:"spec",spec:o.spec,state:o,nextStep:bi};let s=await xr(o,e);return Er(r,s)}var ki={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:wi,argumentHint:"<idea> | --continue [approved]",whenToUse:"When the user wants a feature or refactor delivered end-to-end (spec \u2192 research \u2192 build \u2192 verify) in one ship-ready pass. After the spec phase pauses for approval, invoke `/mint --continue approved` (or call mint with `{userApproved: true}`) to resume \u2014 the handler reloads the spec state from disk.",flags:["--continue"]};Y(ki);import{existsSync as Si,readdirSync as xi,readFileSync as Ei,statSync as Pi}from"fs";import{join as Ai}from"path";function At(t){let e=[];function n(r,o=0){if(o>10||!Si(r))return;let s;try{s=xi(r)}catch{return}for(let i of s){if(i.startsWith("."))continue;let a=Ai(r,i),l;try{l=Pi(a)}catch{continue}if(l.isFile()&&i==="SKILL.md"){let c=Ti(a);c.name&&e.push(c)}else l.isDirectory()&&n(a,o+1)}}return n(t),e}function Ti(t){try{let e=Ei(t,"utf-8");if(!e.startsWith(`---
1222
1234
  `))return{};let n=e.slice(4),r=n.indexOf(`
1223
1235
  ---`);if(r===-1)return{};let o=n.slice(0,r),s=n.slice(r+4).trim(),i={},a=o.split(`
1224
- `);for(let l of a){if(!l)continue;let c=l.indexOf(":");if(c===-1)continue;let d=l.slice(0,c).trim(),u=l.slice(c+1).trim();d==="name"?i.name=u.replace(/^["']|["']$/g,""):d==="description"?i.description=u.replace(/^["']|["']$/g,""):d==="argumentHint"&&(i.argumentHint=u.replace(/^["']|["']$/g,""))}return s.length>0&&(i.body=s),i}catch{return{}}}function xr(t){let e=ke(t);if(e.length===0)return"";let n=[];for(let r of e){let o=r.argumentHint?`${r.argumentHint}`:"",s=o?`- \`${r.name} ${o}\`: ${r.description}`:`- ${r.name}: ${r.description}`;n.push(s),r.whenToUse&&n.push(` When to use: ${r.whenToUse}`)}return["Available skills (invoke via the `skill` tool):",...n].join(`
1225
- `)}function ke(t){let e=[],n=new Set;for(let o of un()){let s=z(o);e.push({name:o,description:s.description,source:s.origin==="user"?"user":s.origin==="project"?"project":"builtin",argumentHint:s.argumentHint,whenToUse:s.whenToUse}),n.add(o)}let r=t??[...q(he()),...q()];for(let o of r){if(o.type!=="local")continue;let s=Pt(o.path);for(let i of s)!i.name||n.has(i.name)||(e.push({name:i.name,description:i.description??`Skill from plugin at ${o.path}`,source:"plugin"}),n.add(i.name))}return e}function Pr(t){let e=new Map,n=t??[...q(he()),...q()];for(let r of n){if(r.type!=="local")continue;let o=Pt(r.path);for(let s of o)s.name&&s.body&&s.body.length>0&&e.set(s.name,s.body)}return e}var Ai=3,Ti="claude-haiku-4-5-20251001",Ii=1024,Ci=[{value:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",description:"Latest balanced Claude \u2014 recommended default"},{value:"claude-opus-4-5-20250929",displayName:"Claude Opus 4.5",description:"Highest-capability Claude"},{value:"claude-haiku-4-5-20250929",displayName:"Claude Haiku 4.5",description:"Fastest, cheapest Claude"}],We=class{client;authMode;initSessionId;promptStream;toolDispatcher;maxTokens;tools;systemPrefix;userSystem;currentModel;currentPermissionMode;messages=[];closed=!1;abortController=null;pendingAbortReason=null;closedPromise;closeResolve=null;lastUsage=null;constructor(e){this.client=e.client,this.authMode=e.authMode,this.initSessionId=Et(),this.promptStream=e.promptStream,this.toolDispatcher=e.toolDispatcher,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.userSystem=e.userSystem,this.currentModel=e.model,this.currentPermissionMode=e.permissionMode??"default",this.closedPromise=new Promise(n=>{this.closeResolve=()=>n("__closed__")})}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:[],apiKeySource:this.authMode,version:"anthropic-direct-v1"}};let n=this.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let r=await Promise.race([n.next(),this.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=new AbortController;if(this.abortController=i,this.pendingAbortReason!==null&&!i.signal.aborted&&(i.abort(this.pendingAbortReason),this.pendingAbortReason=null),i.signal.aborted)return;this.messages.push({role:"user",content:s.content});let a=this.composeSystem(),l=at(this.authMode,this.initSessionId,Et()),c={client:this.client,messages:this.messages,system:a,tools:this.tools,toolDispatcher:this.toolDispatcher,model:this.currentModel,maxTokens:this.maxTokens,headers:l,signal:i.signal,ctx:{sessionId:this.initSessionId}};try{for await(let d of en(c)){if(this.closed)return;d.type==="turn.completed"&&(this.lastUsage=d.usage),yield d}}catch(d){if(i.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}finally{this.abortController===i&&(this.abortController=null)}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}composeSystem(){let e=this.systemPrefix,n=this.userSystem,r=[];return e&&e.length>0&&r.push(...e),n&&n.length>0&&r.push({type:"text",text:n}),r.length===0?null:Re()?Wt(r,De()):r}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){e!==void 0&&e.length>0&&(this.currentModel=e)}async setPermissionMode(e){this.currentPermissionMode=e}async supportedCommands(){try{return ke().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return Ci.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:this.lastUsage}}async mcpServerStatus(){return[]}async accountInfo(){return{subscriptionType:this.authMode==="oauth"?"claude-subscription":"api-key"}}async rewindFiles(e,n){return{canRewind:!1,error:"anthropic-direct provider does not support file checkpoint rewind"}}async compact(){let e=this.messages.length;if(this.closed)return{compacted:!1,reason:"session-closed",messagesBefore:e,messagesAfter:e};if(this.abortController!==null)return{compacted:!1,reason:"turn-in-flight",messagesBefore:e,messagesAfter:e};let n=Mi(),r=rn(this.messages,n);if(r<=0)return{compacted:!1,reason:"history-too-short",messagesBefore:e,messagesAfter:e};let o=this.messages.slice(0,r),s=_i(),i=on(o,s,Ii),a=new AbortController;this.abortController=a,this.pendingAbortReason!==null&&!a.signal.aborted&&(a.abort(this.pendingAbortReason),this.pendingAbortReason=null);let l;try{if(a.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e};let u=at(this.authMode,this.initSessionId,Et()),p=this.client,f=await Promise.resolve(p.messages.create(i,{headers:u,signal:a.signal}));l=await Ri(f)}catch(u){return a.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e}:{compacted:!1,reason:"summarization-failed: "+(u instanceof Error?u.message:String(u)),messagesBefore:e,messagesAfter:e}}finally{this.abortController===a&&(this.abortController=null)}if(l.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:e,messagesAfter:e};let c=an(this.messages,r,l),d=sn(this.messages,r,l);return this.messages.splice(0,this.messages.length,...d),{compacted:!0,messagesBefore:e,messagesAfter:this.messages.length,tokensSavedEstimate:c}}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.()}};function Mi(){let t=process.env.AFK_COMPACT_KEEP_LAST_TURNS;if(t!==void 0&&t.length>0){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return Ai}function _i(){let t=process.env.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?t:Ti}async function Ri(t){let e="";for await(let n of t)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(e+=r.text)}return e}var Di=new Set(["read_file","glob","grep","list_directory"]);function At(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:Di.has(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" requires explicit permission (add to allowedTools config)`}}var Oi=new Set(["agent","read_file","glob","grep","list_directory"]);function Fi(t){return Oi.has(t)}function $i(t,e){return t.reduce((n,r,o)=>{let s=e(r.name,r.input),i=n[n.length-1];return i&&s&&i.isConcurrencySafe?i.indices.push(o):n.push({isConcurrencySafe:s,indices:[o]}),n},[])}var Se=class{handlers;schemas;hookRegistry;permissions;subagentExecutor;skillExecutor;classifier;constructor(e){this.handlers=e.handlers,this.schemas=e.schemas,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.subagentExecutor=e.subagentExecutor,this.skillExecutor=e.skillExecutor,this.classifier=e.concurrencyClassifier??Fi}get toolDefs(){return this.schemas}async execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0};if(this.hookRegistry){let s={event:"PreToolUse",toolName:e.name,input:e.input};try{await this.hookRegistry.dispatch(s,e.signal)}catch(i){if(i instanceof U)return{content:`Tool "${e.name}" blocked by PreToolUse hook: ${i.message}`,isError:!0};throw i}}let n=At(e.name,this.permissions);if(!n.allowed)return{content:n.reason??`Tool "${e.name}" is not permitted`,isError:!0};if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s;try{s=await this.subagentExecutor.execute(e)}catch(i){s={content:`Agent tool error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}if(this.hookRegistry){let i={event:"PostToolUse",toolName:e.name,output:s.content};try{await this.hookRegistry.dispatch(i,e.signal)}catch{}}return s}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s;try{s=await this.skillExecutor.execute(e)}catch(i){s={content:`Skill tool error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}if(this.hookRegistry){let i={event:"PostToolUse",toolName:e.name,output:s.content};try{await this.hookRegistry.dispatch(i,e.signal)}catch{}}return s}let r=this.handlers.get(e.name);if(!r)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let o;try{o=await r(e.input,e.signal)}catch(s){o={content:`Tool execution error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}if(this.hookRegistry){let s={event:"PostToolUse",toolName:e.name,output:o.content};try{await this.hookRegistry.dispatch(s,e.signal)}catch{}}return o}async executeBatch(e){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let n=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){let a=e[i];if(a.signal.aborted){n[i]={content:"Tool call aborted",isError:!0},r.add(i);continue}if(this.hookRegistry){let c={event:"PreToolUse",toolName:a.name,input:a.input};try{await this.hookRegistry.dispatch(c,a.signal)}catch(d){if(d instanceof U){n[i]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${d.message}`,isError:!0},r.add(i);continue}throw d}}let l=At(a.name,this.permissions);l.allowed||(n[i]={content:l.reason??`Tool "${a.name}" is not permitted`,isError:!0},r.add(i))}let o=e.map((i,a)=>({call:i,originalIndex:a})).filter((i,a)=>!r.has(a));if(o.length===0)return n;let s=$i(o.map(i=>i.call),this.classifier);for(let i of s){if(e[0].signal.aborted){for(let a of i.indices){let l=o[a].originalIndex;n[l]={content:"Tool call aborted",isError:!0}}continue}if(i.isConcurrencySafe){let a=await Promise.allSettled(i.indices.map(async l=>{let{call:c,originalIndex:d}=o[l];return{result:await this.executeCore(c),originalIndex:d}}));for(let l of a)if(l.status==="fulfilled")n[l.value.originalIndex]=l.value.result;else{let c=l.reason instanceof Error?l.reason.message:String(l.reason),d=i.indices[a.indexOf(l)];n[o[d].originalIndex]={content:`Tool execution error: ${c}`,isError:!0}}}else for(let a of i.indices){let{call:l,originalIndex:c}=o[a];if(l.signal.aborted){n[c]={content:"Tool call aborted",isError:!0};continue}n[c]=await this.executeCore(l)}}return n}async executeCore(e){if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let o;try{o=await this.subagentExecutor.execute(e)}catch(s){o={content:`Agent tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let o;try{o=await this.skillExecutor.execute(e)}catch(s){o={content:`Skill tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}let n=this.handlers.get(e.name);if(!n)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r;try{r=await n(e.input,e.signal)}catch(o){r={content:`Tool execution error: ${o instanceof Error?o.message:String(o)}`,isError:!0}}return this.firePostToolUse(e.name,r.content,e.signal),r}firePostToolUse(e,n,r){if(!this.hookRegistry)return;let o={event:"PostToolUse",toolName:e,output:n};this.hookRegistry.dispatch(o,r).catch(()=>{})}};import{spawn as Li}from"child_process";function ji(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(e.timeout_ms<0||e.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=e.timeout_ms}return{command:e.command,timeout_ms:n}}function Hi(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Er=async(t,e)=>{let{command:n,timeout_ms:r}=ji(t);return e.aborted?{content:"Command aborted",isError:!0}:new Promise(o=>{let s=!1;function i(p){s||(s=!0,clearTimeout(l),e.removeEventListener("abort",u),o(p))}let a=Li(n,{shell:!0,stdio:["ignore","pipe","pipe"]}),l=setTimeout(()=>{a.kill(),i({content:`Command timed out after ${r}ms`,isError:!0})},r),c="",d="";a.stdout.on("data",p=>{c+=p.toString()}),a.stderr.on("data",p=>{d+=p.toString()});let u=()=>{a.kill(),i({content:"Command aborted",isError:!0})};e.addEventListener("abort",u),a.on("close",()=>{let p=(c+d).trimEnd();p=Hi(p);let f=1e5;p.length>f&&(p=p.slice(0,f)+`
1226
- [output truncated \u2014 exceeded 100KB]`),i({content:p})}),a.on("error",p=>{i({content:`Failed to execute: ${p.message}`,isError:!0})})})};import{promises as Ui}from"fs";var Ar=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let n=t,r=n.file_path,o=n.offset??1,s=n.limit??2e3;if(typeof r!="string")return{content:"Invalid input: file_path must be a string",isError:!0};if(typeof o!="number"||o<1)return{content:"Invalid input: offset must be a positive number",isError:!0};if(typeof s!="number"||s<1)return{content:"Invalid input: limit must be a positive number",isError:!0};try{let i=await Ui.readFile(r),a=Math.min(8192,i.length);for(let m=0;m<a;m++)if(i[m]===0)return{content:`File appears to be binary: ${r}`,isError:!0};let l=i.toString("utf-8");if(l.length===0)return{content:""};let c=l.split(`
1227
- `),d=Math.max(0,o-1),u=Math.min(c.length,d+s),p=c.slice(d,u),f=c.length;if(p.length===0)return{content:`... (offset ${o} is past end of file \u2014 file has ${f} lines)`};let g=String(f).length,h=p.map((m,b)=>{let S=d+b+1;return`${String(S).padStart(g," ")} ${m}`}).join(`
1228
- `);if(p.length<f){let m=d+1,b=d+p.length,S=b<f?` \u2014 pass offset=${b+1} to continue`:"";return{content:`${h}
1229
- ... (showing lines ${m}-${b} of ${f}${S})`}}return{content:h}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`File not found: ${r}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${r}`,isError:!0}:{content:`Error reading file: ${i.message}`,isError:!0}}return{content:"Unknown error reading file",isError:!0}}};import{writeFile as Ni}from"fs/promises";import{mkdir as Bi}from"fs/promises";import{dirname as Ki}from"path";function Gi(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.content!="string")throw new Error('Input must have a "content" field of type string');return{file_path:e.file_path,content:e.content}}var Tr=async(t,e)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:n,content:r}=Gi(t);try{let o=Ki(n);return await Bi(o,{recursive:!0}),await Ni(n,r,{signal:e}),{content:`Wrote ${Buffer.byteLength(r,"utf8")} bytes to ${n}`}}catch(o){return o instanceof Error?"code"in o&&o.code==="EACCES"?{content:`Permission denied: ${n}`,isError:!0}:{content:`Error writing file: ${o.message}`,isError:!0}:{content:"Unknown error writing file",isError:!0}}};import{readFile as zi,writeFile as Vi}from"fs/promises";function qi(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.old_string!="string")throw new Error('Input must have an "old_string" field of type string');if(typeof e.new_string!="string")throw new Error('Input must have a "new_string" field of type string');let n=!1;if(e.replace_all!==void 0){if(typeof e.replace_all!="boolean")throw new Error("replace_all must be a boolean");n=e.replace_all}return{file_path:e.file_path,old_string:e.old_string,new_string:e.new_string,replace_all:n}}function Wi(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}function Yi(t,e,n){let r=t.split(`
1236
+ `);for(let l of a){if(!l)continue;let c=l.indexOf(":");if(c===-1)continue;let d=l.slice(0,c).trim(),u=l.slice(c+1).trim();d==="name"?i.name=u.replace(/^["']|["']$/g,""):d==="description"?i.description=u.replace(/^["']|["']$/g,""):d==="argumentHint"&&(i.argumentHint=u.replace(/^["']|["']$/g,""))}return s.length>0&&(i.body=s),i}catch{return{}}}function Pr(t){let e=xe(t);if(e.length===0)return"";let n=[];for(let r of e){let o=r.argumentHint?`${r.argumentHint}`:"",s=o?`- \`${r.name} ${o}\`: ${r.description}`:`- ${r.name}: ${r.description}`;n.push(s),r.whenToUse&&n.push(` When to use: ${r.whenToUse}`)}return["Available skills (invoke via the `skill` tool):",...n].join(`
1237
+ `)}function xe(t){let e=[],n=new Set;for(let o of fn()){let s=z(o);e.push({name:o,description:s.description,source:s.origin==="user"?"user":s.origin==="project"?"project":"builtin",argumentHint:s.argumentHint,whenToUse:s.whenToUse}),n.add(o)}let r=t??[...q(be()),...q()];for(let o of r){if(o.type!=="local")continue;let s=At(o.path);for(let i of s)!i.name||n.has(i.name)||(e.push({name:i.name,description:i.description??`Skill from plugin at ${o.path}`,source:"plugin"}),n.add(i.name))}return e}function Ar(t){let e=new Map,n=t??[...q(be()),...q()];for(let r of n){if(r.type!=="local")continue;let o=At(r.path);for(let s of o)s.name&&s.body&&s.body.length>0&&e.set(s.name,s.body)}return e}var Ii=3,Ci="claude-haiku-4-5-20251001",Mi=1024,_i=[{value:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",description:"Latest balanced Claude \u2014 recommended default"},{value:"claude-opus-4-5-20250929",displayName:"Claude Opus 4.5",description:"Highest-capability Claude"},{value:"claude-haiku-4-5-20250929",displayName:"Claude Haiku 4.5",description:"Fastest, cheapest Claude"}],Je=class{client;authMode;initSessionId;promptStream;toolDispatcher;maxTokens;tools;systemPrefix;userSystem;currentModel;currentPermissionMode;messages=[];closed=!1;abortController=null;pendingAbortReason=null;closedPromise;closeResolve=null;lastUsage=null;constructor(e){this.client=e.client,this.authMode=e.authMode,this.initSessionId=Tt(),this.promptStream=e.promptStream,this.toolDispatcher=e.toolDispatcher,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.userSystem=e.userSystem,this.currentModel=e.model,this.currentPermissionMode=e.permissionMode??"default",this.closedPromise=new Promise(n=>{this.closeResolve=()=>n("__closed__")})}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:[],apiKeySource:this.authMode,version:"anthropic-direct-v1"}};let n=this.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let r=await Promise.race([n.next(),this.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=new AbortController;if(this.abortController=i,this.pendingAbortReason!==null&&!i.signal.aborted&&(i.abort(this.pendingAbortReason),this.pendingAbortReason=null),i.signal.aborted)return;this.messages.push({role:"user",content:s.content});let a=this.composeSystem(),l=ct(this.authMode,this.initSessionId,Tt()),c={client:this.client,messages:this.messages,system:a,tools:this.tools,toolDispatcher:this.toolDispatcher,model:this.currentModel,maxTokens:this.maxTokens,headers:l,signal:i.signal,ctx:{sessionId:this.initSessionId}};try{for await(let d of nn(c)){if(this.closed)return;d.type==="turn.completed"&&(this.lastUsage=d.usage),yield d}}catch(d){if(i.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}finally{this.abortController===i&&(this.abortController=null)}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}composeSystem(){let e=this.systemPrefix,n=this.userSystem,r=[];return e&&e.length>0&&r.push(...e),n&&n.length>0&&r.push({type:"text",text:n}),r.length===0?null:Oe()?Jt(r,Fe()):r}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){e!==void 0&&e.length>0&&(this.currentModel=e)}async setPermissionMode(e){this.currentPermissionMode=e}async supportedCommands(){try{return xe().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return _i.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:this.lastUsage}}async mcpServerStatus(){return[]}async accountInfo(){return{subscriptionType:this.authMode==="oauth"?"claude-subscription":"api-key"}}async rewindFiles(e,n){return{canRewind:!1,error:"anthropic-direct provider does not support file checkpoint rewind"}}async compact(){let e=this.messages.length;if(this.closed)return{compacted:!1,reason:"session-closed",messagesBefore:e,messagesAfter:e};if(this.abortController!==null)return{compacted:!1,reason:"turn-in-flight",messagesBefore:e,messagesAfter:e};let n=Ri(),r=sn(this.messages,n);if(r<=0)return{compacted:!1,reason:"history-too-short",messagesBefore:e,messagesAfter:e};let o=this.messages.slice(0,r),s=Di(),i=an(o,s,Mi),a=new AbortController;this.abortController=a,this.pendingAbortReason!==null&&!a.signal.aborted&&(a.abort(this.pendingAbortReason),this.pendingAbortReason=null);let l;try{if(a.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e};let u=ct(this.authMode,this.initSessionId,Tt()),p=this.client,f=await Promise.resolve(p.messages.create(i,{headers:u,signal:a.signal}));l=await Oi(f)}catch(u){return a.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e}:{compacted:!1,reason:"summarization-failed: "+(u instanceof Error?u.message:String(u)),messagesBefore:e,messagesAfter:e}}finally{this.abortController===a&&(this.abortController=null)}if(l.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:e,messagesAfter:e};let c=cn(this.messages,r,l),d=ln(this.messages,r,l);return this.messages.splice(0,this.messages.length,...d),{compacted:!0,messagesBefore:e,messagesAfter:this.messages.length,tokensSavedEstimate:c}}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.()}};function Ri(){let t=process.env.AFK_COMPACT_KEEP_LAST_TURNS;if(t!==void 0&&t.length>0){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return Ii}function Di(){let t=process.env.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?t:Ci}async function Oi(t){let e="";for await(let n of t)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(e+=r.text)}return e}var Fi=new Set(["read_file","glob","grep","list_directory"]);function It(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:Fi.has(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" requires explicit permission (add to allowedTools config)`}}var $i=new Set(["agent","read_file","glob","grep","list_directory"]);function Li(t){return $i.has(t)}function ji(t,e){return t.reduce((n,r,o)=>{let s=e(r.name,r.input),i=n[n.length-1];return i&&s&&i.isConcurrencySafe?i.indices.push(o):n.push({isConcurrencySafe:s,indices:[o]}),n},[])}var Ee=class{handlers;schemas;hookRegistry;permissions;subagentExecutor;skillExecutor;classifier;constructor(e){this.handlers=e.handlers,this.schemas=e.schemas,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.subagentExecutor=e.subagentExecutor,this.skillExecutor=e.skillExecutor,this.classifier=e.concurrencyClassifier??Li}get toolDefs(){return this.schemas}async execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0};if(this.hookRegistry){let s={event:"PreToolUse",toolName:e.name,input:e.input};try{await this.hookRegistry.dispatch(s,e.signal)}catch(i){if(i instanceof U)return{content:`Tool "${e.name}" blocked by PreToolUse hook: ${i.message}`,isError:!0};throw i}}let n=It(e.name,this.permissions);if(!n.allowed)return{content:n.reason??`Tool "${e.name}" is not permitted`,isError:!0};if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s;try{s=await this.subagentExecutor.execute(e)}catch(i){s={content:`Agent tool error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}if(this.hookRegistry){let i={event:"PostToolUse",toolName:e.name,output:s.content};try{await this.hookRegistry.dispatch(i,e.signal)}catch{}}return s}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s;try{s=await this.skillExecutor.execute(e)}catch(i){s={content:`Skill tool error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}if(this.hookRegistry){let i={event:"PostToolUse",toolName:e.name,output:s.content};try{await this.hookRegistry.dispatch(i,e.signal)}catch{}}return s}let r=this.handlers.get(e.name);if(!r)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let o;try{o=await r(e.input,e.signal)}catch(s){o={content:`Tool execution error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}if(this.hookRegistry){let s={event:"PostToolUse",toolName:e.name,output:o.content};try{await this.hookRegistry.dispatch(s,e.signal)}catch{}}return o}async executeBatch(e){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let n=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){let a=e[i];if(a.signal.aborted){n[i]={content:"Tool call aborted",isError:!0},r.add(i);continue}if(this.hookRegistry){let c={event:"PreToolUse",toolName:a.name,input:a.input};try{await this.hookRegistry.dispatch(c,a.signal)}catch(d){if(d instanceof U){n[i]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${d.message}`,isError:!0},r.add(i);continue}throw d}}let l=It(a.name,this.permissions);l.allowed||(n[i]={content:l.reason??`Tool "${a.name}" is not permitted`,isError:!0},r.add(i))}let o=e.map((i,a)=>({call:i,originalIndex:a})).filter((i,a)=>!r.has(a));if(o.length===0)return n;let s=ji(o.map(i=>i.call),this.classifier);for(let i of s){if(e[0].signal.aborted){for(let a of i.indices){let l=o[a].originalIndex;n[l]={content:"Tool call aborted",isError:!0}}continue}if(i.isConcurrencySafe){let a=await Promise.allSettled(i.indices.map(async l=>{let{call:c,originalIndex:d}=o[l];return{result:await this.executeCore(c),originalIndex:d}}));for(let l of a)if(l.status==="fulfilled")n[l.value.originalIndex]=l.value.result;else{let c=l.reason instanceof Error?l.reason.message:String(l.reason),d=i.indices[a.indexOf(l)];n[o[d].originalIndex]={content:`Tool execution error: ${c}`,isError:!0}}}else for(let a of i.indices){let{call:l,originalIndex:c}=o[a];if(l.signal.aborted){n[c]={content:"Tool call aborted",isError:!0};continue}n[c]=await this.executeCore(l)}}return n}async executeCore(e){if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let o;try{o=await this.subagentExecutor.execute(e)}catch(s){o={content:`Agent tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let o;try{o=await this.skillExecutor.execute(e)}catch(s){o={content:`Skill tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}let n=this.handlers.get(e.name);if(!n)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r;try{r=await n(e.input,e.signal)}catch(o){r={content:`Tool execution error: ${o instanceof Error?o.message:String(o)}`,isError:!0}}return this.firePostToolUse(e.name,r.content,e.signal),r}firePostToolUse(e,n,r){if(!this.hookRegistry)return;let o={event:"PostToolUse",toolName:e,output:n};this.hookRegistry.dispatch(o,r).catch(()=>{})}};import{spawn as Hi}from"child_process";function Ui(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(e.timeout_ms<0||e.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=e.timeout_ms}return{command:e.command,timeout_ms:n}}function Ni(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Tr=async(t,e)=>{let{command:n,timeout_ms:r}=Ui(t);return e.aborted?{content:"Command aborted",isError:!0}:new Promise(o=>{let s=!1;function i(p){s||(s=!0,clearTimeout(l),e.removeEventListener("abort",u),o(p))}let a=Hi(n,{shell:!0,stdio:["ignore","pipe","pipe"]}),l=setTimeout(()=>{a.kill(),i({content:`Command timed out after ${r}ms`,isError:!0})},r),c="",d="";a.stdout.on("data",p=>{c+=p.toString()}),a.stderr.on("data",p=>{d+=p.toString()});let u=()=>{a.kill(),i({content:"Command aborted",isError:!0})};e.addEventListener("abort",u),a.on("close",()=>{let p=(c+d).trimEnd();p=Ni(p);let f=1e5;p.length>f&&(p=p.slice(0,f)+`
1238
+ [output truncated \u2014 exceeded 100KB]`),i({content:p})}),a.on("error",p=>{i({content:`Failed to execute: ${p.message}`,isError:!0})})})};import{promises as Bi}from"fs";var Ir=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let n=t,r=n.file_path,o=n.offset??1,s=n.limit??2e3;if(typeof r!="string")return{content:"Invalid input: file_path must be a string",isError:!0};if(typeof o!="number"||o<1)return{content:"Invalid input: offset must be a positive number",isError:!0};if(typeof s!="number"||s<1)return{content:"Invalid input: limit must be a positive number",isError:!0};try{let i=await Bi.readFile(r),a=Math.min(8192,i.length);for(let m=0;m<a;m++)if(i[m]===0)return{content:`File appears to be binary: ${r}`,isError:!0};let l=i.toString("utf-8");if(l.length===0)return{content:""};let c=l.split(`
1239
+ `),d=Math.max(0,o-1),u=Math.min(c.length,d+s),p=c.slice(d,u),f=c.length;if(p.length===0)return{content:`... (offset ${o} is past end of file \u2014 file has ${f} lines)`};let g=String(f).length,h=p.map((m,b)=>{let v=d+b+1;return`${String(v).padStart(g," ")} ${m}`}).join(`
1240
+ `);if(p.length<f){let m=d+1,b=d+p.length,v=b<f?` \u2014 pass offset=${b+1} to continue`:"";return{content:`${h}
1241
+ ... (showing lines ${m}-${b} of ${f}${v})`}}return{content:h}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`File not found: ${r}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${r}`,isError:!0}:{content:`Error reading file: ${i.message}`,isError:!0}}return{content:"Unknown error reading file",isError:!0}}};import{writeFile as Ki}from"fs/promises";import{mkdir as Gi}from"fs/promises";import{dirname as zi}from"path";function Vi(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.content!="string")throw new Error('Input must have a "content" field of type string');return{file_path:e.file_path,content:e.content}}var Cr=async(t,e)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:n,content:r}=Vi(t);try{let o=zi(n);return await Gi(o,{recursive:!0}),await Ki(n,r,{signal:e}),{content:`Wrote ${Buffer.byteLength(r,"utf8")} bytes to ${n}`}}catch(o){return o instanceof Error?"code"in o&&o.code==="EACCES"?{content:`Permission denied: ${n}`,isError:!0}:{content:`Error writing file: ${o.message}`,isError:!0}:{content:"Unknown error writing file",isError:!0}}};import{readFile as qi,writeFile as Wi}from"fs/promises";function Yi(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.old_string!="string")throw new Error('Input must have an "old_string" field of type string');if(typeof e.new_string!="string")throw new Error('Input must have a "new_string" field of type string');let n=!1;if(e.replace_all!==void 0){if(typeof e.replace_all!="boolean")throw new Error("replace_all must be a boolean");n=e.replace_all}return{file_path:e.file_path,old_string:e.old_string,new_string:e.new_string,replace_all:n}}function Ji(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}function Qi(t,e,n){let r=t.split(`
1230
1242
  `),o=0,s=0;for(let c=0;c<r.length;c++){let d=r[c]?.length??0,u=o+d+1;if(o+d>=n+e.length){s=c;break}o=u}let i=Math.max(0,s-2),a=Math.min(r.length,s+3);return`...${r.slice(i,a).join(`
1231
- `)}...`}var Ir=async(t,e)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:n,old_string:r,new_string:o,replace_all:s}=qi(t);try{let i=await zi(n,"utf-8"),a=Wi(i,r);if(a===0)return{content:`old_string not found in ${n}`,isError:!0};if(a>1&&!s)return{content:`old_string matches ${a} locations in ${n}. Use replace_all: true or provide more context.`,isError:!0};let l,c;s?(l=i.split(r).join(o),c=i.indexOf(r)):(c=i.indexOf(r),l=i.slice(0,c)+o+i.slice(c+r.length)),await Vi(n,l,"utf-8");let d=Yi(i,r,c);return{content:`${a===1?`Replaced 1 occurrence in ${n}`:`Replaced ${a} occurrences in ${n}`}
1243
+ `)}...`}var Mr=async(t,e)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:n,old_string:r,new_string:o,replace_all:s}=Yi(t);try{let i=await qi(n,"utf-8"),a=Ji(i,r);if(a===0)return{content:`old_string not found in ${n}`,isError:!0};if(a>1&&!s)return{content:`old_string matches ${a} locations in ${n}. Use replace_all: true or provide more context.`,isError:!0};let l,c;s?(l=i.split(r).join(o),c=i.indexOf(r)):(c=i.indexOf(r),l=i.slice(0,c)+o+i.slice(c+r.length)),await Wi(n,l,"utf-8");let d=Qi(i,r,c);return{content:`${a===1?`Replaced 1 occurrence in ${n}`:`Replaced ${a} occurrences in ${n}`}
1232
1244
 
1233
- ${d}`}}catch(i){return{content:`Error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}};import{promises as Mr}from"fs";import Ji from"path";function Qi(t,e){let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/");if(r.includes("**")){let s=r.split("**"),i=0;for(let a=0;a<s.length;a++){let l=s[a]??"",c=Cr(l);if(a===0){let d=n.match(new RegExp(`^${c}`));if(!d)return!1;i=d[0].length}else if(a===s.length-1){let d=new RegExp(`${c}$`);if(!n.slice(i).match(d))return!1}else{let d=new RegExp(c),u=n.slice(i).match(d);if(!u)return!1;let p=u.index??0;i+=p+u[0].length}}return!0}return new RegExp(`^${Cr(r)}$`).test(n)}function Cr(t){return t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]")}async function Xi(t,e){let n=[];async function o(s,i){if(n.length>=500)return!0;try{let a=await Mr.readdir(s,{withFileTypes:!0});for(let l of a){if(n.length>=500)return!0;let c=Ji.join(s,l.name),d=i?`${i}/${l.name}`:l.name;if(Qi(d,e)&&n.push(d),l.isDirectory()&&await o(c,d))return!0}}catch{}return!1}return await o(t,""),n}var _r=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let n=t,r=n.pattern,o=n.path??process.cwd();if(typeof r!="string")return{content:"Invalid input: pattern must be a string",isError:!0};if(r.trim()==="")return{content:"Invalid input: pattern cannot be empty",isError:!0};if(typeof o!="string")return{content:"Invalid input: path must be a string",isError:!0};try{if(!(await Mr.stat(o)).isDirectory())return{content:`Invalid input: path is not a directory: ${o}`,isError:!0};let i=await Xi(o,r);if(i.length===0)return{content:`No files matched pattern '${r}' in ${o}`};let a=i.join(`
1245
+ ${d}`}}catch(i){return{content:`Error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}};import{promises as Rr}from"fs";import Xi from"path";function Zi(t,e){let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/");if(r.includes("**")){let s=r.split("**"),i=0;for(let a=0;a<s.length;a++){let l=s[a]??"",c=_r(l);if(a===0){let d=n.match(new RegExp(`^${c}`));if(!d)return!1;i=d[0].length}else if(a===s.length-1){let d=new RegExp(`${c}$`);if(!n.slice(i).match(d))return!1}else{let d=new RegExp(c),u=n.slice(i).match(d);if(!u)return!1;let p=u.index??0;i+=p+u[0].length}}return!0}return new RegExp(`^${_r(r)}$`).test(n)}function _r(t){return t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]")}async function ea(t,e){let n=[];async function o(s,i){if(n.length>=500)return!0;try{let a=await Rr.readdir(s,{withFileTypes:!0});for(let l of a){if(n.length>=500)return!0;let c=Xi.join(s,l.name),d=i?`${i}/${l.name}`:l.name;if(Zi(d,e)&&n.push(d),l.isDirectory()&&await o(c,d))return!0}}catch{}return!1}return await o(t,""),n}var Dr=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let n=t,r=n.pattern,o=n.path??process.cwd();if(typeof r!="string")return{content:"Invalid input: pattern must be a string",isError:!0};if(r.trim()==="")return{content:"Invalid input: pattern cannot be empty",isError:!0};if(typeof o!="string")return{content:"Invalid input: path must be a string",isError:!0};try{if(!(await Rr.stat(o)).isDirectory())return{content:`Invalid input: path is not a directory: ${o}`,isError:!0};let i=await ea(o,r);if(i.length===0)return{content:`No files matched pattern '${r}' in ${o}`};let a=i.join(`
1234
1246
  `);return i.length>=500&&(a+=`
1235
- [results capped at 500 entries]`),{content:a}}catch(s){return s instanceof Error?"code"in s&&s.code==="ENOENT"?{content:`Path not found: ${o}`,isError:!0}:"code"in s&&s.code==="EACCES"?{content:`Permission denied: ${o}`,isError:!0}:{content:`Error scanning directory: ${s.message}`,isError:!0}:{content:"Unknown error scanning directory",isError:!0}}};import{spawn as Zi}from"child_process";function ea(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.pattern!="string")throw new Error('Input must have a "pattern" field of type string');let n=typeof e.path=="string"?e.path:process.cwd(),r;if(e.include!==void 0){if(typeof e.include!="string")throw new Error("include must be a string");r=e.include}return{pattern:e.pattern,path:n,include:r}}function ta(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Rr=async(t,e)=>{let{pattern:n,path:r,include:o}=ea(t);return e.aborted?{content:"Search aborted",isError:!0}:new Promise(s=>{let i=!1;function a(f){i||(i=!0,e.removeEventListener("abort",p),s(f))}let l=["-rn"];o&&l.push(`--include=${o}`),l.push(n,r);let c=Zi("grep",l),d="",u="";c.stdout.on("data",f=>{d+=f.toString()}),c.stderr.on("data",f=>{u+=f.toString()});let p=()=>{c.kill(),a({content:"Search aborted",isError:!0})};e.addEventListener("abort",p),c.on("close",f=>{if(f===1){a({content:`No matches found for '${n}' in ${r}`});return}if(f===2){a({content:`grep error: ${u.trim()}`,isError:!0});return}let g=d.trimEnd();g=ta(g);let h=1e5;g.length>h&&(g=g.slice(0,h)+`
1236
- [output truncated]`),a({content:g})}),c.on("error",f=>{a({content:`Failed to execute grep: ${f.message}`,isError:!0})})})};import{promises as na}from"fs";var Dr=async(t,e)=>{if(!t||typeof t!="object")throw new Error("Invalid input: expected an object");let r=t.path;if(typeof r!="string")throw new Error("Invalid input: path must be a string");try{let o=await na.readdir(r,{withFileTypes:!0}),s=o.filter(c=>c.isDirectory()).map(c=>`${c.name}/`),i=o.filter(c=>!c.isDirectory()).map(c=>c.name);s.sort(),i.sort();let a=[...s,...i];return a.length===0?{content:"(empty directory)"}:{content:a.join(`
1237
- `)}}catch(o){if(o instanceof Error){let s=o;return s.code==="ENOENT"?{content:`Directory not found: ${r}`,isError:!0}:s.code==="ENOTDIR"?{content:`Not a directory: ${r}`,isError:!0}:s.code==="EACCES"?{content:`Permission denied: ${r}`,isError:!0}:{content:`Error listing directory: ${o.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}};function Or(){return new Map([["bash",Er],["read_file",Ar],["write_file",Tr],["edit_file",Ir],["glob",_r],["grep",Rr],["list_directory",Dr]])}var Fr=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
1247
+ [results capped at 500 entries]`),{content:a}}catch(s){return s instanceof Error?"code"in s&&s.code==="ENOENT"?{content:`Path not found: ${o}`,isError:!0}:"code"in s&&s.code==="EACCES"?{content:`Permission denied: ${o}`,isError:!0}:{content:`Error scanning directory: ${s.message}`,isError:!0}:{content:"Unknown error scanning directory",isError:!0}}};import{spawn as ta}from"child_process";function na(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.pattern!="string")throw new Error('Input must have a "pattern" field of type string');let n=typeof e.path=="string"?e.path:process.cwd(),r;if(e.include!==void 0){if(typeof e.include!="string")throw new Error("include must be a string");r=e.include}return{pattern:e.pattern,path:n,include:r}}function ra(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Or=async(t,e)=>{let{pattern:n,path:r,include:o}=na(t);return e.aborted?{content:"Search aborted",isError:!0}:new Promise(s=>{let i=!1;function a(f){i||(i=!0,e.removeEventListener("abort",p),s(f))}let l=["-rn"];o&&l.push(`--include=${o}`),l.push(n,r);let c=ta("grep",l),d="",u="";c.stdout.on("data",f=>{d+=f.toString()}),c.stderr.on("data",f=>{u+=f.toString()});let p=()=>{c.kill(),a({content:"Search aborted",isError:!0})};e.addEventListener("abort",p),c.on("close",f=>{if(f===1){a({content:`No matches found for '${n}' in ${r}`});return}if(f===2){a({content:`grep error: ${u.trim()}`,isError:!0});return}let g=d.trimEnd();g=ra(g);let h=1e5;g.length>h&&(g=g.slice(0,h)+`
1248
+ [output truncated]`),a({content:g})}),c.on("error",f=>{a({content:`Failed to execute grep: ${f.message}`,isError:!0})})})};import{promises as oa}from"fs";var Fr=async(t,e)=>{if(!t||typeof t!="object")throw new Error("Invalid input: expected an object");let r=t.path;if(typeof r!="string")throw new Error("Invalid input: path must be a string");try{let o=await oa.readdir(r,{withFileTypes:!0}),s=o.filter(c=>c.isDirectory()).map(c=>`${c.name}/`),i=o.filter(c=>!c.isDirectory()).map(c=>c.name);s.sort(),i.sort();let a=[...s,...i];return a.length===0?{content:"(empty directory)"}:{content:a.join(`
1249
+ `)}}catch(o){if(o instanceof Error){let s=o;return s.code==="ENOENT"?{content:`Directory not found: ${r}`,isError:!0}:s.code==="ENOTDIR"?{content:`Not a directory: ${r}`,isError:!0}:s.code==="EACCES"?{content:`Permission denied: ${r}`,isError:!0}:{content:`Error listing directory: ${o.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}};function $r(){return new Map([["bash",Tr],["read_file",Ir],["write_file",Cr],["edit_file",Mr],["glob",Dr],["grep",Or],["list_directory",Fr]])}var Lr=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
1238
1250
 
1239
1251
  - Use read_file before editing to verify the exact content you want to change.
1240
1252
  - Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
@@ -1244,27 +1256,28 @@ ${d}`}}catch(i){return{content:`Error: ${i instanceof Error?i.message:String(i)}
1244
1256
  - When bash output is very long, it may be truncated. If you need the full output, redirect to a file and read it.
1245
1257
  - Use absolute paths for file operations.
1246
1258
 
1247
- When you see a \`<command-name>\` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch the same skill again. Instead, treat the \`<command-message>\` as the skill name and \`<command-args>\` as its arguments, then follow the instructions in the body block immediately following the tag.`;var $r="anthropic-direct",oa=8192,sa="claude-sonnet-4-5-20250929",ia=null;var Q=class{name=$r;tools;providerFactory;skillExecutor;constructor(e={}){let n=[...Ge];e.subagentExecutor&&n.push(er),e.skillExecutor&&n.push(tr),this.tools=e.tools??new Se({handlers:Or(),schemas:n,hookRegistry:e.hookRegistry,permissions:e.permissions,subagentExecutor:e.subagentExecutor,skillExecutor:e.skillExecutor}),this.skillExecutor=e.skillExecutor,e.clientFactory&&(this.providerFactory=e.clientFactory)}query(e){let n=e.config,r=n.apiKey&&n.apiKey.length>0?n.apiKey:process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||"";if(!r||r.length===0)throw new Error(`${$r} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let o=zt(r),s=Vt(r,o),i=this.providerFactory??ia,a=i?i(s):new ra(s),l=qt(o),c=aa(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?ae(n.model)??n.model:sa,u=la(n),p=this.tools instanceof Se?[...this.tools.toolDefs]:[...Ge],f=[...q(he()),...q()],g=n.plugins??[],h=[...f,...g],m=this.skillExecutor?xr(h):"",b=[Fr];m.length>0&&b.push(m),c&&b.push(c);let S=b.join(`
1259
+ When you see a \`<command-name>\` tag in the current conversation turn, the skill has ALREADY been loaded by the user typing a slash command. Do NOT re-invoke the skill tool to dispatch the same skill again. Instead, treat the \`<command-message>\` as the skill name and \`<command-args>\` as its arguments, then follow the instructions in the body block immediately following the tag.`;var jr="anthropic-direct",ia=8192,aa="claude-sonnet-4-5-20250929",la=null;var X=class{name=jr;tools;providerFactory;skillExecutor;constructor(e={}){let n=[...Ve];e.subagentExecutor&&n.push(nr),e.skillExecutor&&n.push(rr),this.tools=e.tools??new Ee({handlers:$r(),schemas:n,hookRegistry:e.hookRegistry,permissions:e.permissions,subagentExecutor:e.subagentExecutor,skillExecutor:e.skillExecutor}),this.skillExecutor=e.skillExecutor,e.clientFactory&&(this.providerFactory=e.clientFactory)}query(e){let n=e.config,r=n.apiKey&&n.apiKey.length>0?n.apiKey:process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||"";if(!r||r.length===0)throw new Error(`${jr} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let o=qt(r),s=Wt(r,o),i=this.providerFactory??la,a=i?i(s):new sa(s),l=Yt(o),c=ca(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?ce(n.model)??n.model:aa,u=da(n),p=this.tools instanceof Ee?[...this.tools.toolDefs]:[...Ve],f=[...q(be()),...q()],g=n.plugins??[],h=[...f,...g],m=this.skillExecutor?Pr(h):"",b=n.cwd||process.cwd(),v=[Lr];v.push(`# Environment
1260
+ - Working directory: ${b}`),m.length>0&&v.push(m),c&&v.push(c);let F=v.join(`
1248
1261
 
1249
- `);return new We({client:a,authMode:o,promptStream:e.prompt,toolDispatcher:this.tools,model:d,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:u,tools:p,userSystem:S,systemPrefix:l})}};function aa(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}function la(t){let e=t.maxOutputTokens;return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):oa}var Lr=new Q;import{Codex as Hr}from"@openai/codex-sdk";import{mkdtempSync as ca,rmSync as da,writeFileSync as ua}from"node:fs";import{tmpdir as pa}from"node:os";import{join as jr}from"node:path";var xe="openai-codex",fa=[{value:"gpt-5.4",displayName:"GPT-5.4",description:"Codex default"},{value:"gpt-5.4-mini",displayName:"GPT-5.4 mini",description:"Faster, cheaper Codex variant"}];function ma(t){let e=[];if(t.continue&&e.push("continue"),t.resumeSessionAt!==void 0&&e.push("resumeSessionAt"),t.forkSession&&e.push("forkSession"),t.persistSession===!1&&e.push("persistSession=false"),t.enableFileCheckpointing&&e.push("enableFileCheckpointing"),t.thinking!==void 0&&e.push("thinking"),t.maxBudgetUsd!==void 0&&e.push("maxBudgetUsd"),t.taskBudget!==void 0&&e.push("taskBudget"),t.plugins&&t.plugins.length>0&&e.push("plugins"),t.agents&&e.push("agents"),t.agent!==void 0&&e.push("agent"),t.onElicitation&&e.push("onElicitation"),t.hooks&&e.push("hooks"),t.canUseTool&&e.push("canUseTool"),t.mcpServers&&e.push("mcpServers"),t.includeHookEvents&&e.push("includeHookEvents"),t.agentProgressSummaries&&e.push("agentProgressSummaries"),t.includePartialMessages&&e.push("includePartialMessages"),e.length>0)throw new ge(xe,e.join(", "),`${xe} provider does not support AgentConfig fields: ${e.join(", ")}`)}function Ur(t){return t==="plan"?{sandboxMode:"read-only",approvalPolicy:"untrusted"}:{sandboxMode:"workspace-write",approvalPolicy:"never"}}function ga(t){if(t)switch(t){case"minimal":case"low":case"medium":case"high":case"xhigh":return t;case"max":return"xhigh";default:return}}function ha(t){let e=t.systemPrompt;if(e!==void 0){if(typeof e=="string")return e.length>0?e:void 0;if(typeof e=="object"&&e!==null&&"append"in e){let n=e.append;return n&&n.length>0?n:void 0}}}function ya(t){let e=ca(jr(pa(),"afk-codex-instr-")),n=jr(e,"instructions.md");return ua(n,t,"utf-8"),{path:n,dispose:()=>{try{da(e,{recursive:!0,force:!0})}catch{}}}}function ba(t){if(t.apiKey)return t.apiKey;let e=process.env.OPENAI_API_KEY??process.env.CODEX_API_KEY;return e&&e.length>0?e:void 0}function*va(t,e,n,r){if(t.type!=="thread.started"&&t.type!=="turn.started"){if(t.type==="turn.completed"){let o=t.usage;yield{type:"turn.completed",usage:{inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,totalTokens:o.input_tokens+o.output_tokens+o.cached_input_tokens,resultSubtype:"success",isError:!1,raw:{input_tokens:o.input_tokens,output_tokens:o.output_tokens,cached_input_tokens:o.cached_input_tokens}},...e!==void 0?{sessionId:e}:{}};return}if(t.type==="turn.failed"){yield{type:"error",error:new Error(t.error.message)};return}if(t.type==="error"){yield{type:"error",error:new Error(t.message)};return}(t.type==="item.started"||t.type==="item.updated"||t.type==="item.completed")&&(yield*wa(t.item,t.type==="item.completed",e,n,r))}}function*wa(t,e,n,r,o){if(t.type==="agent_message"){let s=r.get(t.id)??"";if(t.text!==s){let i=t.text.startsWith(s)?t.text.slice(s.length):t.text;r.set(t.id,t.text),i.length>0&&(yield{type:"delta.text",text:i,...n!==void 0?{sessionId:n}:{}})}e&&(yield{type:"assistant.message",text:t.text,...n!==void 0?{sessionId:n}:{}},r.delete(t.id));return}if(t.type==="reasoning"){let s=o.get(t.id)??"";if(t.text!==s){let i=t.text.startsWith(s)?t.text.slice(s.length):t.text;o.set(t.id,t.text),i.length>0&&(yield{type:"delta.reasoning",text:i,...n!==void 0?{sessionId:n}:{}})}e&&o.delete(t.id);return}if(t.type==="command_execution"){if(e){let s=t.status==="failed",i=t.exit_code!==void 0?` (exit ${t.exit_code})`:"",a=`$ ${t.command}${i}
1262
+ `);return new Je({client:a,authMode:o,promptStream:e.prompt,toolDispatcher:this.tools,model:d,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:u,tools:p,userSystem:F,systemPrefix:l})}};function ca(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}function da(t){let e=t.maxOutputTokens;return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):ia}var Hr=new X;import{Codex as Nr}from"@openai/codex-sdk";import{mkdtempSync as ua,rmSync as pa,writeFileSync as fa}from"node:fs";import{tmpdir as ma}from"node:os";import{join as Ur}from"node:path";var Pe="openai-codex",ga=[{value:"gpt-5.4",displayName:"GPT-5.4",description:"Codex default"},{value:"gpt-5.4-mini",displayName:"GPT-5.4 mini",description:"Faster, cheaper Codex variant"}];function ha(t){let e=[];if(t.continue&&e.push("continue"),t.resumeSessionAt!==void 0&&e.push("resumeSessionAt"),t.forkSession&&e.push("forkSession"),t.persistSession===!1&&e.push("persistSession=false"),t.enableFileCheckpointing&&e.push("enableFileCheckpointing"),t.thinking!==void 0&&e.push("thinking"),t.maxBudgetUsd!==void 0&&e.push("maxBudgetUsd"),t.taskBudget!==void 0&&e.push("taskBudget"),t.plugins&&t.plugins.length>0&&e.push("plugins"),t.agents&&e.push("agents"),t.agent!==void 0&&e.push("agent"),t.onElicitation&&e.push("onElicitation"),t.hooks&&e.push("hooks"),t.canUseTool&&e.push("canUseTool"),t.mcpServers&&e.push("mcpServers"),t.includeHookEvents&&e.push("includeHookEvents"),t.agentProgressSummaries&&e.push("agentProgressSummaries"),t.includePartialMessages&&e.push("includePartialMessages"),e.length>0)throw new ye(Pe,e.join(", "),`${Pe} provider does not support AgentConfig fields: ${e.join(", ")}`)}function Br(t){return t==="plan"?{sandboxMode:"read-only",approvalPolicy:"untrusted"}:{sandboxMode:"workspace-write",approvalPolicy:"never"}}function ya(t){if(t)switch(t){case"minimal":case"low":case"medium":case"high":case"xhigh":return t;case"max":return"xhigh";default:return}}function ba(t){let e=t.systemPrompt;if(e!==void 0){if(typeof e=="string")return e.length>0?e:void 0;if(typeof e=="object"&&e!==null&&"append"in e){let n=e.append;return n&&n.length>0?n:void 0}}}function va(t){let e=ua(Ur(ma(),"afk-codex-instr-")),n=Ur(e,"instructions.md");return fa(n,t,"utf-8"),{path:n,dispose:()=>{try{pa(e,{recursive:!0,force:!0})}catch{}}}}function wa(t){if(t.apiKey)return t.apiKey;let e=process.env.OPENAI_API_KEY??process.env.CODEX_API_KEY;return e&&e.length>0?e:void 0}function*ka(t,e,n,r){if(t.type!=="thread.started"&&t.type!=="turn.started"){if(t.type==="turn.completed"){let o=t.usage;yield{type:"turn.completed",usage:{inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,totalTokens:o.input_tokens+o.output_tokens+o.cached_input_tokens,resultSubtype:"success",isError:!1,raw:{input_tokens:o.input_tokens,output_tokens:o.output_tokens,cached_input_tokens:o.cached_input_tokens}},...e!==void 0?{sessionId:e}:{}};return}if(t.type==="turn.failed"){yield{type:"error",error:new Error(t.error.message)};return}if(t.type==="error"){yield{type:"error",error:new Error(t.message)};return}(t.type==="item.started"||t.type==="item.updated"||t.type==="item.completed")&&(yield*Sa(t.item,t.type==="item.completed",e,n,r))}}function*Sa(t,e,n,r,o){if(t.type==="agent_message"){let s=r.get(t.id)??"";if(t.text!==s){let i=t.text.startsWith(s)?t.text.slice(s.length):t.text;r.set(t.id,t.text),i.length>0&&(yield{type:"delta.text",text:i,...n!==void 0?{sessionId:n}:{}})}e&&(yield{type:"assistant.message",text:t.text,...n!==void 0?{sessionId:n}:{}},r.delete(t.id));return}if(t.type==="reasoning"){let s=o.get(t.id)??"";if(t.text!==s){let i=t.text.startsWith(s)?t.text.slice(s.length):t.text;o.set(t.id,t.text),i.length>0&&(yield{type:"delta.reasoning",text:i,...n!==void 0?{sessionId:n}:{}})}e&&o.delete(t.id);return}if(t.type==="command_execution"){if(e){let s=t.status==="failed",i=t.exit_code!==void 0?` (exit ${t.exit_code})`:"",a=`$ ${t.command}${i}
1250
1263
  `+(t.aggregated_output??"");yield{type:"tool.output",toolUseId:t.id,content:a,isError:s,...n!==void 0?{sessionId:n}:{}}}return}if(t.type==="file_change"){if(e){let s=t.changes.map(i=>`${i.kind} ${i.path}`).join(`
1251
- `);yield{type:"tool.output",toolUseId:t.id,content:s,isError:t.status==="failed",...n!==void 0?{sessionId:n}:{}}}return}if(t.type==="mcp_tool_call"){if(e){let s=t.status==="failed",i;t.error?i=t.error.message:t.result?i=JSON.stringify(t.result,null,2):i="",yield{type:"tool.output",toolUseId:t.id,content:i,isError:s,...n!==void 0?{sessionId:n}:{}}}return}if(t.type==="web_search"){e&&(yield{type:"tool.output",toolUseId:t.id,content:`web_search: ${t.query}`,...n!==void 0?{sessionId:n}:{}});return}if(t.type!=="todo_list"&&t.type==="error"){e&&(yield{type:"error",error:new Error(t.message)});return}}var Tt=class{startOpts;promptStream;codex;thread;currentModel;currentSandbox;currentApproval;abortController=null;pendingAbortReason=null;closed=!1;initSessionId;dispose;closeResolve=null;closedPromise;constructor(e,n,r){this.startOpts=e,this.promptStream=n,this.initSessionId=r,this.codex=new Hr(e.codexOptions),this.thread=e.resumeId?this.codex.resumeThread(e.resumeId,e.threadOptions):this.codex.startThread(e.threadOptions),this.currentModel=e.threadOptions.model,this.currentSandbox=e.threadOptions.sandboxMode??"workspace-write",this.currentApproval=e.threadOptions.approvalPolicy??"never",e.instructionsDispose!==void 0&&(this.dispose=e.instructionsDispose),this.closedPromise=new Promise(o=>{this.closeResolve=()=>o("__closed__")})}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,...this.currentModel!==void 0?{model:this.currentModel}:{},permissionMode:this.sandboxToPermissionMode(),cwd:this.startOpts.threadOptions.workingDirectory??process.cwd(),tools:["Bash","Read","Write","Edit"],slashCommands:[],skills:[],plugins:[],mcpServers:[],apiKeySource:this.startOpts.codexOptions.apiKey!==void 0?"apiKey":"codex-cli",version:"codex-sdk"}};let n=new Map,r=new Map,o=this.initSessionId,s=this.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let i=await Promise.race([s.next(),this.closedPromise]);if(i==="__closed__")break;let a=i;if(a.done)break;let l=a.value,c=new AbortController;if(this.abortController=c,this.pendingAbortReason!==null&&!c.signal.aborted&&(c.abort(this.pendingAbortReason),this.pendingAbortReason=null),c.signal.aborted)return;let d;try{let u=typeof l.content=="string"?l.content:l.content.map(p=>{if(typeof p=="object"&&p&&"type"in p){if(p.type==="text")return p.text;if(p.type==="image")return"[image omitted]"}return""}).join(`
1252
- `);d=await this.thread.runStreamed(u,{signal:c.signal})}catch(u){if(c.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}try{for await(let u of d.events){if(this.closed)return;u.type==="thread.started"&&(o=u.thread_id),yield*va(u,o,n,r)}}catch(u){if(c.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}finally{this.abortController===c&&(this.abortController=null)}}}catch(i){yield{type:"error",error:i instanceof Error?i:new Error(String(i))}}finally{try{await s.return?.()}catch{}}}sandboxToPermissionMode(){return this.currentSandbox==="read-only"||this.currentApproval==="untrusted"?"plan":"bypassPermissions"}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){this.currentModel=e;let n={...this.startOpts.threadOptions,...e!==void 0?{model:e}:{},sandboxMode:this.currentSandbox,approvalPolicy:this.currentApproval},r=this.thread.id;this.thread=r?this.codex.resumeThread(r,n):this.codex.startThread(n),this.startOpts.threadOptions=n}async setPermissionMode(e){let{sandboxMode:n,approvalPolicy:r}=Ur(e);this.currentSandbox=n,this.currentApproval=r;let o={...this.startOpts.threadOptions,sandboxMode:n,approvalPolicy:r},s=this.thread.id;this.thread=s?this.codex.resumeThread(s,o):this.codex.startThread(o),this.startOpts.threadOptions=o}async supportedCommands(){return[]}async supportedModels(){return fa.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:null}}async mcpServerStatus(){return[]}async accountInfo(){return{}}async rewindFiles(e,n){throw new ge(xe,"rewindFiles",`${xe} provider does not support file checkpoint rewind.`)}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),this.dispose?.()}getThread(){return this.thread}},ka=null;var Ye=class{name=xe;query(e){ma(e.config);let n=ba(e.config),r=ga(e.config.effort),{sandboxMode:o,approvalPolicy:s}=Ur(e.config.permissionMode),i={...e.config.model!==void 0?{model:e.config.model}:{},sandboxMode:o,approvalPolicy:s,...r!==void 0?{modelReasoningEffort:r}:{},skipGitRepoCheck:!0,workingDirectory:process.cwd()},a=ha(e.config),l={};n!==void 0&&(l.apiKey=n);let c;if(a!==void 0){let{path:g,dispose:h}=ya(a);l.config={...l.config??{},model_instructions_file:g},c=h}A(`\u{1F7E2} OpenAICodexProvider: creating Codex thread (model=${String(e.config.model)}, sandbox=${o}, approval=${s})`);let d=ka,u=d??(g=>new Hr(g)),p=`codex-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,f=new Tt({threadOptions:i,codexOptions:l,...e.config.resume!==void 0?{resumeId:e.config.resume}:{},...c!==void 0?{instructionsDispose:c}:{}},e.prompt,p);if(d){let g=u(l);f.codex=g,f.thread=e.config.resume?g.resumeThread(e.config.resume,i):g.startThread(i)}return f}},Nr=new Ye;var Sa=new Set(["opus","opus_1m","sonnet","sonnet_1m","haiku","auto"]);function de(t){if(!t)return"anthropic-direct";let e=t.trim().toLowerCase();return!e||Sa.has(e)||e.startsWith("claude-")||e.startsWith("claude_")?"anthropic-direct":e.startsWith("gpt-")||e.startsWith("gpt_")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")||e.startsWith("codex-")||e.startsWith("codex_")||e==="codex"?"openai-codex":"anthropic-direct"}function Br(t){return de(t)==="openai-codex"?Nr:Lr}async function Kr(t,e,n={}){t&&await t.dispatch(e,n.signal)}async function Gr(t,e,n={}){if(t)try{await t.dispatch(e,n.signal)}catch(r){if(r instanceof U||r instanceof G){A(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}A(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var Je=class{pendingResolve=null;bufferedMessage=null;getSessionId;constructor(e){this.getSessionId=e}pushUserMessage(e){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:e,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessage=e}createIterable(){let e=this;return{[Symbol.asyncIterator](){return{next(){if(e.bufferedMessage!==null){let n=e.bufferedMessage;e.bufferedMessage=null;let r=e.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{e.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}};function xa(t){let e=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=t.match(e);if(!n||!n[1]||!n[2]||!n[3])return null;let r=n[1],o=n[2],s=n[3],i=parseFloat(r),a=i;o==="KB"?a=i*1024:o==="MB"?a=i*1024*1024:o==="GB"&&(a=i*1024*1024*1024);let l=r;return i%1===0&&(l=String(Math.floor(i))),l+=o,{sizeLabel:l,sizeBytes:Math.round(a),absolutePath:s.trim()}}function Pa(t){if(t<1024)return`${t}B`;let e=t/1024;if(e<1024)return e%1===0?`${Math.floor(e)}KB`:`${e.toFixed(1)}KB`;let n=e/1024;if(n<1024)return n%1===0?`${Math.floor(n)}MB`:`${n.toFixed(1)}MB`;let r=n/1024;return r%1===0?`${Math.floor(r)}GB`:`${r.toFixed(1)}GB`}function Ea(t){let e=Buffer.byteLength(t,"utf8"),n=Pa(e),r=t.split(`
1253
- `);if(r.length<=1&&t.length<=80)return{content:t,truncated:!1,sizeBytes:e,sizeLabel:n};if(r.length<=1)return t.length<=80?{content:t,truncated:!1,sizeBytes:e,sizeLabel:n}:{content:t.substring(0,80)+"\u2026",truncated:!0,sizeBytes:e,sizeLabel:n};if(t.length<=80)return{content:t,truncated:!1,sizeBytes:e,sizeLabel:n};let o=r[0]??"",s=o;return o.length>80&&(s=o.substring(0,80)+"\u2026"),{content:s+`\u2026+${r.length} lines`,truncated:!0,lineCount:r.length,sizeBytes:e,sizeLabel:n}}function Aa(t,e){let n={...t.raw??{}};return t.inputTokens!==void 0&&(n.input_tokens=t.inputTokens),t.outputTokens!==void 0&&(n.output_tokens=t.outputTokens),t.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=t.cachedInputTokens),t.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=t.cacheCreationTokens),t.totalTokens!==void 0&&(n.total_tokens=t.totalTokens),{sessionId:e,stopReason:t.stopReason??void 0,resultSubtype:t.resultSubtype,durationMs:t.durationMs,durationApiMs:t.durationApiMs,totalCostUsd:t.totalCostUsd,isError:t.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:t.modelUsage,permissionDenials:t.permissionDenials,errors:t.errors}}function Ta(t,e){let n=e.info;t.setSessionMetadata(r=>({...r,sessionId:n.sessionId,model:n.model??r.model,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},tools:n.tools?[...n.tools]:r.tools,slashCommands:n.slashCommands?[...n.slashCommands]:r.slashCommands,skills:n.skills?[...n.skills]:r.skills,plugins:n.plugins?n.plugins.map(o=>({...o})):r.plugins,mcpServers:n.mcpServers?n.mcpServers.map(o=>({...o})):r.mcpServers,...n.apiKeySource!==void 0?{apiKeySource:n.apiKeySource}:{},...n.version!==void 0?{claudeCodeVersion:n.version}:{},...n.outputStyle!==void 0?{outputStyle:n.outputStyle}:{}})),t.updateSessionIdentity(n.sessionId),t.resolveInitialization()}function Ia(t,e){t.setSessionMetadata(n=>({...n,sessionId:e.sessionId,...e.permissionMode!==void 0?{permissionMode:e.permissionMode}:{permissionMode:n.permissionMode},...e.status!==void 0?{status:e.status}:{}}))}function Ca(t,e){let n=xa(e.content);if(n){t.push({type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:`Output persisted (${n.sizeLabel}) \u2192 ${n.absolutePath}`,isError:e.isError===!0,persistedPath:n.absolutePath,sizeBytes:n.sizeBytes,sizeLabel:n.sizeLabel}});return}let{content:r,truncated:o,lineCount:s,sizeBytes:i,sizeLabel:a}=Ea(e.content);t.push({type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:r,isError:e.isError===!0,sizeBytes:i,sizeLabel:a,...o&&{truncated:o},...s!==void 0&&{lineCount:s}}})}function Ma(t,e){if(!e)return;let n={role:"assistant",content:e,timestamp:new Date};t.conversationHistory.push(n),t.messageQueue.push({type:"message",message:n})}async function zr(t){try{for await(let e of t.providerStream)switch(e.type){case"session.init":Ta(t,e);break;case"session.status":Ia(t,e);break;case"delta.text":t.messageQueue.push({type:"chunk",chunk:{type:"content",content:e.text,metadata:{eventType:"delta",deltaType:"text_delta"}}});break;case"delta.reasoning":t.messageQueue.push({type:"chunk",chunk:{type:"thinking",content:e.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}});break;case"assistant.message":e.sessionId&&t.updateSessionIdentity(e.sessionId),Ma(t,e.text);break;case"tool.use.start":t.messageQueue.push({type:"chunk",chunk:{type:"tool_use_detail",toolUseId:e.toolUseId,toolName:e.toolName,toolInput:e.toolInput}});break;case"tool.use":t.messageQueue.push({type:"chunk",chunk:{type:"tool_use",content:e.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:e.toolUseIds}}});break;case"tool.output":Ca(t.messageQueue,e);break;case"progress":t.messageQueue.push({type:"progress",progress:{taskId:e.progress.taskId,description:e.progress.description,...e.progress.summary!==void 0?{summary:e.progress.summary}:{},...e.progress.lastToolName!==void 0?{lastToolName:e.progress.lastToolName}:{},totalTokens:e.progress.totalTokens,toolUses:e.progress.toolUses,durationMs:e.progress.durationMs}});break;case"suggestion":t.messageQueue.push({type:"suggestion",suggestion:e.suggestion});break;case"turn.completed":let n=Aa(e.usage,e.sessionId??t.getSessionMetadata().sessionId);t.setLastResponseMetadata(n);for(let r=t.conversationHistory.length-1;r>=0;r--){let o=t.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}t.messageQueue.push({type:"done",metadata:n});break;case"error":throw e.error}t.resolveInitializationIfNeeded(),t.messageQueue.complete()}catch(e){let n=e instanceof Error?e:new Error(String(e));throw t.resolveInitializationIfNeeded(),t.messageQueue.fail(n),n}}function Vr(t,e,n){t&&(t.aborted?e.abort(t.reason):t.addEventListener("abort",()=>{e.signal.aborted||e.abort(t.reason)},{once:!0})),e.signal.addEventListener("abort",n,{once:!0})}function qr(t,e){let n=t.permissionMode??"bypassPermissions",r=t.persistSession??!0,o={sessionId:t.sessionId,configuredSessionId:t.sessionId,resume:t.resume,resumeSessionAt:t.resumeSessionAt,continue:t.continue,forkSession:t.forkSession,persistSession:r},s={sessionId:t.sessionId,model:e,permissionMode:n};return{sessionIdentity:o,metadata:s}}async function Wr(t){try{await Kr(t.hookRegistry,{event:"SessionStart",sessionId:t.sessionId()},{signal:t.abortSignal}),await zr({providerStream:t.providerQuery,messageQueue:t.messageQueue,conversationHistory:t.conversationHistory,getSessionMetadata:()=>t.stateManager.getSessionMetadata(),setSessionMetadata:e=>t.stateManager.setSessionMetadata(e),updateSessionIdentity:e=>t.stateManager.updateSessionIdentity(e),resolveInitialization:()=>t.stateManager.resolveInitializationOnce(),resolveInitializationIfNeeded:()=>t.stateManager.resolveInitializationIfNeeded(),setLastResponseMetadata:t.setLastResponseMetadata})}catch(e){let n=e instanceof Error?e:new Error(String(e));t.stateManager.isInitializationSettled()||t.stateManager.rejectInitializationOnce(n),await t.dispatchEnd("error").catch(()=>{})}}var Qe=class{initializationPromise;resolveInitialization;rejectInitialization;initializationSettled=!1;sessionMetadata;sessionIdentity;constructor(e,n){this.sessionIdentity=e,this.sessionMetadata=n,this.initializationPromise=new Promise((r,o)=>{this.resolveInitialization=r,this.rejectInitialization=o})}waitForInitialization(){return this.initializationPromise}getSessionIdentity(){return{...this.sessionIdentity,sessionId:this.getSessionId()}}getSessionMetadata(){return{...this.sessionMetadata,sessionId:this.getSessionId()}}getSessionId(){return this.sessionMetadata.sessionId??this.sessionIdentity.sessionId}updateSessionIdentity(e){e&&(this.sessionIdentity={...this.sessionIdentity,sessionId:e},this.sessionMetadata={...this.sessionMetadata,sessionId:e})}setSessionMetadata(e){this.sessionMetadata=e(this.sessionMetadata)}resolveInitializationIfNeeded(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}resolveInitializationOnce(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}rejectInitializationOnce(e){this.initializationSettled||(this.initializationSettled=!0,this.rejectInitialization(e))}isInitializationSettled(){return this.initializationSettled}};async function Yr(t,e){return await new Promise((n,r)=>{let o=null,s="",i=!1,a=c=>{i||(i=!0,clearTimeout(l),c())},l=Number.isFinite(e)&&e>0?setTimeout(()=>{a(()=>r(new Error("Response timeout")))},e):void 0;(async()=>{try{for await(let c of t){if(process.env.AFK_CODEX_DEBUG&&console.log("[wait] got event:",c.type),c.type==="error"){a(()=>r(c.error));return}if(c.type==="chunk"&&c.chunk.type==="content"&&(s+=c.chunk.content),c.type==="message"&&c.message.role==="assistant"&&(o=c.message),c.type==="done"){if(process.env.AFK_CODEX_DEBUG&&console.log("[wait] settling with done; assistantMessage=",!!o,"streamedContent=",s.length),o){let d=o;a(()=>n({...d,metadata:c.metadata}));return}if(s){a(()=>n({role:"assistant",content:s,metadata:c.metadata,timestamp:new Date}));return}}}a(o?()=>n(o):s?()=>n({role:"assistant",content:s,timestamp:new Date}):()=>r(new Error("No assistant response received")))}catch(c){a(()=>r(c instanceof Error?c:new Error(String(c))))}})()})}var Z=class{config;currentState="idle";messageQueue;providerQuery;conversationHistory=[];turnCount=0;lastResponseMetadata=null;processingPromise=null;inputStream;abortController;hookRegistry;sessionEndDispatched=!1;stateManager;constructor(e){this.config=e,this.abortController=new AbortController,this.hookRegistry=e.hookRegistry,Vr(e.abortSignal,this.abortController,()=>{this.onAbort()}),this.initSdkLifecycle()}initSdkLifecycle(){this.messageQueue=new _e;let e=ae(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=qr(this.config,e);this.stateManager=new Qe(n,r),this.inputStream=new Je(()=>this.sessionId);let o=this.config.provider??Br(e);A(`\u{1F7E2} AgentSession: Creating query session via provider=${o.name}`),this.providerQuery=o.query({prompt:this.inputStream.createIterable(),config:this.config}),this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionEndDispatched=!1,this.currentState="idle",this.processingPromise=Wr({providerQuery:this.providerQuery,messageQueue:this.messageQueue,conversationHistory:this.conversationHistory,stateManager:this.stateManager,hookRegistry:this.hookRegistry,abortSignal:this.abortController.signal,sessionId:()=>this.sessionId,setLastResponseMetadata:s=>this.lastResponseMetadata=s,dispatchEnd:s=>this.dispatchSessionEndOnce(s)})}get state(){return this.currentState}get sessionId(){return this.stateManager.getSessionId()}get abortSignal(){return this.abortController.signal}async sendMessage(e,n={}){this.assertCanSend(),this.currentState=n.stream?"streaming":"processing";let r={role:"user",content:e,timestamp:new Date};this.conversationHistory.push(r);let o=this.config.timeoutMs??$e;try{this.inputStream.pushUserMessage(e);let s=await Le(Yr(this.messageQueue,o),o,{controller:this.abortController,label:this.sessionId??"session"});return this.turnCount++,s}finally{this.state!=="closed"&&(this.currentState="idle")}}async*sendMessageStream(e){this.assertCanSend(),this.currentState="streaming";let r={role:"user",content:typeof e=="string"?e:this.summarizeContentBlocks(e),timestamp:new Date};this.conversationHistory.push(r),this.inputStream.pushUserMessage(e);try{for await(let o of this.messageQueue)if(o.type==="done"&&this.turnCount++,yield o,o.type==="done"||o.type==="error")break}finally{this.state!=="closed"&&(this.currentState="idle")}}summarizeContentBlocks(e){let n=[],r=0;for(let s of e)s.type==="text"?n.push(s.text):s.type==="image"&&r++;let o=n.join(" ");return r>0&&(o=o?`${o} [+ ${r} image(s)]`:`[+ ${r} image(s)]`),o||"[content block(s)]"}async interrupt(){this.currentState!=="streaming"&&this.currentState!=="processing"||(this.currentState="idle",await this.providerQuery.interrupt())}async reset(){if(this.currentState==="closed")throw new Error("Cannot reset: session is closed");if(this.abortController.signal.aborted)throw new G("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset");try{await this.providerQuery.close()}catch{}this.processingPromise&&await Promise.race([this.processingPromise,new Promise(e=>setTimeout(e,lt))]).catch(()=>{}),this.messageQueue.complete(),this.stateManager.resolveInitializationIfNeeded();try{this.initSdkLifecycle()}catch(e){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async onAbort(){try{await this.providerQuery.interrupt()}catch{}}async setModel(e){let n=ae(e),r=this.stateManager.getSessionMetadata();await this.providerQuery.setModel(n??r.model??""),n&&this.stateManager.setSessionMetadata(o=>({...o,model:n}))}async setPermissionMode(e){await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:e}))}waitForInitialization(){return this.stateManager.waitForInitialization()}getSessionIdentity(){return this.stateManager.getSessionIdentity()}getSessionMetadata(){return this.stateManager.getSessionMetadata()}getQuery(){return this.providerQuery}supportedCommands(){return this.providerQuery.supportedCommands()}supportedModels(){return this.providerQuery.supportedModels()}supportedAgents(){return this.providerQuery.supportedAgents()}getContextUsage(){return this.providerQuery.getContextUsage()}mcpServerStatus(){return this.providerQuery.mcpServerStatus()}accountInfo(){return this.providerQuery.accountInfo()}rewindFiles(e,n){return this.providerQuery.rewindFiles(e,n)}async compact(){if(this.currentState==="closed")throw new Error("Cannot compact: session is closed");if(this.currentState!=="idle")return{compacted:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let e=this.providerQuery.compact?.bind(this.providerQuery);return e?e():{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){return this.messageQueue}getInputStreamRef(){return{pushUserMessage:e=>this.inputStream.pushUserMessage(e)}}getHistory(){return[...this.conversationHistory]}getTurnCount(){return this.turnCount}async close(){if(this.currentState!=="closed"){this.currentState="closed",this.abortController.signal.aborted||this.abortController.abort("closed"),this.stateManager.resolveInitializationIfNeeded();try{this.providerQuery.close()}catch{}if(this.processingPromise)try{await Promise.race([this.processingPromise,new Promise(e=>setTimeout(e,lt))])}catch{}this.messageQueue.complete(),await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await Gr(this.hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:e}))}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new G("Cannot send message: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")throw new Error("Cannot send message: session is busy");if(this.config.maxTurns&&this.turnCount>=this.config.maxTurns)throw new Error(`Maximum turns (${this.config.maxTurns}) exceeded`)}};var Ct=class{handlers=new Map;register(e,n){let r=this.handlers.get(e);return r||(r=[],this.handlers.set(e,r)),r.push(n),()=>{let o=this.handlers.get(e);if(!o)return;let s=o.indexOf(n);s>=0&&o.splice(s,1)}}count(e){return this.handlers.get(e)?.length??0}async dispatch(e,n){It(n,e.event);let r=this.handlers.get(e.event);if(!r||r.length===0)return{};let o=r.slice(),s={};for(let i of o){It(n,e.event);let a;try{a=await i(e)}catch(l){throw new U(`hook handler threw during ${e.event}`,e.event,l instanceof Error?l.message:String(l),{cause:l})}if(It(n,e.event),_a(a))throw new U(`hook handler blocked ${e.event}${a.reason?`: ${a.reason}`:""}`,e.event,a.reason);s=a}return s}};function _a(t){return t.continue===!1||t.decision==="block"}function It(t,e){if(t?.aborted){let n=t.reason,r=`aborted during ${e}${n?`: ${String(n)}`:""}`;throw new G(r)}}function Jr(){return new Ct}function Qr(){return Jr()}var Ra=["shadow-verify","shadow_verify","resolve","diagnose","appmap","qualify","mint"],Da=[/\bverdict(s)?\b/i,/\brecommend(ation)?s?\b/i,/\bshould\s+(delete|remove|rewrite|refactor|rename|reject|merge|revert|disable)\b/i,/\b(USELESS|KEEP|REJECT|APPROVE|SALVAGE|BLOCK|FAIL)\b/,/\b(redundant|duplicated|superseded|obsolete)\b/i,/\bvulnerab\w*\b/i,/\bunused\b/i,/\bbroken\b/i,/\bregress\w*\b/i,/\|\s*(status|verdict|decision|severity|risk|finding|priority|holds\??)\s*\|/i,/\bfound\s+\d+\s*(issue|problem|bug|error|finding|vulnerabilit)/i,/\b(critical|high|medium|low)\s+(severity|priority|risk)\b/i,/\bclaim(s)?\b[^\n]{0,80}\b(holds?|refuted|verified|partial|confirmed|disputed)\b/i,/\b(root\s*cause|incident)\b/i,/\brecommend\s+(removing|deleting|rewriting|refactoring|merging|reverting)\b/i,/\bI\s+(applied|committed|pushed|edited|wrote|fixed|patched|reset|restored|staged)\b/i,/\b(applied|committed|pushed|fixed|patched)\s+(the|these|those)\s+(change|commit|fix|patch|edit)/i],Oa=[/\bverifier_verdict\b/i,/"\s*claim\s*"\s*:/i,/\bre-derived\b[^.\n]{0,80}\bindependent/i,/\bindependently\s+(re-derived|re-verified|verified|checked)\b/i,/\bverifier\s+(agrees|disagrees|confirms|refutes)\b/i],Fa=`shadow-verify nudge:
1264
+ `);yield{type:"tool.output",toolUseId:t.id,content:s,isError:t.status==="failed",...n!==void 0?{sessionId:n}:{}}}return}if(t.type==="mcp_tool_call"){if(e){let s=t.status==="failed",i;t.error?i=t.error.message:t.result?i=JSON.stringify(t.result,null,2):i="",yield{type:"tool.output",toolUseId:t.id,content:i,isError:s,...n!==void 0?{sessionId:n}:{}}}return}if(t.type==="web_search"){e&&(yield{type:"tool.output",toolUseId:t.id,content:`web_search: ${t.query}`,...n!==void 0?{sessionId:n}:{}});return}if(t.type!=="todo_list"&&t.type==="error"){e&&(yield{type:"error",error:new Error(t.message)});return}}var Ct=class{startOpts;promptStream;codex;thread;currentModel;currentSandbox;currentApproval;abortController=null;pendingAbortReason=null;closed=!1;initSessionId;dispose;closeResolve=null;closedPromise;constructor(e,n,r){this.startOpts=e,this.promptStream=n,this.initSessionId=r,this.codex=new Nr(e.codexOptions),this.thread=e.resumeId?this.codex.resumeThread(e.resumeId,e.threadOptions):this.codex.startThread(e.threadOptions),this.currentModel=e.threadOptions.model,this.currentSandbox=e.threadOptions.sandboxMode??"workspace-write",this.currentApproval=e.threadOptions.approvalPolicy??"never",e.instructionsDispose!==void 0&&(this.dispose=e.instructionsDispose),this.closedPromise=new Promise(o=>{this.closeResolve=()=>o("__closed__")})}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,...this.currentModel!==void 0?{model:this.currentModel}:{},permissionMode:this.sandboxToPermissionMode(),cwd:this.startOpts.threadOptions.workingDirectory??process.cwd(),tools:["Bash","Read","Write","Edit"],slashCommands:[],skills:[],plugins:[],mcpServers:[],apiKeySource:this.startOpts.codexOptions.apiKey!==void 0?"apiKey":"codex-cli",version:"codex-sdk"}};let n=new Map,r=new Map,o=this.initSessionId,s=this.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let i=await Promise.race([s.next(),this.closedPromise]);if(i==="__closed__")break;let a=i;if(a.done)break;let l=a.value,c=new AbortController;if(this.abortController=c,this.pendingAbortReason!==null&&!c.signal.aborted&&(c.abort(this.pendingAbortReason),this.pendingAbortReason=null),c.signal.aborted)return;let d;try{let u=typeof l.content=="string"?l.content:l.content.map(p=>{if(typeof p=="object"&&p&&"type"in p){if(p.type==="text")return p.text;if(p.type==="image")return"[image omitted]"}return""}).join(`
1265
+ `);d=await this.thread.runStreamed(u,{signal:c.signal})}catch(u){if(c.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}try{for await(let u of d.events){if(this.closed)return;u.type==="thread.started"&&(o=u.thread_id),yield*ka(u,o,n,r)}}catch(u){if(c.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}finally{this.abortController===c&&(this.abortController=null)}}}catch(i){yield{type:"error",error:i instanceof Error?i:new Error(String(i))}}finally{try{await s.return?.()}catch{}}}sandboxToPermissionMode(){return this.currentSandbox==="read-only"||this.currentApproval==="untrusted"?"plan":"bypassPermissions"}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){this.currentModel=e;let n={...this.startOpts.threadOptions,...e!==void 0?{model:e}:{},sandboxMode:this.currentSandbox,approvalPolicy:this.currentApproval},r=this.thread.id;this.thread=r?this.codex.resumeThread(r,n):this.codex.startThread(n),this.startOpts.threadOptions=n}async setPermissionMode(e){let{sandboxMode:n,approvalPolicy:r}=Br(e);this.currentSandbox=n,this.currentApproval=r;let o={...this.startOpts.threadOptions,sandboxMode:n,approvalPolicy:r},s=this.thread.id;this.thread=s?this.codex.resumeThread(s,o):this.codex.startThread(o),this.startOpts.threadOptions=o}async supportedCommands(){return[]}async supportedModels(){return ga.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:null}}async mcpServerStatus(){return[]}async accountInfo(){return{}}async rewindFiles(e,n){throw new ye(Pe,"rewindFiles",`${Pe} provider does not support file checkpoint rewind.`)}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),this.dispose?.()}getThread(){return this.thread}},xa=null;var Qe=class{name=Pe;query(e){ha(e.config);let n=wa(e.config),r=ya(e.config.effort),{sandboxMode:o,approvalPolicy:s}=Br(e.config.permissionMode),i={...e.config.model!==void 0?{model:e.config.model}:{},sandboxMode:o,approvalPolicy:s,...r!==void 0?{modelReasoningEffort:r}:{},skipGitRepoCheck:!0,workingDirectory:process.cwd()},a=ba(e.config),l={};n!==void 0&&(l.apiKey=n);let c;if(a!==void 0){let{path:g,dispose:h}=va(a);l.config={...l.config??{},model_instructions_file:g},c=h}A(`\u{1F7E2} OpenAICodexProvider: creating Codex thread (model=${String(e.config.model)}, sandbox=${o}, approval=${s})`);let d=xa,u=d??(g=>new Nr(g)),p=`codex-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,f=new Ct({threadOptions:i,codexOptions:l,...e.config.resume!==void 0?{resumeId:e.config.resume}:{},...c!==void 0?{instructionsDispose:c}:{}},e.prompt,p);if(d){let g=u(l);f.codex=g,f.thread=e.config.resume?g.resumeThread(e.config.resume,i):g.startThread(i)}return f}},Kr=new Qe;var Ea=new Set(["opus","opus_1m","sonnet","sonnet_1m","haiku","auto"]);function pe(t){if(!t)return"anthropic-direct";let e=t.trim().toLowerCase();return!e||Ea.has(e)||e.startsWith("claude-")||e.startsWith("claude_")?"anthropic-direct":e.startsWith("gpt-")||e.startsWith("gpt_")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")||e.startsWith("codex-")||e.startsWith("codex_")||e==="codex"?"openai-codex":"anthropic-direct"}function Gr(t){return pe(t)==="openai-codex"?Kr:Hr}async function zr(t,e,n={}){t&&await t.dispatch(e,n.signal)}async function Vr(t,e,n={}){if(t)try{await t.dispatch(e,n.signal)}catch(r){if(r instanceof U||r instanceof G){A(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}A(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var Xe=class{pendingResolve=null;bufferedMessage=null;getSessionId;constructor(e){this.getSessionId=e}pushUserMessage(e){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:e,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessage=e}createIterable(){let e=this;return{[Symbol.asyncIterator](){return{next(){if(e.bufferedMessage!==null){let n=e.bufferedMessage;e.bufferedMessage=null;let r=e.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{e.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}};function Pa(t){let e=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=t.match(e);if(!n||!n[1]||!n[2]||!n[3])return null;let r=n[1],o=n[2],s=n[3],i=parseFloat(r),a=i;o==="KB"?a=i*1024:o==="MB"?a=i*1024*1024:o==="GB"&&(a=i*1024*1024*1024);let l=r;return i%1===0&&(l=String(Math.floor(i))),l+=o,{sizeLabel:l,sizeBytes:Math.round(a),absolutePath:s.trim()}}function Aa(t){if(t<1024)return`${t}B`;let e=t/1024;if(e<1024)return e%1===0?`${Math.floor(e)}KB`:`${e.toFixed(1)}KB`;let n=e/1024;if(n<1024)return n%1===0?`${Math.floor(n)}MB`:`${n.toFixed(1)}MB`;let r=n/1024;return r%1===0?`${Math.floor(r)}GB`:`${r.toFixed(1)}GB`}function Ta(t){let e=Buffer.byteLength(t,"utf8"),n=Aa(e),r=t.split(`
1266
+ `);if(r.length<=1&&t.length<=80)return{content:t,truncated:!1,sizeBytes:e,sizeLabel:n};if(r.length<=1)return t.length<=80?{content:t,truncated:!1,sizeBytes:e,sizeLabel:n}:{content:t.substring(0,80)+"\u2026",truncated:!0,sizeBytes:e,sizeLabel:n};if(t.length<=80)return{content:t,truncated:!1,sizeBytes:e,sizeLabel:n};let o=r[0]??"",s=o;return o.length>80&&(s=o.substring(0,80)+"\u2026"),{content:s+`\u2026+${r.length} lines`,truncated:!0,lineCount:r.length,sizeBytes:e,sizeLabel:n}}function Ia(t,e){let n={...t.raw??{}};return t.inputTokens!==void 0&&(n.input_tokens=t.inputTokens),t.outputTokens!==void 0&&(n.output_tokens=t.outputTokens),t.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=t.cachedInputTokens),t.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=t.cacheCreationTokens),t.totalTokens!==void 0&&(n.total_tokens=t.totalTokens),{sessionId:e,stopReason:t.stopReason??void 0,resultSubtype:t.resultSubtype,durationMs:t.durationMs,durationApiMs:t.durationApiMs,totalCostUsd:t.totalCostUsd,isError:t.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:t.modelUsage,permissionDenials:t.permissionDenials,errors:t.errors}}function Ca(t,e){let n=e.info;t.setSessionMetadata(r=>({...r,sessionId:n.sessionId,model:n.model??r.model,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},tools:n.tools?[...n.tools]:r.tools,slashCommands:n.slashCommands?[...n.slashCommands]:r.slashCommands,skills:n.skills?[...n.skills]:r.skills,plugins:n.plugins?n.plugins.map(o=>({...o})):r.plugins,mcpServers:n.mcpServers?n.mcpServers.map(o=>({...o})):r.mcpServers,...n.apiKeySource!==void 0?{apiKeySource:n.apiKeySource}:{},...n.version!==void 0?{claudeCodeVersion:n.version}:{},...n.outputStyle!==void 0?{outputStyle:n.outputStyle}:{}})),t.updateSessionIdentity(n.sessionId),t.resolveInitialization()}function Ma(t,e){t.setSessionMetadata(n=>({...n,sessionId:e.sessionId,...e.permissionMode!==void 0?{permissionMode:e.permissionMode}:{permissionMode:n.permissionMode},...e.status!==void 0?{status:e.status}:{}}))}function _a(t,e){let n=Pa(e.content);if(n){t.push({type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:`Output persisted (${n.sizeLabel}) \u2192 ${n.absolutePath}`,isError:e.isError===!0,persistedPath:n.absolutePath,sizeBytes:n.sizeBytes,sizeLabel:n.sizeLabel}});return}let{content:r,truncated:o,lineCount:s,sizeBytes:i,sizeLabel:a}=Ta(e.content);t.push({type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:r,isError:e.isError===!0,sizeBytes:i,sizeLabel:a,...o&&{truncated:o},...s!==void 0&&{lineCount:s}}})}function Ra(t,e){if(!e)return;let n={role:"assistant",content:e,timestamp:new Date};t.conversationHistory.push(n),t.messageQueue.push({type:"message",message:n})}async function qr(t){try{for await(let e of t.providerStream)switch(e.type){case"session.init":Ca(t,e);break;case"session.status":Ma(t,e);break;case"delta.text":t.messageQueue.push({type:"chunk",chunk:{type:"content",content:e.text,metadata:{eventType:"delta",deltaType:"text_delta"}}});break;case"delta.reasoning":t.messageQueue.push({type:"chunk",chunk:{type:"thinking",content:e.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}});break;case"assistant.message":e.sessionId&&t.updateSessionIdentity(e.sessionId),Ra(t,e.text);break;case"tool.use.start":t.messageQueue.push({type:"chunk",chunk:{type:"tool_use_detail",toolUseId:e.toolUseId,toolName:e.toolName,toolInput:e.toolInput}});break;case"tool.use":t.messageQueue.push({type:"chunk",chunk:{type:"tool_use",content:e.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:e.toolUseIds}}});break;case"tool.output":_a(t.messageQueue,e);break;case"progress":t.messageQueue.push({type:"progress",progress:{taskId:e.progress.taskId,description:e.progress.description,...e.progress.summary!==void 0?{summary:e.progress.summary}:{},...e.progress.lastToolName!==void 0?{lastToolName:e.progress.lastToolName}:{},totalTokens:e.progress.totalTokens,toolUses:e.progress.toolUses,durationMs:e.progress.durationMs}});break;case"suggestion":t.messageQueue.push({type:"suggestion",suggestion:e.suggestion});break;case"turn.completed":let n=Ia(e.usage,e.sessionId??t.getSessionMetadata().sessionId);t.setLastResponseMetadata(n);for(let r=t.conversationHistory.length-1;r>=0;r--){let o=t.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}t.messageQueue.push({type:"done",metadata:n});break;case"error":throw e.error}t.resolveInitializationIfNeeded(),t.messageQueue.complete()}catch(e){let n=e instanceof Error?e:new Error(String(e));throw t.resolveInitializationIfNeeded(),t.messageQueue.fail(n),n}}function Wr(t,e,n){t&&(t.aborted?e.abort(t.reason):t.addEventListener("abort",()=>{e.signal.aborted||e.abort(t.reason)},{once:!0})),e.signal.addEventListener("abort",n,{once:!0})}function Yr(t,e){let n=t.permissionMode??"bypassPermissions",r=t.persistSession??!0,o={sessionId:t.sessionId,configuredSessionId:t.sessionId,resume:t.resume,resumeSessionAt:t.resumeSessionAt,continue:t.continue,forkSession:t.forkSession,persistSession:r},s={sessionId:t.sessionId,model:e,permissionMode:n};return{sessionIdentity:o,metadata:s}}async function Jr(t){try{await zr(t.hookRegistry,{event:"SessionStart",sessionId:t.sessionId()},{signal:t.abortSignal}),await qr({providerStream:t.providerQuery,messageQueue:t.messageQueue,conversationHistory:t.conversationHistory,getSessionMetadata:()=>t.stateManager.getSessionMetadata(),setSessionMetadata:e=>t.stateManager.setSessionMetadata(e),updateSessionIdentity:e=>t.stateManager.updateSessionIdentity(e),resolveInitialization:()=>t.stateManager.resolveInitializationOnce(),resolveInitializationIfNeeded:()=>t.stateManager.resolveInitializationIfNeeded(),setLastResponseMetadata:t.setLastResponseMetadata})}catch(e){let n=e instanceof Error?e:new Error(String(e));t.stateManager.isInitializationSettled()||t.stateManager.rejectInitializationOnce(n),await t.dispatchEnd("error").catch(()=>{})}}var Ze=class{initializationPromise;resolveInitialization;rejectInitialization;initializationSettled=!1;sessionMetadata;sessionIdentity;constructor(e,n){this.sessionIdentity=e,this.sessionMetadata=n,this.initializationPromise=new Promise((r,o)=>{this.resolveInitialization=r,this.rejectInitialization=o})}waitForInitialization(){return this.initializationPromise}getSessionIdentity(){return{...this.sessionIdentity,sessionId:this.getSessionId()}}getSessionMetadata(){return{...this.sessionMetadata,sessionId:this.getSessionId()}}getSessionId(){return this.sessionMetadata.sessionId??this.sessionIdentity.sessionId}updateSessionIdentity(e){e&&(this.sessionIdentity={...this.sessionIdentity,sessionId:e},this.sessionMetadata={...this.sessionMetadata,sessionId:e})}setSessionMetadata(e){this.sessionMetadata=e(this.sessionMetadata)}resolveInitializationIfNeeded(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}resolveInitializationOnce(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}rejectInitializationOnce(e){this.initializationSettled||(this.initializationSettled=!0,this.rejectInitialization(e))}isInitializationSettled(){return this.initializationSettled}};async function Qr(t,e){return await new Promise((n,r)=>{let o=null,s="",i=!1,a=c=>{i||(i=!0,clearTimeout(l),c())},l=Number.isFinite(e)&&e>0?setTimeout(()=>{a(()=>r(new Error("Response timeout")))},e):void 0;(async()=>{try{for await(let c of t){if(process.env.AFK_CODEX_DEBUG&&console.log("[wait] got event:",c.type),c.type==="error"){a(()=>r(c.error));return}if(c.type==="chunk"&&c.chunk.type==="content"&&(s+=c.chunk.content),c.type==="message"&&c.message.role==="assistant"&&(o=c.message),c.type==="done"){if(process.env.AFK_CODEX_DEBUG&&console.log("[wait] settling with done; assistantMessage=",!!o,"streamedContent=",s.length),o){let d=o;a(()=>n({...d,metadata:c.metadata}));return}if(s){a(()=>n({role:"assistant",content:s,metadata:c.metadata,timestamp:new Date}));return}}}a(o?()=>n(o):s?()=>n({role:"assistant",content:s,timestamp:new Date}):()=>r(new Error("No assistant response received")))}catch(c){a(()=>r(c instanceof Error?c:new Error(String(c))))}})()})}var te=class{config;currentState="idle";messageQueue;providerQuery;conversationHistory=[];turnCount=0;lastResponseMetadata=null;processingPromise=null;inputStream;abortController;hookRegistry;sessionEndDispatched=!1;stateManager;constructor(e){this.config=e,this.abortController=new AbortController,this.hookRegistry=e.hookRegistry,Wr(e.abortSignal,this.abortController,()=>{this.onAbort()}),this.initSdkLifecycle()}initSdkLifecycle(){this.messageQueue=new De;let e=ce(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=Yr(this.config,e);this.stateManager=new Ze(n,r),this.inputStream=new Xe(()=>this.sessionId);let o=this.config.provider??Gr(e);A(`\u{1F7E2} AgentSession: Creating query session via provider=${o.name}`),this.providerQuery=o.query({prompt:this.inputStream.createIterable(),config:this.config}),this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionEndDispatched=!1,this.currentState="idle",this.processingPromise=Jr({providerQuery:this.providerQuery,messageQueue:this.messageQueue,conversationHistory:this.conversationHistory,stateManager:this.stateManager,hookRegistry:this.hookRegistry,abortSignal:this.abortController.signal,sessionId:()=>this.sessionId,setLastResponseMetadata:s=>this.lastResponseMetadata=s,dispatchEnd:s=>this.dispatchSessionEndOnce(s)})}get state(){return this.currentState}get sessionId(){return this.stateManager.getSessionId()}get abortSignal(){return this.abortController.signal}async sendMessage(e,n={}){this.assertCanSend(),this.currentState=n.stream?"streaming":"processing";let r={role:"user",content:e,timestamp:new Date};this.conversationHistory.push(r);let o=this.config.timeoutMs??je;try{this.inputStream.pushUserMessage(e);let s=await He(Qr(this.messageQueue,o),o,{controller:this.abortController,label:this.sessionId??"session"});return this.turnCount++,s}finally{this.state!=="closed"&&(this.currentState="idle")}}async*sendMessageStream(e){this.assertCanSend(),this.currentState="streaming";let r={role:"user",content:typeof e=="string"?e:this.summarizeContentBlocks(e),timestamp:new Date};this.conversationHistory.push(r),this.inputStream.pushUserMessage(e);try{for await(let o of this.messageQueue)if(o.type==="done"&&this.turnCount++,yield o,o.type==="done"||o.type==="error")break}finally{this.state!=="closed"&&(this.currentState="idle")}}summarizeContentBlocks(e){let n=[],r=0;for(let s of e)s.type==="text"?n.push(s.text):s.type==="image"&&r++;let o=n.join(" ");return r>0&&(o=o?`${o} [+ ${r} image(s)]`:`[+ ${r} image(s)]`),o||"[content block(s)]"}async interrupt(){this.currentState!=="streaming"&&this.currentState!=="processing"||(this.currentState="idle",await this.providerQuery.interrupt())}async reset(){if(this.currentState==="closed")throw new Error("Cannot reset: session is closed");if(this.abortController.signal.aborted)throw new G("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset");try{await this.providerQuery.close()}catch{}this.processingPromise&&await Promise.race([this.processingPromise,new Promise(e=>setTimeout(e,dt))]).catch(()=>{}),this.messageQueue.complete(),this.stateManager.resolveInitializationIfNeeded();try{this.initSdkLifecycle()}catch(e){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async onAbort(){try{await this.providerQuery.interrupt()}catch{}}async setModel(e){let n=ce(e),r=this.stateManager.getSessionMetadata();await this.providerQuery.setModel(n??r.model??""),n&&this.stateManager.setSessionMetadata(o=>({...o,model:n}))}async setPermissionMode(e){await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:e}))}waitForInitialization(){return this.stateManager.waitForInitialization()}getSessionIdentity(){return this.stateManager.getSessionIdentity()}getSessionMetadata(){return this.stateManager.getSessionMetadata()}getQuery(){return this.providerQuery}supportedCommands(){return this.providerQuery.supportedCommands()}supportedModels(){return this.providerQuery.supportedModels()}supportedAgents(){return this.providerQuery.supportedAgents()}getContextUsage(){return this.providerQuery.getContextUsage()}mcpServerStatus(){return this.providerQuery.mcpServerStatus()}accountInfo(){return this.providerQuery.accountInfo()}rewindFiles(e,n){return this.providerQuery.rewindFiles(e,n)}async compact(){if(this.currentState==="closed")throw new Error("Cannot compact: session is closed");if(this.currentState!=="idle")return{compacted:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let e=this.providerQuery.compact?.bind(this.providerQuery);return e?e():{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){return this.messageQueue}getInputStreamRef(){return{pushUserMessage:e=>this.inputStream.pushUserMessage(e)}}getHistory(){return[...this.conversationHistory]}getTurnCount(){return this.turnCount}async close(){if(this.currentState!=="closed"){this.currentState="closed",this.abortController.signal.aborted||this.abortController.abort("closed"),this.stateManager.resolveInitializationIfNeeded();try{this.providerQuery.close()}catch{}if(this.processingPromise)try{await Promise.race([this.processingPromise,new Promise(e=>setTimeout(e,dt))])}catch{}this.messageQueue.complete(),await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await Vr(this.hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:e}))}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new G("Cannot send message: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")throw new Error("Cannot send message: session is busy");if(this.config.maxTurns&&this.turnCount>=this.config.maxTurns)throw new Error(`Maximum turns (${this.config.maxTurns}) exceeded`)}};var _t=class{handlers=new Map;register(e,n){let r=this.handlers.get(e);return r||(r=[],this.handlers.set(e,r)),r.push(n),()=>{let o=this.handlers.get(e);if(!o)return;let s=o.indexOf(n);s>=0&&o.splice(s,1)}}count(e){return this.handlers.get(e)?.length??0}async dispatch(e,n){Mt(n,e.event);let r=this.handlers.get(e.event);if(!r||r.length===0)return{};let o=r.slice(),s={};for(let i of o){Mt(n,e.event);let a;try{a=await i(e)}catch(l){throw new U(`hook handler threw during ${e.event}`,e.event,l instanceof Error?l.message:String(l),{cause:l})}if(Mt(n,e.event),Da(a))throw new U(`hook handler blocked ${e.event}${a.reason?`: ${a.reason}`:""}`,e.event,a.reason);s=a}return s}};function Da(t){return t.continue===!1||t.decision==="block"}function Mt(t,e){if(t?.aborted){let n=t.reason,r=`aborted during ${e}${n?`: ${String(n)}`:""}`;throw new G(r)}}function Xr(){return new _t}function Zr(){return Xr()}var Oa=["shadow-verify","shadow_verify","resolve","diagnose","appmap","qualify","mint"],Fa=[/\bverdict(s)?\b/i,/\brecommend(ation)?s?\b/i,/\bshould\s+(delete|remove|rewrite|refactor|rename|reject|merge|revert|disable)\b/i,/\b(USELESS|KEEP|REJECT|APPROVE|SALVAGE|BLOCK|FAIL)\b/,/\b(redundant|duplicated|superseded|obsolete)\b/i,/\bvulnerab\w*\b/i,/\bunused\b/i,/\bbroken\b/i,/\bregress\w*\b/i,/\|\s*(status|verdict|decision|severity|risk|finding|priority|holds\??)\s*\|/i,/\bfound\s+\d+\s*(issue|problem|bug|error|finding|vulnerabilit)/i,/\b(critical|high|medium|low)\s+(severity|priority|risk)\b/i,/\bclaim(s)?\b[^\n]{0,80}\b(holds?|refuted|verified|partial|confirmed|disputed)\b/i,/\b(root\s*cause|incident)\b/i,/\brecommend\s+(removing|deleting|rewriting|refactoring|merging|reverting)\b/i,/\bI\s+(applied|committed|pushed|edited|wrote|fixed|patched|reset|restored|staged)\b/i,/\b(applied|committed|pushed|fixed|patched)\s+(the|these|those)\s+(change|commit|fix|patch|edit)/i],$a=[/\bverifier_verdict\b/i,/"\s*claim\s*"\s*:/i,/\bre-derived\b[^.\n]{0,80}\bindependent/i,/\bindependently\s+(re-derived|re-verified|verified|checked)\b/i,/\bverifier\s+(agrees|disagrees|confirms|refutes)\b/i],La=`shadow-verify nudge:
1254
1267
 
1255
1268
  The sub-agent that just finished returned output that reads like **decision-driving findings** (verdicts, recommendations, audit conclusions, or claim-style results that could drive file edits, deletions, commits, or external side-effects).
1256
1269
 
1257
1270
  Single-pass sub-agent reports are prone to confident hallucination \u2014 polished output that falls apart on re-derivation. Before acting on these conclusions, consider dispatching \`/shadow-verify\`. Independent verifiers will re-derive the 2\u20133 most load-bearing claims from scratch (without seeing the original reasoning) and flag any that don't hold up.
1258
1271
 
1259
- Skip when: the findings are purely exploratory, the sub-agent ran inside an already-verifying orchestrator, the user is about to dismiss the report, or the stakes are low (read-only Q&A).`;function $a(t){if(!t)return!1;let e=t.toLowerCase();return Ra.some(n=>e.includes(n))}function La(t){return Oa.some(e=>e.test(t))}function ja(t){let e=0;for(let n of Da)n.test(t)&&e++;return e}function Xr(t){if(t.event!=="SubagentStop")return{};let e=t.lastMessage??"";return e.length<600?{}:$a(t.agentType)?{}:La(e)?{}:ja(e)<2?{}:{injectContext:Fa}}function Mt(t){let e=Qr();return e.register("SubagentStop",Xr),t&&e.register("SubagentStop",n=>n.event!=="SubagentStop"?{}:n.status==="idle"||n.status==="running"?{}:(t({subagentId:n.subagentId,status:n.status,durationMs:n.durationMs,agentType:n.agentType}),{})),e}var Ha="[skill-routing: active]\n\nRoute recurring work through registered skills instead of rolling ad-hoc solutions:\n\n- Multi-file implementation or new features \u2192 `/mint`\n- Bugs, failing tests, or regressions \u2192 `/diagnose`\n- High-stakes sub-agent output that will drive edits or commits \u2192 `/shadow-verify` before acting\n- Refactor needing parallel waves \u2192 `/parallelize`\n\nCommon composed sequences \u2014 reach for these when the task shape matches:\n\n- Bug with failing test and non-trivial fix \u2192 `/diagnose` \u2192 `/shadow-verify` on the proposed fix\n- Refactor needing parallel waves \u2192 plan \u2192 `/parallelize` \u2192 build waves\n\nSkip orchestration for: single-line edits, trivial Q&A, and direct tool calls the user explicitly requested. The goal is leverage, not ceremony \u2014 if a skill would add overhead without adding value, don't invoke it.";function _t(t,e){return!t||!e?t:`${t}
1272
+ Skip when: the findings are purely exploratory, the sub-agent ran inside an already-verifying orchestrator, the user is about to dismiss the report, or the stakes are low (read-only Q&A).`;function ja(t){if(!t)return!1;let e=t.toLowerCase();return Oa.some(n=>e.includes(n))}function Ha(t){return $a.some(e=>e.test(t))}function Ua(t){let e=0;for(let n of Fa)n.test(t)&&e++;return e}function eo(t){if(t.event!=="SubagentStop")return{};let e=t.lastMessage??"";return e.length<600?{}:ja(t.agentType)?{}:Ha(e)?{}:Ua(e)<2?{}:{injectContext:La}}function Rt(t){let e=Zr();return e.register("SubagentStop",eo),t&&e.register("SubagentStop",n=>n.event!=="SubagentStop"?{}:n.status==="idle"||n.status==="running"?{}:(t({subagentId:n.subagentId,status:n.status,durationMs:n.durationMs,agentType:n.agentType}),{})),e}var Na="[skill-routing: active]\n\nRoute recurring work through registered skills instead of rolling ad-hoc solutions:\n\n- Multi-file implementation or new features \u2192 `/mint`\n- Bugs, failing tests, or regressions \u2192 `/diagnose`\n- High-stakes sub-agent output that will drive edits or commits \u2192 `/shadow-verify` before acting\n- Refactor needing parallel waves \u2192 `/parallelize`\n\nCommon composed sequences \u2014 reach for these when the task shape matches:\n\n- Bug with failing test and non-trivial fix \u2192 `/diagnose` \u2192 `/shadow-verify` on the proposed fix\n- Refactor needing parallel waves \u2192 plan \u2192 `/parallelize` \u2192 build waves\n\nSkip orchestration for: single-line edits, trivial Q&A, and direct tool calls the user explicitly requested. The goal is leverage, not ceremony \u2014 if a skill would add overhead without adding value, don't invoke it.";function Dt(t,e){return!t||!e?t:`${t}
1260
1273
 
1261
- ${Ha}`}function Ua(t){if(typeof t!="object"||t===null)throw new Error("Skill tool input must be an object");let e=t,n=e.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=e.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var fe=class{constructor(e){this.ctx=e}ctx;pluginBodies=null;async execute(e){if(e.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??Pe;if(n>=r)return{content:`Skill tool not available at nesting depth ${n} (max ${r})`,isError:!0};let o;try{o=Ua(e.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=z(o.name);return await this.executeRegistrySkill(l,o.arguments,e.signal)}catch{}let s=this.getPluginSkillBody(o.name);if(s)return await this.executePluginSkill(o.name,s,o.arguments,e.signal);let a=ke(this.ctx.pluginConfigs).map(l=>l.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(e,n,r){if(r.aborted)return{content:"Skill call aborted",isError:!0};if(e.context==="fork")return this.executeForkedRegistrySkill(e,n,r);try{let o=await e.handler(n&&n.length>0?n:void 0,this.ctx.parentSession);return{content:typeof o=="string"?o:o!=null?JSON.stringify(o):"Skill completed successfully."}}catch(o){return{content:`Skill execution error: ${o instanceof Error?o.message:String(o)}`,isError:!0}}}async executeForkedRegistrySkill(e,n,r){if(r.aborted)return{content:"Skill call aborted",isError:!0};let o;try{if(o=T(e.name)["system.md"],!o)return{content:`Skill "${e.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(i){return{content:`Failed to load skill prompts: ${i instanceof Error?i.message:String(i)}`,isError:!0}}let s=new k({parentAbortSignal:r});try{let i=await s.forkSubagent({parent:this.ctx.parentSession,config:{model:e.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:o},idPrefix:`skill-fork-${e.name}`}),a=n&&n.length>0?n:"Run the skill.",l=await i.runToResult(a);return l.status==="succeeded"&&l.message?{content:l.message.content}:{content:l.error?.message??"Forked skill failed with no output",isError:!0}}catch(i){return{content:`Forked skill execution error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}finally{await s.teardownAll()}}async executePluginSkill(e,n,r,o){if(o.aborted)return{content:"Skill call aborted",isError:!0};let s=new k({parentAbortSignal:o});try{let i=await s.forkSubagent({parent:this.ctx.parentSession,config:{model:this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:n},idPrefix:`skill-${e}`}),a=r&&r.length>0?r:"Run the skill.",l=await i.runToResult(a);return l.status==="succeeded"&&l.message?{content:l.message.content}:{content:l.error?.message??"Plugin skill failed with no output",isError:!0}}catch(i){return{content:`Plugin skill execution error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}finally{await s.teardownAll()}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=Pr(this.ctx.pluginConfigs)),this.pluginBodies.get(e)}};var Pe=3;function Rt(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}var Na=[...we,"agent","skill"];function Zr(){return({childExecutor:t,childSkillExecutor:e})=>new Q({permissions:{allowedTools:Na},subagentExecutor:t,skillExecutor:e})}function eo(t){return(e,n,r)=>new fe({parentSession:Rt(r),defaultModel:t,depth:e,maxDepth:n})}function Ba(t){if(typeof t!="object"||t===null)throw new Error("Agent tool input must be an object");let e=t,n=e.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=e.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=e.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let a="agent-tool",l=e.id_prefix;if(l!==void 0){if(typeof l!="string")throw new Error("Agent tool id_prefix must be a string");a=l}return{prompt:n,model:r,max_turns:s,id_prefix:a}}var Xe=class t{constructor(e){this.ctx=e}ctx;async execute(e){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=Ba(e.input)}catch(c){return{content:`Agent tool input validation failed: ${c instanceof Error?c.message:String(c)}`,isError:!0}}let r=this.ctx.depth??0,o=this.ctx.maxDepth??Pe,s,i={model:n.model??this.ctx.defaultSubagentModel??"sonnet",apiKey:this.ctx.defaultConfig.apiKey,systemPrompt:this.ctx.defaultConfig.systemPrompt,maxTurns:n.max_turns};if(this.ctx.childProviderFactory&&r<o){s=new k({parentAbortSignal:e.signal});let c=new t({subagentManager:s,parentSession:Rt(e.signal),defaultConfig:this.ctx.defaultConfig,defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,depth:r+1,maxDepth:o}),d=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,e.signal):void 0;i.provider=this.ctx.childProviderFactory({childExecutor:c,childSkillExecutor:d})}let a;try{a=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,config:i,idPrefix:n.id_prefix})}catch(c){return{content:`Failed to fork subagent: ${c instanceof Error?c.message:String(c)}`,isError:!0}}let l=()=>{a.cancel()};e.signal.addEventListener("abort",l,{once:!0});try{let c=await a.runToResult(n.prompt);return c.status==="succeeded"&&c.message?{content:c.message.content}:{content:c.error?.message??"Subagent failed with no output",isError:!0}}finally{e.signal.removeEventListener("abort",l),await s?.teardownAll(),await a.teardown()}}};async function Ka(){let t;try{t=lr()}catch(s){console.error("\u274C Configuration error:",s.message),process.exit(1)}let e=de(t.model);if(e==="openai-codex"){let s=process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY;console.log(s?"\u{1F4DD} Using OPENAI_API_KEY / CODEX_API_KEY for Codex auth":"\u{1F4DD} Using existing `codex login` state on disk for Codex auth")}else process.env.CLAUDE_CODE_OAUTH_TOKEN?console.log("\u{1F4DD} Using CLAUDE_CODE_OAUTH_TOKEN for Anthropic auth"):process.env.ANTHROPIC_API_KEY?console.log("\u{1F4DD} Using ANTHROPIC_API_KEY for Anthropic auth"):t.apiKey?(process.env.ANTHROPIC_API_KEY=t.apiKey,console.log("\u{1F4DD} Using API key from config for Anthropic auth")):(console.error("\u274C Claude models require ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN."),console.error(" Set one in your environment or run `afk login`."),process.exit(1));let n=process.env.TELEGRAM_BOT_TOKEN;n||(console.error("\u274C Error: TELEGRAM_BOT_TOKEN environment variable is required"),console.error(`
1262
- How to get a bot token:`),console.error(" 1. Open Telegram and search for @BotFather"),console.error(" 2. Send /newbot and follow the instructions"),console.error(" 3. Copy the token to your .env file"),process.exit(1));let r=Kt(process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS,console.warn);r.size===0&&(console.error("\u274C Error: AFK_TELEGRAM_ALLOWED_CHAT_IDS must list at least one chat ID"),console.error(`
1274
+ ${Na}`}function Ba(t){if(typeof t!="object"||t===null)throw new Error("Skill tool input must be an object");let e=t,n=e.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=e.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var ge=class{constructor(e){this.ctx=e}ctx;pluginBodies=null;async execute(e){if(e.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??Ae;if(n>=r)return{content:`Skill tool not available at nesting depth ${n} (max ${r})`,isError:!0};let o;try{o=Ba(e.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=z(o.name);return await this.executeRegistrySkill(l,o.arguments,e.signal)}catch{}let s=this.getPluginSkillBody(o.name);if(s)return await this.executePluginSkill(o.name,s,o.arguments,e.signal);let a=xe(this.ctx.pluginConfigs).map(l=>l.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(e,n,r){if(r.aborted)return{content:"Skill call aborted",isError:!0};if(e.context==="fork")return this.executeForkedRegistrySkill(e,n,r);try{let o=await e.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel});return{content:typeof o=="string"?o:o!=null?JSON.stringify(o):"Skill completed successfully."}}catch(o){return{content:`Skill execution error: ${o instanceof Error?o.message:String(o)}`,isError:!0}}}async executeForkedRegistrySkill(e,n,r){if(r.aborted)return{content:"Skill call aborted",isError:!0};let o;try{if(o=T(e.name)["system.md"],!o)return{content:`Skill "${e.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(i){return{content:`Failed to load skill prompts: ${i instanceof Error?i.message:String(i)}`,isError:!0}}let s=new S({parentAbortSignal:r,apiKey:this.ctx.apiKey});try{let i=await s.forkSubagent({parent:this.ctx.parentSession,config:{model:e.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:o},idPrefix:`skill-fork-${e.name}`}),a=n&&n.length>0?n:"Run the skill.",l=await i.runToResult(a);return l.status==="succeeded"&&l.message?{content:l.message.content}:{content:l.error?.message??"Forked skill failed with no output",isError:!0}}catch(i){return{content:`Forked skill execution error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}finally{await s.teardownAll()}}async executePluginSkill(e,n,r,o){if(o.aborted)return{content:"Skill call aborted",isError:!0};let s=new S({parentAbortSignal:o,apiKey:this.ctx.apiKey});try{let i=await s.forkSubagent({parent:this.ctx.parentSession,config:{model:this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",systemPrompt:n},idPrefix:`skill-${e}`}),a=r&&r.length>0?r:"Run the skill.",l=await i.runToResult(a);return l.status==="succeeded"&&l.message?{content:l.message.content}:{content:l.error?.message??"Plugin skill failed with no output",isError:!0}}catch(i){return{content:`Plugin skill execution error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}finally{await s.teardownAll()}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=Ar(this.ctx.pluginConfigs)),this.pluginBodies.get(e)}};var Ae=3;function Ot(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}var Ka=[...Se,"agent","skill"];function to(){return({childExecutor:t,childSkillExecutor:e})=>new X({permissions:{allowedTools:Ka},subagentExecutor:t,skillExecutor:e})}function no(t,e){return(n,r,o)=>new ge({parentSession:Ot(o),defaultModel:t,apiKey:e,depth:n,maxDepth:r})}function Ga(t){if(typeof t!="object"||t===null)throw new Error("Agent tool input must be an object");let e=t,n=e.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=e.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=e.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let a="agent-tool",l=e.id_prefix;if(l!==void 0){if(typeof l!="string")throw new Error("Agent tool id_prefix must be a string");a=l}return{prompt:n,model:r,max_turns:s,id_prefix:a}}var et=class t{constructor(e){this.ctx=e}ctx;async execute(e){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=Ga(e.input)}catch(c){return{content:`Agent tool input validation failed: ${c instanceof Error?c.message:String(c)}`,isError:!0}}let r=this.ctx.depth??0,o=this.ctx.maxDepth??Ae,s,i={model:n.model??this.ctx.defaultSubagentModel??"sonnet",apiKey:this.ctx.defaultConfig.apiKey,systemPrompt:this.ctx.defaultConfig.systemPrompt,maxTurns:n.max_turns};if(this.ctx.childProviderFactory&&r<o){s=new S({parentAbortSignal:e.signal});let c=new t({subagentManager:s,parentSession:Ot(e.signal),defaultConfig:this.ctx.defaultConfig,defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,depth:r+1,maxDepth:o}),d=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,e.signal):void 0;i.provider=this.ctx.childProviderFactory({childExecutor:c,childSkillExecutor:d})}let a;try{a=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,config:i,idPrefix:n.id_prefix})}catch(c){return{content:`Failed to fork subagent: ${c instanceof Error?c.message:String(c)}`,isError:!0}}let l=()=>{a.cancel()};e.signal.addEventListener("abort",l,{once:!0});try{let c=await a.runToResult(n.prompt);return c.status==="succeeded"&&c.message?{content:c.message.content}:{content:c.error?.message??"Subagent failed with no output",isError:!0}}finally{e.signal.removeEventListener("abort",l),await s?.teardownAll(),await a.teardown()}}};async function za(){let t;try{t=dr()}catch(s){console.error("\u274C Configuration error:",s.message),process.exit(1)}let e=pe(t.model);if(e==="openai-codex"){let s=process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY;console.log(s?"\u{1F4DD} Using OPENAI_API_KEY / CODEX_API_KEY for Codex auth":"\u{1F4DD} Using existing `codex login` state on disk for Codex auth")}else process.env.CLAUDE_CODE_OAUTH_TOKEN?console.log("\u{1F4DD} Using CLAUDE_CODE_OAUTH_TOKEN for Anthropic auth"):process.env.ANTHROPIC_API_KEY?console.log("\u{1F4DD} Using ANTHROPIC_API_KEY for Anthropic auth"):t.apiKey?(process.env.ANTHROPIC_API_KEY=t.apiKey,console.log("\u{1F4DD} Using API key from config for Anthropic auth")):(console.error("\u274C Claude models require ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN."),console.error(" Set one in your environment or run `afk login`."),process.exit(1));let n=process.env.TELEGRAM_BOT_TOKEN;n||(console.error("\u274C Error: TELEGRAM_BOT_TOKEN environment variable is required"),console.error(`
1275
+ How to get a bot token:`),console.error(" 1. Open Telegram and search for @BotFather"),console.error(" 2. Send /newbot and follow the instructions"),console.error(" 3. Copy the token to your .env file"),process.exit(1));let r=zt(process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS,console.warn);r.size===0&&(console.error("\u274C Error: AFK_TELEGRAM_ALLOWED_CHAT_IDS must list at least one chat ID"),console.error(`
1263
1276
  This is an allowlist that gates who can message the bot.`),console.error("Set it to a comma-separated list of numeric Telegram chat IDs, e.g.:"),console.error(" AFK_TELEGRAM_ALLOWED_CHAT_IDS=123456789,-100987654321"),console.error(`
1264
- To find your chat ID, DM the bot and inspect the update, or use @userinfobot.`),process.exit(1)),console.log("\u{1F916} Starting Agent AFK Telegram Bot..."),console.log(`\u{1F4E1} Model: ${t.model} \xB7 Provider: ${e}`),console.log(`\u{1F512} Allowlist: ${r.size} chat ID(s)`);let o=new Ce({botToken:n,apiKey:t.apiKey??"",dataDir:process.env.TELEGRAM_DATA_DIR||"./data/telegram-sessions",defaultModel:t.model,verbose:process.env.TELEGRAM_VERBOSE==="true",allowedChatIds:r,settingSources:["user","project"],createSession:async s=>{let i=ae(s.model)??s.model;console.log(`Creating session with model: ${s.model} -> ${i}`);let l=de(i)==="openai-codex",c=l?void 0:cr(),d;if(!l){let h,m=new k({}),b={get sessionId(){return h?.sessionId},getInputStreamRef(){return h?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return h?.abortSignal??new AbortController().signal}},S=Zr(),F=new Xe({subagentManager:m,parentSession:b,defaultConfig:{apiKey:s.apiKey??t.apiKey??"",systemPrompt:s.systemPrompt??t.systemPrompt},defaultSubagentModel:wt(),childProviderFactory:S,childSkillExecutorFactory:eo(s.model)}),R=new fe({parentSession:b,defaultModel:s.model,defaultSubagentModel:wt()}),x=[...we,"agent","skill"];d=new Q({permissions:{allowedTools:x},subagentExecutor:F,skillExecutor:R});let M=s.systemPrompt||t.systemPrompt,_=t.autoRouting?.telegram??!1,B=typeof M=="string"?_t(M,_):M,K=new Z({...s.apiKey!==void 0?{apiKey:s.apiKey}:{},model:s.model,...B!==void 0?{systemPrompt:B}:{},maxTurns:100,...c!==void 0?{maxOutputTokens:c}:{},provider:d,hookRegistry:Mt()});return h=K,K}let u=s.systemPrompt||t.systemPrompt,p=t.autoRouting?.telegram??!1,f=typeof u=="string"?_t(u,p):u;return new Z({...s.apiKey!==void 0?{apiKey:s.apiKey}:{},model:s.model,...f!==void 0?{systemPrompt:f}:{},maxTurns:100,...c!==void 0?{maxOutputTokens:c}:{},hookRegistry:Mt()})}});try{o.start(),console.log("\u2705 Bot started successfully!"),console.log(`
1277
+ To find your chat ID, DM the bot and inspect the update, or use @userinfobot.`),process.exit(1)),console.log("\u{1F916} Starting Agent AFK Telegram Bot..."),console.log(`\u{1F4E1} Model: ${t.model} \xB7 Provider: ${e}`),console.log(`\u{1F512} Allowlist: ${r.size} chat ID(s)`);let o=new _e({botToken:n,apiKey:t.apiKey??"",dataDir:process.env.TELEGRAM_DATA_DIR||"./data/telegram-sessions",defaultModel:t.model,verbose:process.env.TELEGRAM_VERBOSE==="true",allowedChatIds:r,settingSources:["user","project"],createSession:async s=>{let i=ce(s.model)??s.model;console.log(`Creating session with model: ${s.model} -> ${i}`);let l=pe(i)==="openai-codex",c=l?void 0:ur(),d;if(!l){let h,m=s.apiKey??t.apiKey??"",b=new S({apiKey:m}),v={get sessionId(){return h?.sessionId},getInputStreamRef(){return h?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return h?.abortSignal??new AbortController().signal}},F=to(),W=new et({subagentManager:b,parentSession:v,defaultConfig:{apiKey:m,systemPrompt:s.systemPrompt??t.systemPrompt},defaultSubagentModel:St(),childProviderFactory:F,childSkillExecutorFactory:no(s.model,m)}),B=new ge({parentSession:v,defaultModel:s.model,defaultSubagentModel:St(),apiKey:m}),_=[...Se,"agent","skill"];d=new X({permissions:{allowedTools:_},subagentExecutor:W,skillExecutor:B});let x=s.systemPrompt||t.systemPrompt,R=t.autoRouting?.telegram??!1,M=typeof x=="string"?Dt(x,R):x,K=new te({...s.apiKey!==void 0?{apiKey:s.apiKey}:{},model:s.model,...M!==void 0?{systemPrompt:M}:{},maxTurns:100,...c!==void 0?{maxOutputTokens:c}:{},provider:d,hookRegistry:Rt()});return h=K,K}let u=s.systemPrompt||t.systemPrompt,p=t.autoRouting?.telegram??!1,f=typeof u=="string"?Dt(u,p):u;return new te({...s.apiKey!==void 0?{apiKey:s.apiKey}:{},model:s.model,...f!==void 0?{systemPrompt:f}:{},maxTurns:100,...c!==void 0?{maxOutputTokens:c}:{},hookRegistry:Rt()})}});try{o.start(),console.log("\u2705 Bot started successfully!"),console.log(`
1265
1278
  \u{1F4DD} Slash commands (Agent SDK):`),console.log(" /start - Welcome and command list"),console.log(" /help - Show command list"),console.log(" /clear - Clear conversation history"),console.log(" /compact - Compact history (summarize older messages)"),console.log(" /model - Switch model (opus/sonnet/haiku/gpt-5.4/...)"),console.log(`
1266
1279
  \u{1F4AC} Send any message to chat with the agent.`),console.log(`
1267
1280
  \u23F9\uFE0F Press Ctrl+C to stop the bot.`);let s=setInterval(()=>{let a=o.getStats();console.log(`
1268
1281
  \u{1F4CA} Stats: ${a.activeSessions} active sessions, ${a.totalChats} total chats`)},3e5),i=async()=>{console.log(`
1269
1282
 
1270
- \u{1F6D1} Shutting down bot...`),clearInterval(s),await o.stop(),console.log("\u2705 Bot stopped."),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i)}catch(s){console.error("\u274C Failed to start bot:",s),process.exit(1)}}Ka().catch(t=>{console.error("\u274C Unhandled error:",t),process.exit(1)});
1283
+ \u{1F6D1} Shutting down bot...`),clearInterval(s),await o.stop(),console.log("\u2705 Bot stopped."),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i)}catch(s){console.error("\u274C Failed to start bot:",s),process.exit(1)}}za().catch(t=>{console.error("\u274C Unhandled error:",t),process.exit(1)});