agent-afk 1.1.0 → 1.3.0
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/cli.mjs +142 -135
- package/dist/index.mjs +48 -48
- package/dist/telegram.mjs +50 -50
- package/package.json +1 -1
package/dist/telegram.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Telegraf as
|
|
2
|
+
import{Telegraf as wo}from"telegraf";import{promises as ge}from"fs";import{join as Ut}from"path";var Ae=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 ge.mkdir(this.options.dataDir,{recursive:!0});let e=await ge.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=Ut(this.options.dataDir,n),o=await ge.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 ge.mkdir(this.options.dataDir,{recursive:!0});for(let[e,n]of this.sessionData.entries()){let r=Ut(this.options.dataDir,`${e}.json`);await ge.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 Te(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
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 st(t){let e=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");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,"&").replace(/"/g,""")+'">'+r+"</a>"),e=e.replace(/^#{1,6}\s+/gm,""),e}function O(t){return`\u274C Error: ${t instanceof Error?t.message:t}`}var Nt=[{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 Bt(t){let e=["\u{1F4CB} Bot commands (aligned with agent-afk CLI):","",...Nt.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
5
|
`)}function Kt(){return`\u{1F44B} Welcome to Agent AFK Bot!
|
|
@@ -10,25 +10,25 @@ Available commands:
|
|
|
10
10
|
${Nt.map(e=>`${e.cmd} - ${e.desc}`).join(`
|
|
11
11
|
`)}
|
|
12
12
|
|
|
13
|
-
Just send me a message to get started!`}function Gt(t){return`${{opus:"\u{1F680}",sonnet:"\u26A1",haiku:"\u{1F338}"}[t]||"\u{1F916}"} Switched to Claude ${t.toUpperCase()}`}function Ie(){return"\u{1F504} Conversation history cleared!"}function zt(t){if(!t)return"\u{1F4E6} Conversation compacted (older messages summarized).";let e=t.tokensSavedEstimate!==void 0&&t.tokensSavedEstimate>0?` (~${
|
|
13
|
+
Just send me a message to get started!`}function Gt(t){return`${{opus:"\u{1F680}",sonnet:"\u26A1",haiku:"\u{1F338}"}[t]||"\u{1F916}"} Switched to Claude ${t.toUpperCase()}`}function Ie(){return"\u{1F504} Conversation history cleared!"}function zt(t){if(!t)return"\u{1F4E6} Conversation compacted (older messages summarized).";let e=t.tokensSavedEstimate!==void 0&&t.tokensSavedEstimate>0?` (~${ho(t.tokensSavedEstimate)} input tokens saved)`:"";return`\u{1F4E6} Compacted ${t.before} \u2192 ${t.after} messages${e}.`}function Vt(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 ho(t){return t>=1e3?`${Math.round(t/100)/10}k`:String(t)}async function it(t){await t.reply(Kt())}async function at(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(Bt(r))}async function lt(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(Ie())}catch(s){r("Clear error:",s),await t.reply(O(s))}}async function qt(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(zt({before:s.messagesBefore,after:s.messagesAfter,...s.tokensSavedEstimate!==void 0?{tokensSavedEstimate:s.tokensSavedEstimate}:{}})):await t.reply(Vt(s.reason??"unknown"))}catch(o){n("Compact error:",o),await t.reply(O(o))}}async function ct(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(Gt(a))}catch(c){n("Model switch error:",c),await t.reply(O(c))}}function ut(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("rate limit")||e.toLowerCase().includes("too many requests")}function dt(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("network")||e.toLowerCase().includes("connect")||e.toLowerCase().includes("timeout")}var
|
|
16
|
+
Valid options: opus, sonnet, haiku`));return}try{await e.switchModel(r,a),await t.reply(Gt(a))}catch(c){n("Model switch error:",c),await t.reply(O(c))}}function ut(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("rate limit")||e.toLowerCase().includes("too many requests")}function dt(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("network")||e.toLowerCase().includes("connect")||e.toLowerCase().includes("timeout")}var yo=300,bo=9e4,vo=6e4;async function Wt(t,e,n,r){let o="",s=null,i=0,a=async(l,c=!1)=>{let u=st(l||"\u2026"),d=Date.now();if(!s){let f=Te(u);s=await t.reply(f[0]??"\u2026",{parse_mode:"HTML"});return}if(!c&&d-i<yo&&l.length<100)return;i=d;let p=Te(u);try{await t.telegram.editMessageText(t.chat?.id,s.message_id,void 0,p[0]??u,{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](),u=!1,d=null,p=()=>{let f=u?vo:bo;return new Promise((g,h)=>{d=setTimeout(()=>{d=null,h(new Error(u?"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=>{d!=null&&(clearTimeout(d),d=null),g(m)},m=>{d!=null&&(clearTimeout(d),d=null),h(m)})})};for(;;){let f=await p();if(f.done)break;let g=f.value;if(u||(u=!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:y}=g.progress,b=y?`
|
|
17
17
|
\u25E6 ${h} (${y})`:`
|
|
18
18
|
\u25E6 ${h}`;o+=b,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=Te(st(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 Yt(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 Ce=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(Yt(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}ut(o)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):dt(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(Ie())}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 Wt(n,o,r,this.log)}catch(o){console.error("\u274C Message handling error:",o),this.log("Message handling error:",o);let s=o;ut(o)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):dt(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 Jt(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 Qt(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 vo(e.botToken),this.sessionManager=new Ae(e),this.messageHandler=new Ce(this.bot,this.sessionManager,this.registeredCommandChats,this.log.bind(this)),this.setupHandlers()}setupHandlers(){this.bot.use(Qt(this.options.allowedChatIds,this.log.bind(this))),this.bot.command("start",e=>it(e)),this.bot.command("help",e=>at(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 lt(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}),this.bot.command("compact",e=>qt(e,this.sessionManager,this.log.bind(this))),this.bot.command("model",e=>ct(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 it(e)}async handleHelp(e){return at(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 lt(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}async handleMessage(e){return this.messageHandler.handle(e)}async handleModelSwitch(e){return ct(e,this.sessionManager,this.log.bind(this))}log(...e){this.options.verbose&&console.log("[TelegramBot]",...e)}};function wo(){return process.env.AFK_DEBUG==="1"||process.env.DEBUG==="1"}function A(...t){wo()&&console.log(...t)}var V=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},K=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 he=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 Re=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 qr from"@anthropic-ai/sdk";var ko="claude-code-20250219,oauth-2025-04-20",So="claude-cli/1.0.0 (external, cli)",xo="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function Xt(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function pt(t,e){return e==="oauth"?{authToken:t}:{apiKey:t}}function De(t,e,n){return t!=="oauth"?{}:{"anthropic-beta":ko,"x-app":"cli","User-Agent":So,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Zt(t){return t!=="oauth"?null:[{type:"text",text:xo}]}import{execFileSync as en}from"child_process";import{existsSync as Po,readFileSync as Eo,writeFileSync as Ao}from"fs";import{homedir as tn,userInfo as nn}from"os";import{join as rn}from"path";var To="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Io="https://platform.claude.com/v1/oauth/token",Co=300*1e3;function on(){let t=an();if(t===void 0)return;let e=ln(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}}async function sn(){let t=an();if(t===void 0)return;let e=ln(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Co)return e.accessToken;if(!e.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await _o(e.refreshToken);if(!n){process.stderr.write("agent-afk: OAuth token refresh failed. Run `claude login` to refresh.\n");return}try{let r={};try{r=JSON.parse(t)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},Mo(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
22
|
-
`)}return n.accessToken}function an(){if(process.platform==="darwin")try{return en("security",["find-generic-password","-s","Claude Code-credentials","-a",nn().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=rn(tn(),".claude",".credentials.json");if(!
|
|
23
|
-
`)[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*ft(t){let e=t.maxToolUseIterations
|
|
24
|
-
`),gn="[Compacted summary of earlier conversation]",hn="Acknowledged. Continuing from the summary above.";function
|
|
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=Te(st(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 Yt(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 Ce=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(Yt(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}ut(o)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):dt(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(Ie())}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 Wt(n,o,r,this.log)}catch(o){console.error("\u274C Message handling error:",o),this.log("Message handling error:",o);let s=o;ut(o)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):dt(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 Jt(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 Qt(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 wo(e.botToken),this.sessionManager=new Ae(e),this.messageHandler=new Ce(this.bot,this.sessionManager,this.registeredCommandChats,this.log.bind(this)),this.setupHandlers()}setupHandlers(){this.bot.use(Qt(this.options.allowedChatIds,this.log.bind(this))),this.bot.command("start",e=>it(e)),this.bot.command("help",e=>at(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 lt(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}),this.bot.command("compact",e=>qt(e,this.sessionManager,this.log.bind(this))),this.bot.command("model",e=>ct(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 it(e)}async handleHelp(e){return at(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 lt(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}async handleMessage(e){return this.messageHandler.handle(e)}async handleModelSwitch(e){return ct(e,this.sessionManager,this.log.bind(this))}log(...e){this.options.verbose&&console.log("[TelegramBot]",...e)}};function ko(){return process.env.AFK_DEBUG==="1"||process.env.DEBUG==="1"}function A(...t){ko()&&console.log(...t)}var V=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},K=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 he=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 Re=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 Wr from"@anthropic-ai/sdk";var So="claude-code-20250219,oauth-2025-04-20",xo="claude-cli/1.0.0 (external, cli)",Po="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function Xt(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function pt(t,e){return e==="oauth"?{authToken:t}:{apiKey:t}}function De(t,e,n){return t!=="oauth"?{}:{"anthropic-beta":So,"x-app":"cli","User-Agent":xo,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Zt(t){return t!=="oauth"?null:[{type:"text",text:Po}]}import{execFileSync as en}from"child_process";import{existsSync as Eo,readFileSync as Ao,writeFileSync as To}from"fs";import{homedir as tn,userInfo as nn}from"os";import{join as rn}from"path";var Io="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Co="https://platform.claude.com/v1/oauth/token",_o=300*1e3;function on(){let t=an();if(t===void 0)return;let e=ln(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}}async function sn(){let t=an();if(t===void 0)return;let e=ln(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+_o)return e.accessToken;if(!e.refreshToken){process.stderr.write("agent-afk: OAuth token expired and no refresh token available. Run `claude login` to refresh.\n");return}let n=await Mo(e.refreshToken);if(!n){process.stderr.write("agent-afk: OAuth token refresh failed. Run `claude login` to refresh.\n");return}try{let r={};try{r=JSON.parse(t)}catch{}let o=r.claudeAiOauth??{};r.claudeAiOauth={...o,accessToken:n.accessToken,expiresAt:n.expiresAt,...n.refreshToken!==void 0?{refreshToken:n.refreshToken}:{}},Ro(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
22
|
+
`)}return n.accessToken}function an(){if(process.platform==="darwin")try{return en("security",["find-generic-password","-s","Claude Code-credentials","-a",nn().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=rn(tn(),".claude",".credentials.json");if(!Eo(t))return;try{return Ao(t,"utf-8")}catch{return}}}function ln(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={accessToken:o},i=r.refreshToken;typeof i=="string"&&i.length>0&&(s.refreshToken=i);let a=r.expiresAt;return typeof a=="number"&&(s.expiresAt=a),s}async function Mo(t){try{let e=await fetch(Co,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:Io})});if(!e.ok)return;let n=await e.json(),r=n.access_token,o=n.expires_in;if(typeof r!="string"||typeof o!="number")return;let s=n.refresh_token;return{accessToken:r,expiresAt:Date.now()+o*1e3,...typeof s=="string"&&s.length>0?{refreshToken:s}:{}}}catch{return}}function Ro(t){if(process.platform==="darwin")en("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",nn().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=rn(tn(),".claude",".credentials.json");To(e,t,"utf-8")}}import{randomUUID as Xe}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 cn(t,e){if(t.length===0)return t;let n=t[t.length-1],r=dn(n,e);return r===n?t:[...t.slice(0,-1),r]}function un(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Do(n,e);return r===n?t:[...t.slice(0,-1),r]}function Do(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=dn(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function dn(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}import{randomUUID as $o}from"node:crypto";function pn(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 fn(t,e){let n=(u,d)=>{if(!(u==null&&d==null))return(u??0)+(d??0)},r=(u,d)=>d!==void 0?d:u,o={stopReason:e.stopReason??t.stopReason??null},s=n(t.inputTokens,e.inputTokens);s!==void 0&&(o.inputTokens=s);let i=n(t.outputTokens,e.outputTokens);i!==void 0&&(o.outputTokens=i);let a=r(t.cachedInputTokens,e.cachedInputTokens);a!==void 0&&(o.cachedInputTokens=a);let l=r(t.cacheCreationTokens,e.cacheCreationTokens);l!==void 0&&(o.cacheCreationTokens=l);let c=n(t.totalTokens,e.totalTokens);return c!==void 0&&(o.totalTokens=c),o}function Oo(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:Oo(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*mn(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 Lo=0;function jo(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(`
|
|
23
|
+
`)[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*ft(t){let e=t.maxToolUseIterations??Lo,n={stopReason:null},r=0,o=$o(),s=Date.now();for(;;){if(t.signal.aborted)return;let i=Oe()?un(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,u=!1;try{for await(let m of mn(l,t.ctx))if(m.kind==="event"){if(m.event.type==="error"){yield m.event,u=!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(u)return;if(c===null){yield{type:"turn.completed",usage:n,sessionId:t.ctx.sessionId};return}if(n=fn(n,pn(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})),t.messages.push({role:"assistant",content:c.assistantBlocks}),yield{type:"turn.completed",usage:n,sessionId:t.ctx.sessionId};return}t.messages.push({role:"assistant",content:c.assistantBlocks});let d=[];for(let m of c.toolUseBlocks)d.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:jo(m.input),sessionId:t.ctx.sessionId};if(t.signal.aborted)return;let p;if(t.toolDispatcher.executeBatch)p=await t.toolDispatcher.executeBatch(d);else{p=[];for(let m of d){if(t.signal.aborted){p.push({content:"Tool call aborted",isError:!0});continue}try{p.push(await t.toolDispatcher.execute(m))}catch(y){let b=y instanceof Error?y.message:String(y);p.push({content:`Tool execution threw: ${b}`,isError:!0})}}}let f=[];for(let m=0;m<d.length;m++){let y=d[m],b=p[m];yield{type:"tool.output",toolUseId:y.id,content:b.content,...b.isError===!0?{isError:!0}:{},sessionId:t.ctx.sessionId},f.push({type:"tool_result",tool_use_id:y.id,content:b.content,...b.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 Ho=["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(`
|
|
24
|
+
`),gn="[Compacted summary of earlier conversation]",hn="Acknowledged. Continuing from the summary above.";function Uo(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 yn(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&&Uo(o)&&(n+=1,n===e))return r}return-1}function bn(t,e,n){let r=No(t);return{model:e,max_tokens:n,system:Ho,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
|
|
25
25
|
|
|
26
26
|
<transcript>
|
|
27
27
|
`+r+`
|
|
28
28
|
</transcript>`}],stream:!0}}function vn(t,e,n){return[{role:"user",content:gn+`
|
|
29
29
|
|
|
30
|
-
`+n},{role:"assistant",content:hn},...t.slice(e)]}function wn(t,e,n){let r=
|
|
31
|
-
`).trim()}function kn(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function Sn(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
|
|
30
|
+
`+n},{role:"assistant",content:hn},...t.slice(e)]}function wn(t,e,n){let r=Bo(t.slice(0,e)),o=gn.length+2+n.length+hn.length,s=Math.max(0,r-o);return Math.round(s/4)}function No(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=kn(o.input);e.push(`[tool call: ${i} ${a}]`)}else if(s==="tool_result"){let i=o.content;e.push(`[tool result: ${Sn(i)}]`)}else s==="image"?e.push("[image]"):s==="document"&&e.push("[document]")}e.push("")}return e.join(`
|
|
31
|
+
`).trim()}function kn(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function Sn(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 Bo(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+=kn(r.input).length:o==="tool_result"&&(e+=Sn(r.content).length)}return e}import{z as I}from"zod";import{mkdir as zn,appendFile as Vn}from"fs/promises";import{join as St}from"path";var xn={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
|
|
32
32
|
|
|
33
33
|
You are an inspector auditing skills for correct type categorization. Skills come from two sources:
|
|
34
34
|
- **User-scope** \u2014 authored directly by the user under \`~/.afk/skills/<name>/SKILL.md\`
|
|
@@ -821,8 +821,8 @@ Field semantics:
|
|
|
821
821
|
- \`issues\` \u2014 concrete blockers with file:line citations where possible. Empty array when \`PASS\`.
|
|
822
822
|
- \`summary\` \u2014 optional narrative; the orchestrator may surface it to the user. Keep it concise.
|
|
823
823
|
`}};function T(t){let e=xn[t];if(!e){let n=Object.keys(xn).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+t+". "+r)}return e}var $e=new Map;function J(t){$e.set(t.name,t)}function q(t){let e=$e.get(t);if(e)return e;let n=Array.from($e.keys()).sort(),r=n.length>0?`
|
|
824
|
-
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}`)}function Pn(){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,mt=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 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 En(t,e,n={}){t&&await t.dispatch(e,n.signal)}async function An(t,e,n={}){if(!t)return{};try{return await t.dispatch(e,n.signal)}catch(r){return r instanceof K||r instanceof V?(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
|
|
825
|
-
`;await
|
|
824
|
+
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}`)}function Pn(){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,mt=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 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 En(t,e,n={}){t&&await t.dispatch(e,n.signal)}async function An(t,e,n={}){if(!t)return{};try{return await t.dispatch(e,n.signal)}catch(r){return r instanceof K||r instanceof V?(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 qo,writeFile as Wo}from"fs/promises";import{dirname as Yo,join as Jo}from"path";import{join as R,dirname as Ko}from"path";import{homedir as gt}from"os";import{fileURLToPath as Go}from"url";function Y(){return process.env.AFK_HOME||R(gt(),".afk")}function ie(){return R(Y(),"agent-framework")}function Tn(){return R(ie(),"forge-telemetry.jsonl")}function ce(){return R(ie(),"briefs")}function Ue(){return R(ie(),"ceiling-ledger")}function ht(){return R(Y(),"skills")}function ue(){return R(Y(),"plugins")}function zo(){return R(process.cwd(),".afk")}function ye(){return R(zo(),"plugins")}function Ne(){return R(ue(),".index.json")}function yt(){let t=Go(import.meta.url),e=Ko(t);return R(e,"bundled-plugins")}function In(){return R(Y(),"config")}function Vo(){return R(Y(),"state")}function Cn(){return R(Vo(),"sessions")}function _n(){return R(In(),"afk.env")}function bt(){return R(In(),"afk.config.json")}function Mn(){return R(gt(),".afk.env")}function vt(){return R(gt(),".afk.config.json")}function Qo(){return Jo(ie(),"routing-decisions.jsonl")}async function Rn(t){if(!(process.env.VITEST||process.env.NODE_ENV==="test"))try{let e=Qo();await qo(Yo(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,surface:"afk",...t})+`
|
|
825
|
+
`;await Wo(e,r,{flag:"a"})}catch{}}import{AsyncLocalStorage as Xo}from"node:async_hooks";var Zo=new Xo;function Q(){return Zo.getStore()}function Dn(t){let e=es(t);return e!==void 0?e:ts(t)}function es(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return On(n.trim())}function ts(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=ns(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=On(r);if(o!==void 0)return o}}function ns(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 On(t){try{return JSON.parse(t)}catch{return}}function Fn(t,e,n,r){if(!r)return{id:t,status:e,message:n};let o=Dn(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 $n(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 Be=class{constructor(e,n,r,o,s,i,a,l,c,u,d,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=u;this.agentType=d;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??Q(),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 Fn(this.id,this.currentStatus,n,this.outputSchema)}catch(n){return $n(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 An(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 w=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 En(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 re(i),l=e.parent.getInputStreamRef?.(),c=e.parent.abortSignal,u=this.progressSink??Q(),d=new Be(n,a,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??je,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},l,c,e.idPrefix,u,e.parent.sessionId);return this.active.set(n,d),await Rn({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,parent_session_id:e.parent.sessionId}),d}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 Ke(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 u of s){let d=t[u];d&&d.handle.status==="running"&&d.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(t.map(a=>a.handle.teardown())),o}import{fileURLToPath as rs}from"node:url";import{dirname as os}from"node:path";var ss=rs(import.meta.url),Gc=os(ss),U={name:"research-agent",systemPrompt:`---
|
|
826
826
|
name: research-agent
|
|
827
827
|
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.
|
|
828
828
|
model: sonnet
|
|
@@ -872,16 +872,16 @@ Unless the dispatcher specifies a different schema, return:
|
|
|
872
872
|
\`\`\`
|
|
873
873
|
|
|
874
874
|
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\`.
|
|
875
|
-
`,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{existsSync as oe,readdirSync as
|
|
876
|
-
`)}function
|
|
875
|
+
`,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{existsSync as oe,readdirSync as fs,readFileSync as ms}from"fs";import{join as X}from"path";import{existsSync as wt,readFileSync as ls,readdirSync as cs,statSync as us}from"fs";import{join as be,resolve as jn}from"path";import{existsSync as is,mkdirSync as qc,readFileSync as as,renameSync as Wc,writeFileSync as Yc,unlinkSync as Jc}from"fs";function Ln(t=Ne()){if(!is(t))return Ge();try{let e=as(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Ge();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 Ge()}catch{return Ge()}}function Ge(){return{version:2,plugins:{},marketplaces:{}}}var ds=5,Hn="cache";function G(t=ue()){if(!wt(t))return[];let e=t===ue()?Ne():be(t,".index.json"),n=Ln(e),r=[];return Un(t,t,0,r,new Set,n.plugins),r}function Un(t,e,n,r,o,s){if(n>ds||o.has(e))return;if(o.add(e),wt(be(e,".claude-plugin","plugin.json"))){let a=kt(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=cs(e)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=be(e,a),c;try{c=us(l)}catch{continue}c.isDirectory()&&Un(t,l,n+1,r,o,s)}}function kt(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]===Hn&&r.length>=3){let s=r[1];if(s){let i=be(t,Hn,s),l=ps(i,e)??r[2];if(l)return{layout:"cache",key:`${s}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function ps(t,e){let n=be(t,".claude-plugin","marketplace.json");if(!wt(n))return null;let r;try{r=JSON.parse(ls(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=jn(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("../"))&&jn(t,a.source)===s)return a.name}return null}var Nn=["command","agent"];function Bn(t=Y()){let e=[],n=X(t,"skills");if(oe(n))for(let r of ze(n)){let o=X(n,r,"SKILL.md");oe(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of Nn){let o=X(t,`${r}s`);if(oe(o))for(let s of ze(o))s.endsWith(".md")&&e.push({path:X(o,s),type:r,source:"user"})}return e}function Kn(t=ue()){if(!oe(t))return[];let e=[],n=G(t);for(let r of n){let s=kt(t,r.path)?.key,i=X(r.path,"skills");if(oe(i))for(let a of ze(i)){let l=X(i,a,"SKILL.md");if(!oe(l))continue;let c={path:l,type:"skill",source:"plugin"};s&&(c.plugin_key=s),e.push(c)}for(let a of Nn){let l=X(r.path,`${a}s`);if(oe(l))for(let c of ze(l)){if(!c.endsWith(".md"))continue;let u={path:X(l,c),type:a,source:"plugin"};s&&(u.plugin_key=s),e.push(u)}}}return e}function Gn(t=X(Y(),"settings.json")){if(!oe(t))return[];try{let e=ms(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 ze(t){try{return fs(t).filter(e=>!e.startsWith("."))}catch{return[]}}var Wn=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"])}),qn=I.record(I.string(),I.record(I.string(),I.number())),vu=I.object({inventory:I.object({user:qn,plugin:qn}),misfits:I.array(Wn),briefs_written:I.number(),total_artifacts:I.number()}),gs=I.object({writeBriefs:I.boolean().optional(),scope:I.enum(["user","plugin","all"]).optional()}),hs=["skill","command","agent"],Yn=["skill","command","agent","hook"];function ys(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function bs(t){let e=()=>{let s={};for(let i of Yn)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 vs(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function ws(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(`
|
|
876
|
+
`)}function ks(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(`
|
|
877
877
|
`);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(`
|
|
878
|
-
`)}function
|
|
879
|
-
${
|
|
880
|
-
${
|
|
878
|
+
`)}function Ss(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 xs(t,e,n){let r=n?.apiKey,o=typeof t=="object"&&t!==null?t:{},s=gs.parse(o),i=s.writeBriefs??!0,a=s.scope??"all",l=ys(a);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let c=e.sessionId,u=T("audit-fit"),d={skill:u["01-skill-inspector.md"],command:u["02-command-inspector.md"],agent:u["03-agent-inspector.md"],hook:u["04-hook-inspector.md"]};for(let x of Yn)if(!d[x])throw new Error(`audit-fit skill missing inspector prompt for ${x}`);let p=l.runUserDiscovery?Bn():[],f=l.runPluginDiscovery?Kn():[],g={skill:[],command:[],agent:[]};for(let x of[...p,...f])g[x.type].push(x);let h=new w({apiKey:r}),m=()=>async x=>U.allowedTools.includes(x)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${x} not allowed for audit-fit inspectors. Allowed tools: ${U.allowedTools.join(", ")}`},y=[];for(let x of hs){let P=g[x];if(P.length===0)continue;let E=d[x];E&&y.push({type:x,prompt:`${E}
|
|
879
|
+
${ws(P)}`,artifacts:P,runPrompt:`Inspect every ${x} listed in the artifact section.`})}if(l.runHookInspector){let x=d.hook;if(x){let P=St(Y(),"settings.json"),E=Gn(P);y.push({type:"hook",prompt:`${x}
|
|
880
|
+
${ks(P,E)}`,artifacts:[],runPrompt:`Inspect every hook listed in the Discovered hooks section. Settings file: ${P}.`})}}let b=[];if(y.length>0){let x=await Promise.all(y.map(v=>h.forkSubagent({parent:{sessionId:c},config:{model:"sonnet",systemPrompt:`${U.systemPrompt}
|
|
881
881
|
|
|
882
|
-
${v.prompt}`,canUseTool:m()},idPrefix:`inspector-${v.type}`,outputSchema:I.array(Wn)}))),P=await Ke(y.map((v,L)=>{let j=x[L];if(!j)throw new Error(`audit-fit: missing handle for ${v.type} inspector`);return{handle:j,prompt:v.runPrompt}}),{failFast:!1}),E=[];for(let v=0;v<P.length;v++){let L=P[v],j=y[v];if(!j)continue;let ne=
|
|
882
|
+
${v.prompt}`,canUseTool:m()},idPrefix:`inspector-${v.type}`,outputSchema:I.array(Wn)}))),P=await Ke(y.map((v,L)=>{let j=x[L];if(!j)throw new Error(`audit-fit: missing handle for ${v.type} inspector`);return{handle:j,prompt:v.runPrompt}}),{failFast:!1}),E=[];for(let v=0;v<P.length;v++){let L=P[v],j=y[v];if(!j)continue;let ne=Ss(j.type,L);if(ne.kind==="failure"){E.push(ne.message);continue}let Pe=new Map;for(let B of j.artifacts)Pe.set(B.path,B.source);for(let B of ne.output){if(j.type==="hook"){if(B.source!=="user"){E.push(`${j.type}: hook verdict has source=${B.source} (must be 'user')`);continue}}else{let Ee=Pe.get(B.path);if(Ee===void 0){E.push(`${j.type}: verdict for unknown path ${B.path} (not in discovered list)`);continue}if(B.source!==Ee){E.push(`${j.type}: verdict source mismatch for ${B.path} (expected ${Ee}, got ${B.source})`);continue}}b.push(B)}}if(E.length>0){let v=E.map(L=>` - ${L}`).join(`
|
|
883
883
|
`);throw new Error(`audit-fit: ${E.length} inspector failure(s):
|
|
884
|
-
${v}`)}}let{inventory:F,misfits:N}=
|
|
884
|
+
${v}`)}}let{inventory:F,misfits:N}=bs(b),H=0;if(i){let x=ce();await zn(x,{recursive:!0});for(let P of N.filter(vs)){let E=P.path.replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,30),v=St(x,`audit-fit-${E}.md`),L=`---
|
|
885
885
|
theme: audit-fit
|
|
886
886
|
session_count: 1
|
|
887
887
|
---
|
|
@@ -904,7 +904,7 @@ ${P.rationale}
|
|
|
904
904
|
---
|
|
905
905
|
Generated by audit-fit on ${new Date().toISOString().split(".")[0]}Z
|
|
906
906
|
`;await Vn(v,L),H++}}let _=ie();await zn(_,{recursive:!0});let S=x=>{let P=0;for(let E of Object.values(x))for(let v of Object.values(E))P+=v;return P},M=x=>{let P=F.user[x]??{},E=F.plugin[x]??{},v=L=>Object.values(L).reduce((j,ne)=>j+ne,0);return v(P)+v(E)},D={timestamp:new Date().toISOString(),surface:"afk",scope:a,total_artifacts:b.length,misfits_count:N.length,briefs_written:H,by_source:{user:S(F.user),plugin:S(F.plugin)},by_type:{skill:M("skill"),command:M("command"),agent:M("agent"),hook:M("hook")}},z=St(_,"audit-fit-telemetry.jsonl");return await Vn(z,JSON.stringify(D)+`
|
|
907
|
-
`),{inventory:F,misfits:N,briefs_written:H,total_artifacts:b.length}}var
|
|
907
|
+
`),{inventory:F,misfits:N,briefs_written:H,total_artifacts:b.length}}var Ps={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:xs,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"]};J(Ps);import{z as k}from"zod";import{execFile as Is}from"node:child_process";import{promisify as Cs}from"node:util";import{tmpdir as _s}from"node:os";import{join as Ms}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 Es}from"node:url";import{dirname as As}from"node:path";var Ts=Es(import.meta.url),Eu=As(Ts),xt={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 Pt(t){let e={description:t.description,prompt:t.systemPrompt};return t.allowedTools&&(e.tools=[...t.allowedTools]),t.model&&(e.model=t.model),e}var Qn=Cs(Is),er=k.object({id:k.string(),claim:k.string(),confidence:k.number().min(0).max(1),evidence_sources:k.array(k.string()),location:k.string().optional(),proposed_fix:k.string().optional(),coverage_gaps:k.array(k.string()).optional(),boundary_flag:k.string().optional()}),Rs=k.object({hypothesis_id:k.string(),claim:k.string(),verdict:k.enum(["VERIFIED","REFUTED","INCONCLUSIVE"]),evidence:k.string(),gate_reason:k.string()}),tr=k.object({hypothesis_id:k.string(),reproducer_passed:k.boolean(),regressions:k.array(k.string()),confidence:k.number().min(0).max(1),verification_log:k.string()}),Bu=k.object({reproducer:k.string().optional(),hypotheses:k.array(er),premise_verifications:k.array(Rs).optional(),winner:k.object({hypothesis_id:k.string(),verification_log:k.string(),proposed_fix:k.string()}).optional(),verification_results:k.array(tr).optional()});async function Ds(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 u=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}:u?{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:u.verdict,evidence:u.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 Os(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 v=t;if(typeof v.failure=="string")return{failure:v.failure,repoPath:v.repoPath||process.cwd(),context:v.context||"",maxHypotheses:Math.min(v.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"],u=i["verify.md"];if(!a||!l||!c||!u)throw new Error("diagnose skill missing required prompts (system.md, research.md, hypothesis.md, verify.md)");let d=new w({apiKey:r}),p=Fs(o.context),f=`${U.systemPrompt}
|
|
908
908
|
|
|
909
909
|
${l}
|
|
910
910
|
|
|
@@ -918,7 +918,7 @@ Focus: GIT HISTORY
|
|
|
918
918
|
Failure: ${o.failure}${o.context?`
|
|
919
919
|
Context: ${o.context}`:""}
|
|
920
920
|
|
|
921
|
-
Repo: ${o.repoPath}`,h=await d.forkSubagent({parent:{sessionId:s},config:{model:"sonnet",systemPrompt:f,canUseTool:Xn()},idPrefix:"diagnose-codebase-research"}),m=await d.forkSubagent({parent:{sessionId:s},config:{model:"sonnet",systemPrompt:g,cwd:o.repoPath,agents:{"git-investigator":Pt(xt)},canUseTool
|
|
921
|
+
Repo: ${o.repoPath}`,h=await d.forkSubagent({parent:{sessionId:s},config:{model:"sonnet",systemPrompt:f,canUseTool:Xn()},idPrefix:"diagnose-codebase-research"}),m=await d.forkSubagent({parent:{sessionId:s},config:{model:"sonnet",systemPrompt:g,cwd:o.repoPath,agents:{"git-investigator":Pt(xt)},canUseTool:$s()},idPrefix:"diagnose-git-research"}),[y,b]=await Ke([{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:y?.output||y?.message||"No output",git:b?.output||b?.message||"No output"},N=await d.forkSubagent({parent:{sessionId:s},config:{model:"sonnet",systemPrompt:`${a}
|
|
922
922
|
|
|
923
923
|
${c}`,canUseTool:Xn()},idPrefix:"diagnose-hypothesis-synthesis",outputSchema:k.object({hypotheses:k.array(er)})}),H=`Given these research findings, synthesize 2\u20134 hypotheses (max 4):
|
|
924
924
|
|
|
@@ -928,16 +928,16 @@ ${JSON.stringify(F.codebase,null,2)}
|
|
|
928
928
|
GIT RESEARCH:
|
|
929
929
|
${JSON.stringify(F.git,null,2)}
|
|
930
930
|
|
|
931
|
-
Original failure: ${o.failure}`,_;try{_=await N.runToResult(H)}finally{await N.teardown().catch(()=>{})}if(_.status!=="succeeded"||!_.output)throw new Error(`hypothesis synthesis failed: ${C(_)}`);let S=_.output.hypotheses.slice(0,o.maxHypotheses);if(S.length===0)return{reproducer:p,hypotheses:[],verification_results:[]};let{premise_verifications:M,hypotheses_to_test:D}=await
|
|
931
|
+
Original failure: ${o.failure}`,_;try{_=await N.runToResult(H)}finally{await N.teardown().catch(()=>{})}if(_.status!=="succeeded"||!_.output)throw new Error(`hypothesis synthesis failed: ${C(_)}`);let S=_.output.hypotheses.slice(0,o.maxHypotheses);if(S.length===0)return{reproducer:p,hypotheses:[],verification_results:[]};let{premise_verifications:M,hypotheses_to_test:D}=await Ds(S,async v=>{let L=q("shadow-verify");if(!L)throw new Error("shadow-verify skill not registered");return(await L.handler({claims:v,context:`Original failure: ${o.failure}`},e)).verifications});if(D.length===0)return{reproducer:p,hypotheses:S,premise_verifications:M,verification_results:[]};let z=p||o.failure,x=D.map(v=>Ls(v,z,o.repoPath,s,u,d)),P=await Promise.all(x),E=P.find(v=>v.reproducer_passed);return{reproducer:p,hypotheses:S,premise_verifications:M.length>0?M:void 0,winner:E?{hypothesis_id:E.hypothesis_id,verification_log:E.verification_log,proposed_fix:S.find(v=>v.id===E.hypothesis_id)?.proposed_fix||""}:void 0,verification_results:P}}function Fs(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 Xn(){return async t=>U.allowedTools.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed. Allowed tools: ${U.allowedTools.join(", ")}`}}var Zn=[...U.allowedTools,"Agent"];function $s(){return async t=>Zn.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed for git orchestrator. Allowed tools: ${Zn.join(", ")}`}}async function Ls(t,e,n,r,o,s){let i=Ms(_s(),`diagnose-hyp-${t.id}-${Date.now()}`),a;try{await Qn("git",["worktree","add","--detach",i,"HEAD"],{cwd:n}),a=await s.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:`${o}
|
|
932
932
|
|
|
933
|
-
You are testing in an isolated worktree at: ${i}`,canUseTool:
|
|
933
|
+
You are testing in an isolated worktree at: ${i}`,canUseTool:js()},idPrefix:`diagnose-verifier-${t.id}`,outputSchema:tr});let l=`Test this hypothesis:
|
|
934
934
|
|
|
935
935
|
Claim: ${t.claim}
|
|
936
936
|
Location: ${t.location||"unknown"}
|
|
937
937
|
Proposed fix: ${t.proposed_fix||"unknown"}
|
|
938
938
|
Reproducer: ${e}
|
|
939
939
|
|
|
940
|
-
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 Qn("git",["worktree","remove","--force",i],{cwd:n})}catch{}}}function
|
|
940
|
+
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 Qn("git",["worktree","remove","--force",i],{cwd:n})}catch{}}}function js(){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.`}:U.allowedTools.includes(e)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${e} not allowed. Allowed tools: ${U.allowedTools.join(", ")}`}}var Hs={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:Os,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."};J(Hs);import{z as W}from"zod";import{execFile as Zs}from"child_process";import{promisify as ei}from"util";import{mkdir as ur,writeFile as dr}from"fs/promises";import{existsSync as cr}from"fs";import{join as ae}from"path";import{fileURLToPath as ti}from"url";import{fileURLToPath as Us}from"node:url";import{dirname as Ns}from"node:path";var Bs=Us(import.meta.url),qu=Ns(Bs),Et={name:"qualify",systemPrompt:`---
|
|
941
941
|
name: qualify
|
|
942
942
|
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.
|
|
943
943
|
model: sonnet
|
|
@@ -1170,17 +1170,17 @@ If the append fails (permissions, disk full, unwritable path), do not retry and
|
|
|
1170
1170
|
- 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).
|
|
1171
1171
|
|
|
1172
1172
|
Be skeptical. Protect the plugin from fluff. Stage 2 catches patterns that are strong when they work and catastrophic when they don't.
|
|
1173
|
-
`,sourcePath:"agent-framework-local/agents/qualify.md"};import{fileURLToPath as
|
|
1174
|
-
`;return await rr(e,o,{flag:"a"}),n}async function or(){let t=Ue(),e=
|
|
1175
|
-
`;await rr(e,o,{flag:"a"})}import{readFile as sr,readdir as
|
|
1173
|
+
`,sourcePath:"agent-framework-local/agents/qualify.md"};import{fileURLToPath as Ks}from"node:url";import{dirname as Gs}from"node:path";var zs=Ks(import.meta.url),Xu=Gs(zs);import{mkdir as nr,writeFile as rr}from"fs/promises";import{dirname as Vs,join as qs}from"path";async function Z(t){let e=Tn();await nr(Vs(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r={timestamp:n,surface:"afk",...t},o=JSON.stringify(r)+`
|
|
1174
|
+
`;return await rr(e,o,{flag:"a"}),n}async function or(){let t=Ue(),e=qs(t,"forge-thaw-history.jsonl");await nr(t,{recursive:!0});let r={timestamp:new Date().toISOString().split(".")[0]+"Z",surface:"afk",event:"forge.thaw_override",thaw_triggered:!0},o=JSON.stringify(r)+`
|
|
1175
|
+
`;await rr(e,o,{flag:"a"})}import{readFile as sr,readdir as Ws,writeFile as Ys,mkdir as Js,unlink as Qs}from"fs/promises";import{join as Ve}from"path";import{existsSync as Xs}from"fs";async function ir(t){let e=Ve(ce(),t+".md"),n=await sr(e,"utf-8");return{id:t,content:n}}async function ar(){let t=ce();return Xs(t)?(await Ws(t,{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".md")).map(r=>r.name.slice(0,-3)):[]}async function At(t,e){let n=ce(),r=Ve(n,t+".md"),o=Ve(n,e),s=Ve(o,t+".md");await Js(o,{recursive:!0});let i=await sr(r,"utf-8");await Ys(s,i,"utf-8"),await Qs(r)}function lr(t){let e=/^\*{0,2}(APPROVE|SALVAGE|REJECT)\*{0,2}/,n=t.split(`
|
|
1176
1176
|
`).map(c=>c.trim()).filter(c=>c),r=n.find(c=>e.test(c));if(!r)return{verdict:"REJECT",feedback:t};let o=r.match(e)?.[1];if(!o)return{verdict:"REJECT",feedback:t};let s=t.match(/score:\s*(\d+)/i),i=s&&s[1]?parseInt(s[1],10):void 0,a=n.indexOf(r),l=n.slice(a+1).join(`
|
|
1177
|
-
`).trim();return{verdict:o,score:i,feedback:l||r}}var
|
|
1178
|
-
`),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
|
|
1179
|
-
`;return await dr(n,i,{flag:"a"}),o}async function
|
|
1177
|
+
`).trim();return{verdict:o,score:i,feedback:l||r}}var ni=ei(Zs);function ri(){let t=process.env.AFK_EVAL_HARNESS_ROOT;if(t){let o=ae(t,"scripts","eval-harness","runner.py");if(cr(o))return o}let e=ti(import.meta.url),n=ae(e,"../../../.."),r=ae(n,"..","awa-private","scripts","eval-harness","runner.py");if(cr(r))return r;throw new Error(`Could not find eval-harness runner.py. Tried: ${r}`)}function oi(t){return ae(t,"..","..","..","plugins","awa-private")}function si(){return Ue()}function ii(t){let e=t.split(`
|
|
1178
|
+
`),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 ai(t){let e=si(),n=ae(e,"qualifications.jsonl");await ur(e,{recursive:!0});let o=new Date().toISOString().split(".")[0]+"Z",i=JSON.stringify({timestamp:o,surface:"afk",refers_to_run_id:t,source:"forge-gate-check-ts"})+`
|
|
1179
|
+
`;return await dr(n,i,{flag:"a"}),o}async function li(){let t;try{t=ri()}catch(l){throw new Error(`Failed to resolve eval-harness runner.py: ${l instanceof Error?l.message:String(l)}`)}let e=oi(t),n="",r="",o=0;try{let l=await ni("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"?ii(n):void 0,a;if(s==="OPEN"){let l=new Date().toISOString().split(".")[0]+"Z";a=await ai(l)}return{gate_status:s,exit_code:o,stdout:n,stderr:r||void 0,tasks_failed:i,ledger_entry_ref:a}}var ci=W.object({iteration:W.number().int().positive(),verdict:W.enum(["APPROVE","SALVAGE","REJECT"]),score:W.number().optional(),feedback:W.string()}),Dd=W.object({status:W.enum(["APPROVED","REJECTED","GATE_CLOSED","MAX_ITERATIONS"]),skill_path:W.string().optional(),qualify_verdicts:W.array(ci),brief_id:W.string().optional(),telemetry_ref:W.string()});async function ui(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=[],u="REJECTED",d,p;try{let f=await li();if(f.gate_status==="CLOSED"&&!i)return l=await Z({event:"forge.gate_check",gate_status:"CLOSED"}),{status:"GATE_CLOSED",qualify_verdicts:[],telemetry_ref:l};i&&f.gate_status==="CLOSED"&&(await or(),l=await Z({event:"forge.thaw_override",gate_status:"CLOSED"})),l=await Z({event:"forge.gate_check",gate_status:"OPEN"});let g="",h=!1;if(s)g=s,h=!0;else{let S=await ar();if(S.length>0){let M=S[0],D=await ir(M);g=D.content,p=D.id,h=!0}else{if(!e?.sessionId)throw new Error("forge requires parent session for gap discovery");let D=T("forge")["gap-discovery.md"];if(!D)throw new Error("forge skill missing gap-discovery.md prompt");let P=await(await new w({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:D},idPrefix:"forge-gap-discovery"})).runToResult("Identify the most impactful skill gap.");if(P.status!=="succeeded")throw new Error(`gap discovery failed: ${C(P)}`);if(g=P.message?.content||"",!g)throw new Error("gap discovery returned no concept")}}if(l=await Z({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"),y=m["generate.md"],b=m["system.md"];if(!y)throw new Error("forge skill missing generate.md prompt");if(!b)throw new Error("forge skill missing system.md prompt");let H=await(await new w({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:b},idPrefix:"forge-generate"})).runToResult(`Generate a new amplifier skill based on this concept:
|
|
1180
1180
|
|
|
1181
1181
|
${g}`);if(H.status!=="succeeded")throw new Error(`skill generation failed: ${C(H)}`);let _=H.message?.content||"";if(!_)throw new Error("skill generation returned no output");for(let S=1;S<=a;S++){let M=Et.systemPrompt;if(!M)throw new Error("qualify agent missing system prompt");let x=await(await new w({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:M},idPrefix:`forge-qualify-${S}`})).runToResult(`Evaluate this amplifier skill against the force-multiplier criteria:
|
|
1182
1182
|
|
|
1183
|
-
${_}`);if(x.status!=="succeeded")throw new Error(`qualify iteration ${S} failed: ${C(x)}`);let P=x.message?.content||"",{verdict:E,score:v,feedback:L}=lr(P),j={iteration:S,verdict:E,score:v,feedback:L};if(c.push(j),l=await Z({event:"forge.qualify_iteration",iteration:S,verdict:E,score:v||null}),E==="APPROVE"){u="APPROVED";break}else if(E==="SALVAGE"&&S<a){let ne=m["qualify-rework.md"];if(!ne)throw new Error("forge skill missing qualify-rework.md prompt");let Pe=ne.replace("{feedback}",L).replace("{original_skill}",_),ot=await(await new w({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:Pe},idPrefix:`forge-rework-${S}`})).runToResult("Refine the skill based on the feedback.");if(ot.status!=="succeeded")throw new Error(`rework iteration ${S} failed: ${C(ot)}`);if(_=ot.message?.content||"",!_)throw new Error(`rework iteration ${S} returned no output`)}else E==="REJECT"&&S>=a&&(u="MAX_ITERATIONS")}if(u==="APPROVED"){let S=_.match(/^name:\s*([^\n]+)/m),M=S&&S[1]?S[1].trim().replace(/^["']|["']$/g,""):"unknown",D=ae(ht(),M);await ur(D,{recursive:!0});let z=ae(D,"SKILL.md");await dr(z,_,"utf-8"),d=z,h&&p&&await At(p,"consumed"),l=await Z({event:"forge.complete",status:"APPROVED",skill_name:M,iterations:c.length})}else u==="MAX_ITERATIONS"&&(h&&p&&await At(p,"failed"),l=await Z({event:"forge.complete",status:"MAX_ITERATIONS",iterations:c.length}))}catch(f){throw l=await Z({event:"forge.error",error:f instanceof Error?f.message:String(f)}),f}return{status:u,skill_path:d,qualify_verdicts:c,brief_id:p,telemetry_ref:l}}var ui={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:ci,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"]};J(ui);var di={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"]}},pi={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"]}},fi={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"]}},mi={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"]}},gi={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"]}},hi={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"]}},yi={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"]}},pr={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"]}},fr={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"]}},qe=[di,pi,fi,mi,gi,hi,yi],ve=qe.map(t=>t.name);import{readFileSync as bi,existsSync as yr}from"fs";import{join as br}from"path";import{config as vi}from"dotenv";var mr={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 We(t){return t in mr}function gr(t){let e=mr[t];if(!e)throw new Error(`Invalid model: ${t}`);return e}function le(t){if(t!==void 0)return typeof t=="string"&&We(t)?gr(t):t}var Ye={model:"sonnet",maxTokens:4096,temperature:1},hr=!1;function Tt(){return process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||on()}function wi(){if(!hr){let r=[br(process.cwd(),".env"),_n(),Mn()];for(let o of r)if(yr(o)){vi({path:o});break}hr=!0}let t={},e=Tt();e!==void 0&&(t.apiKey=e);let n=process.env.AFK_MODEL??process.env.CLAUDE_MODEL;if(n){let r=n.toLowerCase();t.model=We(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 ki(){let t=[br(process.cwd(),"afk.config.json"),bt(),vt()];for(let e of t)if(yr(e))try{let n=bi(e,"utf-8"),r=JSON.parse(n),o={};if(typeof r.model=="string"&&r.model.length>0&&(o.model=(We(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 vr(t){let e=wi(),n=ki(),r={...Ye,...e,...n,...t};return{model:r.model??Ye.model,maxTokens:r.maxTokens??Ye.maxTokens,temperature:r.temperature??Ye.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 Tt()}function It(){let t=process.env.AFK_DEFAULT_SUBAGENT_MODEL;return!t||t.length===0?"sonnet":t}function Si(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 wr(){return Si(process.env.AFK_MAX_OUTPUT_TOKENS)}async function kr(t,e){let r=T("mint")["spec.md"];if(!r)throw new Error("mint skill missing spec.md prompt");let i=await(await new w().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 Sr(t,e){let r=T("mint")["research.md"];if(!r)throw new Error("mint skill missing research.md prompt");let i=await(await new w().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:$()},idPrefix:"mint-research"})).runToResult(`Gather context and research for this specification:
|
|
1183
|
+
${_}`);if(x.status!=="succeeded")throw new Error(`qualify iteration ${S} failed: ${C(x)}`);let P=x.message?.content||"",{verdict:E,score:v,feedback:L}=lr(P),j={iteration:S,verdict:E,score:v,feedback:L};if(c.push(j),l=await Z({event:"forge.qualify_iteration",iteration:S,verdict:E,score:v||null}),E==="APPROVE"){u="APPROVED";break}else if(E==="SALVAGE"&&S<a){let ne=m["qualify-rework.md"];if(!ne)throw new Error("forge skill missing qualify-rework.md prompt");let Pe=ne.replace("{feedback}",L).replace("{original_skill}",_),ot=await(await new w({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:Pe},idPrefix:`forge-rework-${S}`})).runToResult("Refine the skill based on the feedback.");if(ot.status!=="succeeded")throw new Error(`rework iteration ${S} failed: ${C(ot)}`);if(_=ot.message?.content||"",!_)throw new Error(`rework iteration ${S} returned no output`)}else E==="REJECT"&&S>=a&&(u="MAX_ITERATIONS")}if(u==="APPROVED"){let S=_.match(/^name:\s*([^\n]+)/m),M=S&&S[1]?S[1].trim().replace(/^["']|["']$/g,""):"unknown",D=ae(ht(),M);await ur(D,{recursive:!0});let z=ae(D,"SKILL.md");await dr(z,_,"utf-8"),d=z,h&&p&&await At(p,"consumed"),l=await Z({event:"forge.complete",status:"APPROVED",skill_name:M,iterations:c.length})}else u==="MAX_ITERATIONS"&&(h&&p&&await At(p,"failed"),l=await Z({event:"forge.complete",status:"MAX_ITERATIONS",iterations:c.length}))}catch(f){throw l=await Z({event:"forge.error",error:f instanceof Error?f.message:String(f)}),f}return{status:u,skill_path:d,qualify_verdicts:c,brief_id:p,telemetry_ref:l}}var di={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:ui,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"]};J(di);var pi={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"]}},fi={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"]}},mi={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"]}},gi={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"]}},hi={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"]}},yi={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"]}},bi={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"]}},pr={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"]}},fr={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"]}},qe=[pi,fi,mi,gi,hi,yi,bi],ve=qe.map(t=>t.name);import{readFileSync as vi,existsSync as yr}from"fs";import{join as br}from"path";import{config as wi}from"dotenv";var mr={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 We(t){return t in mr}function gr(t){let e=mr[t];if(!e)throw new Error(`Invalid model: ${t}`);return e}function le(t){if(t!==void 0)return typeof t=="string"&&We(t)?gr(t):t}var Ye={model:"sonnet",maxTokens:4096,temperature:1},hr=!1;function Tt(){return process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||on()}function ki(){if(!hr){let r=[br(process.cwd(),".env"),_n(),Mn()];for(let o of r)if(yr(o)){wi({path:o});break}hr=!0}let t={},e=Tt();e!==void 0&&(t.apiKey=e);let n=process.env.AFK_MODEL??process.env.CLAUDE_MODEL;if(n){let r=n.toLowerCase();t.model=We(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=[br(process.cwd(),"afk.config.json"),bt(),vt()];for(let e of t)if(yr(e))try{let n=vi(e,"utf-8"),r=JSON.parse(n),o={};if(typeof r.model=="string"&&r.model.length>0&&(o.model=(We(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 vr(t){let e=ki(),n=Si(),r={...Ye,...e,...n,...t};return{model:r.model??Ye.model,maxTokens:r.maxTokens??Ye.maxTokens,temperature:r.temperature??Ye.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 Tt()}function It(){let t=process.env.AFK_DEFAULT_SUBAGENT_MODEL;return!t||t.length===0?"sonnet":t}function xi(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 wr(){return xi(process.env.AFK_MAX_OUTPUT_TOKENS)}async function kr(t,e){let r=T("mint")["spec.md"];if(!r)throw new Error("mint skill missing spec.md prompt");let i=await(await new w().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 Sr(t,e){let r=T("mint")["research.md"];if(!r)throw new Error("mint skill missing research.md prompt");let i=await(await new w().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:$()},idPrefix:"mint-research"})).runToResult(`Gather context and research for this specification:
|
|
1184
1184
|
|
|
1185
1185
|
${t}`);if(i.status!=="succeeded"||!i.message)throw new Error(`research phase failed: ${C(i)}`);return i.message.content}async function xr(t,e,n){let o=T("mint")["plan.md"];if(!o)throw new Error("mint skill missing plan.md prompt");let i=await new w().forkSubagent({parent:{sessionId:n},config:{model:"sonnet",systemPrompt:o,apiKey:$()},idPrefix:"mint-plan"}),a=`Specification:
|
|
1186
1186
|
${t}
|
|
@@ -1188,13 +1188,13 @@ ${t}
|
|
|
1188
1188
|
Research findings:
|
|
1189
1189
|
${e}
|
|
1190
1190
|
|
|
1191
|
-
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
|
|
1191
|
+
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 Pi(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 Pr(t,e){if(Pi(t)<3)return null;try{return await q("parallelize").handler({plan:t})}catch{}try{let o=Je().get("parallelize");if(!o)return null;let s=new w({parentAbortSignal:e.abortSignal,apiKey:$()});try{let a=await(await s.forkSubagent({parent:e,config:{model:"sonnet",systemPrompt:o},idPrefix:"mint-parallelize"})).runToResult(JSON.stringify({plan:t}));return a.status==="succeeded"&&a.message?a.message.content:null}finally{await s.teardownAll()}}catch(r){return console.warn(`Parallelize dispatch failed: ${r instanceof Error?r.message:String(r)}`),null}}import{z as te}from"zod";function pe(t){let e=Q();e&&e({type:"panel",spec:t},{subagentId:"__main__"})}var Ei=te.object({status:te.enum(["PASS","FAIL"]),status_reason:te.string().optional(),files_changed:te.array(te.string()),tests_passed:te.boolean(),build_passed:te.boolean().optional(),verification_passed:te.boolean().optional(),notes:te.string()});async function Er(t,e,n){let o=T("mint")["build.md"];if(!o)throw new Error("mint skill missing build.md prompt");let i=await new w().forkSubagent({parent:{sessionId:n},config:{model:"sonnet",systemPrompt:o,apiKey:$()},idPrefix:"mint-build",outputSchema:Ei}),a=`Implementation plan:
|
|
1192
1192
|
${t}
|
|
1193
1193
|
|
|
1194
1194
|
`+(e?`Wave orchestration plan:
|
|
1195
1195
|
${JSON.stringify(e,null,2)}
|
|
1196
1196
|
|
|
1197
|
-
`:"")+"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,u={filesChanged:c.files_changed,testsPassed:c.tests_passed,notes:c.notes};return pe({kind:"checkpoint",title:"build",body:[`Files changed: ${u.filesChanged.length}`,`Tests: ${u.testsPassed?"passed":"failed"}`,"Next: verify"]}),u}import{z as fe}from"zod";var
|
|
1197
|
+
`:"")+"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,u={filesChanged:c.files_changed,testsPassed:c.tests_passed,notes:c.notes};return pe({kind:"checkpoint",title:"build",body:[`Files changed: ${u.filesChanged.length}`,`Tests: ${u.testsPassed?"passed":"failed"}`,"Next: verify"]}),u}import{z as fe}from"zod";var Ai=fe.object({status:fe.enum(["PASS","FAIL"]),status_reason:fe.string().optional(),issues:fe.array(fe.string()).default([]),summary:fe.string().optional()});async function Ct(t,e,n,r,o){let i=await new w().forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:o,apiKey:$()},idPrefix:`mint-verify-${t}`,outputSchema:Ai}),a=`Plan:
|
|
1198
1198
|
${e}
|
|
1199
1199
|
|
|
1200
1200
|
Build results:
|
|
@@ -1231,23 +1231,23 @@ ${JSON.stringify(t.buildResults,null,2)}
|
|
|
1231
1231
|
Verification results:
|
|
1232
1232
|
${JSON.stringify(t.verifyResults,null,2)}
|
|
1233
1233
|
|
|
1234
|
-
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 pe({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${l}`,`Heal iterations: ${c}`,`Idea: ${t.idea}`]}),a.message.content}import{existsSync as Ir,mkdirSync as
|
|
1234
|
+
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 pe({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${l}`,`Heal iterations: ${c}`,`Idea: ${t.idea}`]}),a.message.content}import{existsSync as Ir,mkdirSync as Ti,readFileSync as Ii,unlinkSync as Ci,writeFileSync as _i}from"fs";import{dirname as Mi,join as Ri}from"path";function _t(t){return Ri(Cn(),t,"mint-state.json")}function Cr(t,e){let n=_t(t);Ti(Mi(n),{recursive:!0}),_i(n,JSON.stringify(e,null,2),"utf-8")}function Di(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 _r(t){let e=_t(t);if(!Ir(e))return null;try{let n=JSON.parse(Ii(e,"utf-8"));return Di(n)?n:null}catch{return null}}function Mt(t){let e=_t(t);if(Ir(e))try{Ci(e)}catch{}}var Oi=2,Mr=/^\s*(?:--continue(?:\s+(?:approved|yes|y))?|approved?|yes|y|lgtm)\s*$/i,Fi='To approve and run the rest of the pipeline, say "approve", "yes", or "lgtm" \u2014 or invoke /mint --continue approved. 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 $i(t){if(typeof t=="string")return Mr.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&&Mr.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 Rr(t,e){if(!e.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let n=e.sessionId;try{t.currentPhase="research",t.research=await Sr(t.spec,n),se(t,"research",t.research),t.currentPhase="plan",t.plan=await xr(t.spec,t.research,n),se(t,"plan",t.plan),t.currentPhase="parallelize",t.waveOrchestrationPlan=await Pr(t.plan,e),se(t,"parallelize",JSON.stringify(t.waveOrchestrationPlan||"skipped")),t.currentPhase="build",t.buildResults=await Er(t.plan,t.waveOrchestrationPlan,n),se(t,"build",JSON.stringify(t.buildResults)),t.currentPhase="verify",t.verifyResults=await Qe(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<Oi;){let s=await Ar(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 Tr(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 Dr(t,e){return("completed"in e||e.phase==="heal-failed")&&Mt(t),e}async function Li(t,e){let n=$i(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??_r(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 Rr(i,e);return Dr(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.");Mt(r);let o={currentPhase:"spec",idea:n.idea,healIterations:0,history:[]};try{o.spec=await kr(n.idea,r),se(o,"spec",o.spec)}catch(i){throw new Error(`mint failed at spec: ${i}`)}if(!n.autoApprove)return Cr(r,o),{paused:!0,phase:"spec",spec:o.spec,state:o,nextStep:Fi};let s=await Rr(o,e);return Dr(r,s)}var ji={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:Li,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"]};J(ji);import{existsSync as Hi,readdirSync as Ui,readFileSync as Ni,statSync as Bi}from"fs";import{join as Ki}from"path";function Rt(t){let e=[];function n(r,o=0){if(o>10||!Hi(r))return;let s;try{s=Ui(r)}catch{return}for(let i of s){if(i.startsWith("."))continue;let a=Ki(r,i),l;try{l=Bi(a)}catch{continue}if(l.isFile()&&i==="SKILL.md"){let c=Gi(a);c.name&&e.push(c)}else l.isDirectory()&&n(a,o+1)}}return n(t),e}function Gi(t){try{let e=Ni(t,"utf-8");if(!e.startsWith(`---
|
|
1235
1235
|
`))return{};let n=e.slice(4),r=n.indexOf(`
|
|
1236
1236
|
---`);if(r===-1)return{};let o=n.slice(0,r),s=n.slice(r+4).trim(),i={},a=o.split(`
|
|
1237
1237
|
`);for(let l of a){if(!l)continue;let c=l.indexOf(":");if(c===-1)continue;let u=l.slice(0,c).trim(),d=l.slice(c+1).trim();u==="name"?i.name=d.replace(/^["']|["']$/g,""):u==="description"?i.description=d.replace(/^["']|["']$/g,""):u==="argumentHint"&&(i.argumentHint=d.replace(/^["']|["']$/g,""))}return s.length>0&&(i.body=s),i}catch{return{}}}function Or(t){let e=we(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(`
|
|
1238
|
-
`)}function we(t){let e=[],n=new Set;for(let o of Pn()){let s=q(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??[...G(ye()),...G(),...G(yt())];for(let o of r){if(o.type!=="local")continue;let s=Rt(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 Je(t){let e=new Map,n=t??[...G(ye()),...G(),...G(yt())];for(let r of n){if(r.type!=="local")continue;let o=Rt(r.path);for(let s of o)s.name&&s.body&&s.body.length>0&&e.set(s.name,s.body)}return e}var Gi=3,zi="claude-haiku-4-5-20251001",Vi=1024,qi=[{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"}],Ze=class{client;authMode;initSessionId;promptStream;toolDispatcher;maxTokens;tools;systemPrefix;userSystem;tokenRefresher;currentModel;currentPermissionMode;messages=[];closed=!1;abortController=null;pendingAbortReason=null;closedPromise;closeResolve=null;lastUsage=null;refreshPromise=null;constructor(e){this.client=e.client,this.authMode=e.authMode,this.initSessionId=Xe(),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.tokenRefresher=e.tokenRefresher,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=De(this.authMode,this.initSessionId,Xe()),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 u of this.turnWithAuthRetry(c)){if(this.closed)return;u.type==="turn.completed"&&(this.lastUsage=u.usage),yield u}}catch(u){if(i.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};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{}}}async*turnWithAuthRetry(e){let n=null;for await(let o of ft(e)){if(this.closed)return;if(o.type==="error"&&this.isRetryableAuth(o.error)){n=o;break}yield o}if(!n)return;let r=null;try{if(this.refreshPromise)r=await this.refreshPromise;else{this.refreshPromise=this.tokenRefresher();try{r=await this.refreshPromise??null}finally{this.refreshPromise=null}}}catch{this.refreshPromise=null}if(!r){yield n;return}this.client=r,e.client=this.client,e.headers=De(this.authMode,this.initSessionId,Xe()),yield*ft(e)}isRetryableAuth(e){return this.authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in e&&e.status===401}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()?cn(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 we().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return qi.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=Wi(),r=yn(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=Yi(),i=bn(o,s,Vi),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 d=De(this.authMode,this.initSessionId,Xe()),p=this.client,f=await Promise.resolve(p.messages.create(i,{headers:d,signal:a.signal}));l=await Ji(f)}catch(d){return a.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e}:{compacted:!1,reason:"summarization-failed: "+(d instanceof Error?d.message:String(d)),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=wn(this.messages,r,l),u=vn(this.messages,r,l);return this.messages.splice(0,this.messages.length,...u),{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 Wi(){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 Gi}function Yi(){let t=process.env.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?t:zi}async function Ji(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}function Dt(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:{allowed:!0}}var Qi=new Set(["agent","read_file","glob","grep","list_directory"]);function Xi(t){return Qi.has(t)}function Zi(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 ke=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??Xi}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 K)return{content:`Tool "${e.name}" blocked by PreToolUse hook: ${i.message}`,isError:!0};throw i}}let n=Dt(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(u){if(u instanceof K){n[i]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${u.message}`,isError:!0},r.add(i);continue}throw u}}let l=Dt(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=Zi(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:u}=o[l];return{result:await this.executeCore(c),originalIndex:u}}));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),u=i.indices[a.indexOf(l)];n[o[u].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 ea}from"child_process";function ta(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 na(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Fr=async(t,e)=>{let{command:n,timeout_ms:r}=ta(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",d),o(p))}let a=ea(n,{shell:!0,stdio:["ignore","pipe","pipe"]}),l=setTimeout(()=>{a.kill(),i({content:`Command timed out after ${r}ms`,isError:!0})},r),c="",u="";a.stdout.on("data",p=>{c+=p.toString()}),a.stderr.on("data",p=>{u+=p.toString()});let d=()=>{a.kill(),i({content:"Command aborted",isError:!0})};e.addEventListener("abort",d),a.on("close",()=>{let p=(c+u).trimEnd();p=na(p);let f=1e5;p.length>f&&(p=p.slice(0,f)+`
|
|
1239
|
-
[output truncated \u2014 exceeded 100KB]`),i({content:p})}),a.on("error",p=>{i({content:`Failed to execute: ${p.message}`,isError:!0})})})};import{promises as
|
|
1238
|
+
`)}function we(t){let e=[],n=new Set;for(let o of Pn()){let s=q(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??[...G(ye()),...G(),...G(yt())];for(let o of r){if(o.type!=="local")continue;let s=Rt(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 Je(t){let e=new Map,n=t??[...G(ye()),...G(),...G(yt())];for(let r of n){if(r.type!=="local")continue;let o=Rt(r.path);for(let s of o)s.name&&s.body&&s.body.length>0&&e.set(s.name,s.body)}return e}var zi={opus:128e3,opus_1m:128e3,sonnet:64e3,sonnet_1m:64e3,haiku:64e3,"claude-opus-4-7":128e3,"claude-opus-4-6":128e3,"claude-sonnet-4-6":64e3,"claude-haiku-4-5-20251001":64e3},Vi=64e3;function Fr(t){return zi[t]??Vi}var qi={opus:2e5,opus_1m:1e6,sonnet:2e5,sonnet_1m:1e6,haiku:2e5},Wi=2e5;function $r(t){return qi[t]??Wi}var Yi=3,Ji="claude-haiku-4-5-20251001",Qi=1024,Xi=[{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"}],Ze=class{client;authMode;initSessionId;promptStream;toolDispatcher;maxTokens;tools;systemPrefix;userSystem;tokenRefresher;currentModel;currentPermissionMode;messages=[];closed=!1;abortController=null;pendingAbortReason=null;closedPromise;closeResolve=null;lastUsage=null;refreshPromise=null;constructor(e){this.client=e.client,this.authMode=e.authMode,this.initSessionId=Xe(),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.tokenRefresher=e.tokenRefresher,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=De(this.authMode,this.initSessionId,Xe()),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 u of this.turnWithAuthRetry(c)){if(this.closed)return;u.type==="turn.completed"&&(this.lastUsage=u.usage),yield u}}catch(u){if(i.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};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{}}}async*turnWithAuthRetry(e){let n=null;for await(let o of ft(e)){if(this.closed)return;if(o.type==="error"&&this.isRetryableAuth(o.error)){n=o;break}yield o}if(!n)return;let r=null;try{if(this.refreshPromise)r=await this.refreshPromise;else{this.refreshPromise=this.tokenRefresher();try{r=await this.refreshPromise??null}finally{this.refreshPromise=null}}}catch{this.refreshPromise=null}if(!r){yield n;return}this.client=r,e.client=this.client,e.headers=De(this.authMode,this.initSessionId,Xe()),yield*ft(e)}isRetryableAuth(e){return this.authMode==="oauth"&&this.tokenRefresher!==void 0&&"status"in e&&e.status===401}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()?cn(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 we().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return Xi.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=$r(this.currentModel),r;if(e&&n>0){let o=(e.inputTokens??0)+(e.outputTokens??0)+(e.cachedInputTokens??0)+(e.cacheCreationTokens??0);r=Math.min(100,Math.max(0,o/n*100))}return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:this.lastUsage,...r!==void 0?{percentage:r}:{},maxTokens:n}}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=Zi(),r=yn(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=ea(),i=bn(o,s,Qi),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 d=De(this.authMode,this.initSessionId,Xe()),p=this.client,f=await Promise.resolve(p.messages.create(i,{headers:d,signal:a.signal}));l=await ta(f)}catch(d){return a.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e}:{compacted:!1,reason:"summarization-failed: "+(d instanceof Error?d.message:String(d)),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=wn(this.messages,r,l),u=vn(this.messages,r,l);return this.messages.splice(0,this.messages.length,...u),{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 Zi(){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 Yi}function ea(){let t=process.env.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?t:Ji}async function ta(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}function Dt(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:{allowed:!0}}var na=new Set(["agent","read_file","glob","grep","list_directory"]);function ra(t){return na.has(t)}function oa(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 ke=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??ra}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 K)return{content:`Tool "${e.name}" blocked by PreToolUse hook: ${i.message}`,isError:!0};throw i}}let n=Dt(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(u){if(u instanceof K){n[i]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${u.message}`,isError:!0},r.add(i);continue}throw u}}let l=Dt(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=oa(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:u}=o[l];return{result:await this.executeCore(c),originalIndex:u}}));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),u=i.indices[a.indexOf(l)];n[o[u].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 sa}from"child_process";function ia(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 aa(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Lr=async(t,e)=>{let{command:n,timeout_ms:r}=ia(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",d),o(p))}let a=sa(n,{shell:!0,stdio:["ignore","pipe","pipe"]}),l=setTimeout(()=>{a.kill(),i({content:`Command timed out after ${r}ms`,isError:!0})},r),c="",u="";a.stdout.on("data",p=>{c+=p.toString()}),a.stderr.on("data",p=>{u+=p.toString()});let d=()=>{a.kill(),i({content:"Command aborted",isError:!0})};e.addEventListener("abort",d),a.on("close",()=>{let p=(c+u).trimEnd();p=aa(p);let f=1e5;p.length>f&&(p=p.slice(0,f)+`
|
|
1239
|
+
[output truncated \u2014 exceeded 100KB]`),i({content:p})}),a.on("error",p=>{i({content:`Failed to execute: ${p.message}`,isError:!0})})})};import{promises as la}from"fs";var jr=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 la.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(`
|
|
1240
1240
|
`),u=Math.max(0,o-1),d=Math.min(c.length,u+s),p=c.slice(u,d),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,y)=>{let b=u+y+1;return`${String(b).padStart(g," ")} ${m}`}).join(`
|
|
1241
1241
|
`);if(p.length<f){let m=u+1,y=u+p.length,b=y<f?` \u2014 pass offset=${y+1} to continue`:"";return{content:`${h}
|
|
1242
|
-
... (showing lines ${m}-${y} of ${f}${b})`}}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
|
|
1242
|
+
... (showing lines ${m}-${y} of ${f}${b})`}}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 ca}from"fs/promises";import{mkdir as ua}from"fs/promises";import{dirname as da}from"path";function pa(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 Hr=async(t,e)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:n,content:r}=pa(t);try{let o=da(n);return await ua(o,{recursive:!0}),await ca(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 fa,writeFile as ma}from"fs/promises";function ga(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 ha(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 ya(t,e,n){let r=t.split(`
|
|
1243
1243
|
`),o=0,s=0;for(let c=0;c<r.length;c++){let u=r[c]?.length??0,d=o+u+1;if(o+u>=n+e.length){s=c;break}o=d}let i=Math.max(0,s-2),a=Math.min(r.length,s+3);return`...${r.slice(i,a).join(`
|
|
1244
|
-
`)}...`}var
|
|
1244
|
+
`)}...`}var Ur=async(t,e)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:n,old_string:r,new_string:o,replace_all:s}=ga(t);try{let i=await fa(n,"utf-8"),a=ha(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 ma(n,l,"utf-8");let u=ya(i,r,c);return{content:`${a===1?`Replaced 1 occurrence in ${n}`:`Replaced ${a} occurrences in ${n}`}
|
|
1245
1245
|
|
|
1246
|
-
${u}`}}catch(i){return{content:`Error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}};import{promises as
|
|
1246
|
+
${u}`}}catch(i){return{content:`Error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}};import{promises as Br}from"fs";import ba from"path";function va(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=Nr(l);if(a===0){let u=n.match(new RegExp(`^${c}`));if(!u)return!1;i=u[0].length}else if(a===s.length-1){let u=new RegExp(`${c}$`);if(!n.slice(i).match(u))return!1}else{let u=new RegExp(c),d=n.slice(i).match(u);if(!d)return!1;let p=d.index??0;i+=p+d[0].length}}return!0}return new RegExp(`^${Nr(r)}$`).test(n)}function Nr(t){return t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]")}async function wa(t,e){let n=[];async function o(s,i){if(n.length>=500)return!0;try{let a=await Br.readdir(s,{withFileTypes:!0});for(let l of a){if(n.length>=500)return!0;let c=ba.join(s,l.name),u=i?`${i}/${l.name}`:l.name;if(va(u,e)&&n.push(u),l.isDirectory()&&await o(c,u))return!0}}catch{}return!1}return await o(t,""),n}var Kr=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 Br.stat(o)).isDirectory())return{content:`Invalid input: path is not a directory: ${o}`,isError:!0};let i=await wa(o,r);if(i.length===0)return{content:`No files matched pattern '${r}' in ${o}`};let a=i.join(`
|
|
1247
1247
|
`);return i.length>=500&&(a+=`
|
|
1248
|
-
[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
|
|
1249
|
-
[output truncated]`),a({content:g})}),c.on("error",f=>{a({content:`Failed to execute grep: ${f.message}`,isError:!0})})})};import{promises as
|
|
1250
|
-
`)}}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
|
|
1248
|
+
[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 ka}from"child_process";function Sa(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 xa(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Gr=async(t,e)=>{let{pattern:n,path:r,include:o}=Sa(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=ka("grep",l),u="",d="";c.stdout.on("data",f=>{u+=f.toString()}),c.stderr.on("data",f=>{d+=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: ${d.trim()}`,isError:!0});return}let g=u.trimEnd();g=xa(g);let h=1e5;g.length>h&&(g=g.slice(0,h)+`
|
|
1249
|
+
[output truncated]`),a({content:g})}),c.on("error",f=>{a({content:`Failed to execute grep: ${f.message}`,isError:!0})})})};import{promises as Pa}from"fs";var zr=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 Pa.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(`
|
|
1250
|
+
`)}}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 Vr(){return new Map([["bash",Lr],["read_file",jr],["write_file",Hr],["edit_file",Ur],["glob",Kr],["grep",Gr],["list_directory",zr]])}var qr=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1251
1251
|
|
|
1252
1252
|
- Use read_file before editing to verify the exact content you want to change.
|
|
1253
1253
|
- Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
|
|
@@ -1257,28 +1257,28 @@ ${u}`}}catch(i){return{content:`Error: ${i instanceof Error?i.message:String(i)}
|
|
|
1257
1257
|
- When bash output is very long, it may be truncated. If you need the full output, redirect to a file and read it.
|
|
1258
1258
|
- Use absolute paths for file operations.
|
|
1259
1259
|
|
|
1260
|
-
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
|
|
1260
|
+
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 Yr="anthropic-direct",Ea="claude-sonnet-4-5-20250929",Jr=null;var ee=class{name=Yr;tools;providerFactory;skillExecutor;constructor(e={}){let n=[...qe];e.subagentExecutor&&n.push(pr),e.skillExecutor&&n.push(fr),this.tools=e.tools??new ke({handlers:Vr(),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(`${Yr} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let o=Xt(r),s=pt(r,o),i=this.providerFactory??Jr,a=i?i(s):new Wr(s),l=Zt(o),c=Aa(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?le(n.model)??n.model:Ea,d=Ta(n,u),p=this.tools instanceof ke?[...this.tools.toolDefs]:[...qe],f=[...G(ye()),...G()],g=n.plugins??[],h=[...f,...g],m=this.skillExecutor?Or(h):"",y=n.cwd||process.cwd(),b=[qr];b.push(`# Environment
|
|
1261
1261
|
- Working directory: ${y}`),m.length>0&&b.push(m),c&&b.push(c);let F=b.join(`
|
|
1262
1262
|
|
|
1263
|
-
`),N;if(o==="oauth"){let H=this.providerFactory??
|
|
1263
|
+
`),N;if(o==="oauth"){let H=this.providerFactory??Jr;N=async()=>{let _=await sn();if(!_)return null;let S=pt(_,"oauth");return H?H(S):new Wr(S)}}return new Ze({client:a,authMode:o,promptStream:e.prompt,toolDispatcher:this.tools,model:u,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:d,tools:p,userSystem:F,systemPrefix:l,tokenRefresher:N})}};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 Ta(t,e){let n=t.maxOutputTokens;return typeof n=="number"&&Number.isFinite(n)&&n>0?Math.floor(n):Fr(e)}var Qr=new ee;import{Codex as Zr}from"@openai/codex-sdk";import{mkdtempSync as Ia,rmSync as Ca,writeFileSync as _a}from"node:fs";import{tmpdir as Ma}from"node:os";import{join as Xr}from"node:path";var Se="openai-codex",Ra=[{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 Da(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 he(Se,e.join(", "),`${Se} provider does not support AgentConfig fields: ${e.join(", ")}`)}function eo(t){return t==="plan"?{sandboxMode:"read-only",approvalPolicy:"untrusted"}:{sandboxMode:"workspace-write",approvalPolicy:"never"}}function Oa(t){if(t)switch(t){case"minimal":case"low":case"medium":case"high":case"xhigh":return t;case"max":return"xhigh";default:return}}function Fa(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 $a(t){let e=Ia(Xr(Ma(),"afk-codex-instr-")),n=Xr(e,"instructions.md");return _a(n,t,"utf-8"),{path:n,dispose:()=>{try{Ca(e,{recursive:!0,force:!0})}catch{}}}}function La(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*ja(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*Ha(t.item,t.type==="item.completed",e,n,r))}}function*Ha(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}
|
|
1264
1264
|
`+(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(`
|
|
1265
|
-
`);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 Ot=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
|
|
1266
|
-
`);u=await this.thread.runStreamed(d,{signal:c.signal})}catch(d){if(c.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}try{for await(let d of u.events){if(this.closed)return;d.type==="thread.started"&&(o=d.thread_id),yield*
|
|
1267
|
-
`);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 Ba(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 Ka(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 Ga(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 za(t,e){let n=Ha(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}=Na(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 Va(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 oo(t){try{for await(let e of t.providerStream)switch(e.type){case"session.init":Ka(t,e);break;case"session.status":Ga(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),Va(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":za(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=Ba(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 so(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 io(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 ao(t){try{await no(t.hookRegistry,{event:"SessionStart",sessionId:t.sessionId()},{signal:t.abortSignal}),await oo({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 nt=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 lo(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 u=o;a(()=>n({...u,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 re=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,so(e.abortSignal,this.abortController,()=>{this.onAbort()}),this.initSdkLifecycle()}initSdkLifecycle(){this.messageQueue=new Re;let e=le(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=io(this.config,e);this.stateManager=new nt(n,r),this.inputStream=new tt(()=>this.sessionId);let o=this.config.provider??to(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=ao({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(lo(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 V("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,mt))]).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=le(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,mt))])}catch{}this.messageQueue.complete(),await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await ro(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 V("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){Ft(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){Ft(n,e.event);let a;try{a=await i(e)}catch(l){throw new K(`hook handler threw during ${e.event}`,e.event,l instanceof Error?l.message:String(l),{cause:l})}if(Ft(n,e.event),qa(a))throw new K(`hook handler blocked ${e.event}${a.reason?`: ${a.reason}`:""}`,e.event,a.reason);s=a}return s}};function qa(t){return t.continue===!1||t.decision==="block"}function Ft(t,e){if(t?.aborted){let n=t.reason,r=`aborted during ${e}${n?`: ${String(n)}`:""}`;throw new V(r)}}function co(){return new $t}function uo(){return co()}var Wa=["shadow-verify","shadow_verify","resolve","diagnose","appmap","qualify","mint"],Ya=[/\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],Ja=[/\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],Qa=`shadow-verify nudge:
|
|
1265
|
+
`);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 Ot=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 Zr(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 u;try{let d=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(`
|
|
1266
|
+
`);u=await this.thread.runStreamed(d,{signal:c.signal})}catch(d){if(c.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}try{for await(let d of u.events){if(this.closed)return;d.type==="thread.started"&&(o=d.thread_id),yield*ja(d,o,n,r)}}catch(d){if(c.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};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}=eo(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 Ra.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 he(Se,"rewindFiles",`${Se} 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}},Ua=null;var et=class{name=Se;query(e){Da(e.config);let n=La(e.config),r=Oa(e.config.effort),{sandboxMode:o,approvalPolicy:s}=eo(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=Fa(e.config),l={};n!==void 0&&(l.apiKey=n);let c;if(a!==void 0){let{path:g,dispose:h}=$a(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 u=Ua,d=u??(g=>new Zr(g)),p=`codex-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,f=new Ot({threadOptions:i,codexOptions:l,...e.config.resume!==void 0?{resumeId:e.config.resume}:{},...c!==void 0?{instructionsDispose:c}:{}},e.prompt,p);if(u){let g=d(l);f.codex=g,f.thread=e.config.resume?g.resumeThread(e.config.resume,i):g.startThread(i)}return f}},to=new et;var Na=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||Na.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 no(t){return de(t)==="openai-codex"?to:Qr}async function ro(t,e,n={}){t&&await t.dispatch(e,n.signal)}async function oo(t,e,n={}){if(t)try{await t.dispatch(e,n.signal)}catch(r){if(r instanceof K||r instanceof V){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 tt=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 Ba(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 Ka(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 Ga(t){let e=Buffer.byteLength(t,"utf8"),n=Ka(e),r=t.split(`
|
|
1267
|
+
`);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 za(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 Va(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 qa(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 Wa(t,e){let n=Ba(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}=Ga(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 Ya(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 so(t){try{for await(let e of t.providerStream)switch(e.type){case"session.init":Va(t,e);break;case"session.status":qa(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),Ya(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":Wa(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=za(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 io(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 ao(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 lo(t){try{await ro(t.hookRegistry,{event:"SessionStart",sessionId:t.sessionId()},{signal:t.abortSignal}),await so({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 nt=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 co(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 u=o;a(()=>n({...u,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 re=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,io(e.abortSignal,this.abortController,()=>{this.onAbort()}),this.initSdkLifecycle()}initSdkLifecycle(){this.messageQueue=new Re;let e=le(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=ao(this.config,e);this.stateManager=new nt(n,r),this.inputStream=new tt(()=>this.sessionId);let o=this.config.provider??no(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=lo({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(co(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 V("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,mt))]).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=le(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,mt))])}catch{}this.messageQueue.complete(),await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await oo(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 V("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){Ft(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){Ft(n,e.event);let a;try{a=await i(e)}catch(l){throw new K(`hook handler threw during ${e.event}`,e.event,l instanceof Error?l.message:String(l),{cause:l})}if(Ft(n,e.event),Ja(a))throw new K(`hook handler blocked ${e.event}${a.reason?`: ${a.reason}`:""}`,e.event,a.reason);s=a}return s}};function Ja(t){return t.continue===!1||t.decision==="block"}function Ft(t,e){if(t?.aborted){let n=t.reason,r=`aborted during ${e}${n?`: ${String(n)}`:""}`;throw new V(r)}}function uo(){return new $t}function po(){return uo()}var Qa=["shadow-verify","shadow_verify","resolve","diagnose","appmap","qualify","mint"],Xa=[/\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],Za=[/\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],el=`shadow-verify nudge:
|
|
1268
1268
|
|
|
1269
1269
|
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).
|
|
1270
1270
|
|
|
1271
1271
|
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.
|
|
1272
1272
|
|
|
1273
|
-
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
|
|
1273
|
+
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 tl(t){if(!t)return!1;let e=t.toLowerCase();return Qa.some(n=>e.includes(n))}function nl(t){return Za.some(e=>e.test(t))}function rl(t){let e=0;for(let n of Xa)n.test(t)&&e++;return e}function fo(t){if(t.event!=="SubagentStop")return{};let e=t.lastMessage??"";return e.length<600?{}:tl(t.agentType)?{}:nl(e)?{}:rl(e)<2?{}:{injectContext:el}}function Lt(t){let e=po();return e.register("SubagentStop",fo),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 ol="[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 jt(t,e){return!t||!e?t:`${t}
|
|
1274
1274
|
|
|
1275
|
-
${
|
|
1275
|
+
${ol}`}function sl(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 me=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??xe;if(n>=r)return{content:`Skill tool not available at nesting depth ${n} (max ${r})`,isError:!0};let o;try{o=sl(e.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=q(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=we(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 w({parentAbortSignal:r,apiKey:this.ctx.apiKey,progressSink:Q()});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 w({parentAbortSignal:o,apiKey:this.ctx.apiKey,progressSink:Q()});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=Je(this.ctx.pluginConfigs)),this.pluginBodies.get(e)}};var xe=3;function Ht(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}var il=[...ve,"agent","skill"];function mo(){return({childExecutor:t,childSkillExecutor:e})=>new ee({permissions:{allowedTools:il},subagentExecutor:t,skillExecutor:e})}function go(t,e){return(n,r,o)=>new me({parentSession:Ht(o),defaultModel:t,apiKey:e,depth:n,maxDepth:r})}function al(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 rt=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=al(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??xe,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 w({parentAbortSignal:e.signal});let c=new t({subagentManager:s,parentSession:Ht(e.signal),defaultConfig:this.ctx.defaultConfig,defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,depth:r+1,maxDepth:o}),u=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,e.signal):void 0;i.provider=this.ctx.childProviderFactory({childExecutor:c,childSkillExecutor:u})}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 ll(){let t;try{t=vr()}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(`
|
|
1276
1276
|
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=Jt(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(`
|
|
1277
1277
|
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(`
|
|
1278
|
-
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=le(s.model)??s.model;console.log(`Creating session with model: ${s.model} -> ${i}`);let l=de(i)==="openai-codex",c=l?void 0:wr(),u;if(!l){let h,m=s.apiKey??t.apiKey??"",y=new w({apiKey:m}),b={get sessionId(){return h?.sessionId},getInputStreamRef(){return h?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return h?.abortSignal??new AbortController().signal}},F=
|
|
1278
|
+
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=le(s.model)??s.model;console.log(`Creating session with model: ${s.model} -> ${i}`);let l=de(i)==="openai-codex",c=l?void 0:wr(),u;if(!l){let h,m=s.apiKey??t.apiKey??"",y=new w({apiKey:m}),b={get sessionId(){return h?.sessionId},getInputStreamRef(){return h?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return h?.abortSignal??new AbortController().signal}},F=mo(),N=new rt({subagentManager:y,parentSession:b,defaultConfig:{apiKey:m,systemPrompt:s.systemPrompt??t.systemPrompt},defaultSubagentModel:It(),childProviderFactory:F,childSkillExecutorFactory:go(s.model,m)}),H=new me({parentSession:b,defaultModel:s.model,defaultSubagentModel:It(),apiKey:m}),_=[...ve,"agent","skill"];u=new ee({permissions:{allowedTools:_},subagentExecutor:N,skillExecutor:H});let S=s.systemPrompt||t.systemPrompt,M=t.autoRouting?.telegram??!1,D=typeof S=="string"?jt(S,M):S,z=new re({...s.apiKey!==void 0?{apiKey:s.apiKey}:{},model:s.model,...D!==void 0?{systemPrompt:D}:{},maxTurns:100,...c!==void 0?{maxOutputTokens:c}:{},provider:u,hookRegistry:Lt()});return h=z,z}let d=s.systemPrompt||t.systemPrompt,p=t.autoRouting?.telegram??!1,f=typeof d=="string"?jt(d,p):d;return new re({...s.apiKey!==void 0?{apiKey:s.apiKey}:{},model:s.model,...f!==void 0?{systemPrompt:f}:{},maxTurns:100,...c!==void 0?{maxOutputTokens:c}:{},hookRegistry:Lt()})}});try{o.start(),console.log("\u2705 Bot started successfully!"),console.log(`
|
|
1279
1279
|
\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(`
|
|
1280
1280
|
\u{1F4AC} Send any message to chat with the agent.`),console.log(`
|
|
1281
1281
|
\u23F9\uFE0F Press Ctrl+C to stop the bot.`);let s=setInterval(()=>{let a=o.getStats();console.log(`
|
|
1282
1282
|
\u{1F4CA} Stats: ${a.activeSessions} active sessions, ${a.totalChats} total chats`)},3e5),i=async()=>{console.log(`
|
|
1283
1283
|
|
|
1284
|
-
\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)}}
|
|
1284
|
+
\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)}}ll().catch(t=>{console.error("\u274C Unhandled error:",t),process.exit(1)});
|