agent-afk 0.2.4 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +171 -158
- package/dist/index.mjs +79 -78
- package/dist/postinstall.mjs +87 -0
- package/dist/telegram.mjs +85 -84
- package/package.json +27 -25
package/dist/index.mjs
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
function
|
|
2
|
-
`)[
|
|
3
|
-
`)
|
|
1
|
+
function Gr(){return process.env.AFK_DEBUG==="1"||process.env.DEBUG==="1"}function A(...t){Gr()&&console.log(...t)}var q=class extends Error{constructor(e){super(e),this.name="AbortError"}},_e=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},G=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 ae=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 xr from"@anthropic-ai/sdk";var zr="claude-code-20250219,oauth-2025-04-20",Kr="claude-cli/1.0.0 (external, cli)",qr="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function Dt(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function ot(t,e){return e==="oauth"?{authToken:t}:{apiKey:t}}function De(t,e,n){return t!=="oauth"?{}:{"anthropic-beta":zr,"x-app":"cli","User-Agent":Kr,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Ot(t){return t!=="oauth"?null:[{type:"text",text:qr}]}import{execFileSync as Ft}from"child_process";import{existsSync as Vr,readFileSync as Wr,writeFileSync as Yr}from"fs";import{homedir as $t,userInfo as jt}from"os";import{join as Lt}from"path";var Jr="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Qr="https://platform.claude.com/v1/oauth/token",Xr=300*1e3;function Ht(){let t=Nt();if(t===void 0)return;let e=Bt(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 Ut(){let t=Nt();if(t===void 0)return;let e=Bt(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Xr)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 Zr(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}:{}},eo(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
2
|
+
`)}return n.accessToken}function Nt(){if(process.platform==="darwin")try{return Ft("security",["find-generic-password","-s","Claude Code-credentials","-a",jt().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=Lt($t(),".claude",".credentials.json");if(!Vr(t))return;try{return Wr(t,"utf-8")}catch{return}}}function Bt(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 Zr(t){try{let e=await fetch(Qr,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:Jr})});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 eo(t){if(process.platform==="darwin")Ft("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",jt().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=Lt($t(),".claude",".credentials.json");Yr(e,t,"utf-8")}}import{randomUUID as qe}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 Gt(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Kt(n,e);return r===n?t:[...t.slice(0,-1),r]}function zt(t,e){if(t.length===0)return t;let n=t[t.length-1],r=to(n,e);return r===n?t:[...t.slice(0,-1),r]}function to(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=Kt(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function Kt(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}import{randomUUID as oo}from"node:crypto";function qt(t,e){if(!t)return{stopReason:e??null};let n={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null};return t.cache_read_input_tokens!=null&&(n.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(n.cacheCreationTokens=t.cache_creation_input_tokens),n.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n}function Vt(t,e){let n=(c,d)=>{if(!(c==null&&d==null))return(c??0)+(d??0)},r={stopReason:e.stopReason??t.stopReason??null},o=n(t.inputTokens,e.inputTokens);o!==void 0&&(r.inputTokens=o);let s=n(t.outputTokens,e.outputTokens);s!==void 0&&(r.outputTokens=s);let i=n(t.cachedInputTokens,e.cachedInputTokens);i!==void 0&&(r.cachedInputTokens=i);let a=n(t.cacheCreationTokens,e.cacheCreationTokens);a!==void 0&&(r.cacheCreationTokens=a);let l=n(t.totalTokens,e.totalTokens);return l!==void 0&&(r.totalTokens=l),r}function no(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function ro(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:no(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*Wt(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:ro(n,r,o)}}var so=0;function io(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(`
|
|
3
|
+
`)[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*st(t){let e=t.maxToolUseIterations??so,n={stopReason:null},r=0,o=oo(),s=Date.now();for(;;){if(t.signal.aborted)return;let i=Oe()?zt(t.messages,Fe()):t.messages,a={model:t.model,max_tokens:t.maxTokens,messages:i,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools}:{}},l;try{l=await Promise.resolve(t.client.messages.create(a,{headers:t.headers,signal:t.signal}))}catch(m){if(t.signal.aborted)return;yield{type:"error",error:m instanceof Error?m:new Error(String(m))};return}let c=null,d=!1;try{for await(let m of Wt(l,t.ctx))if(m.kind==="event"){if(m.event.type==="error"){yield m.event,d=!0;break}yield m.event}else{c=m.result;break}}catch(m){if(t.signal.aborted)return;yield{type:"error",error:m instanceof Error?m:new Error(String(m))};return}if(d)return;if(c===null){yield{type:"turn.completed",usage:n,sessionId:t.ctx.sessionId};return}if(n=Vt(n,qt(c.usage,c.stopReason)),c.stopReason!=="tool_use"){c.text.length>0&&(yield{type:"assistant.message",text:c.text,sessionId:t.ctx.sessionId},c.text.length<=200&&(yield{type:"suggestion",suggestion:c.text,sessionId:t.ctx.sessionId})),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 u=[];for(let m of c.toolUseBlocks)u.push({id:m.id,name:m.name,input:m.input,signal:t.signal}),yield{type:"tool.use.start",toolUseId:m.id,toolName:m.name,toolInput:io(m.input),sessionId:t.ctx.sessionId};if(t.signal.aborted)return;let p;if(t.toolDispatcher.executeBatch)p=await t.toolDispatcher.executeBatch(u);else{p=[];for(let m of u){if(t.signal.aborted){p.push({content:"Tool call aborted",isError:!0});continue}try{p.push(await t.toolDispatcher.execute(m))}catch(w){let v=w instanceof Error?w.message:String(w);p.push({content:`Tool execution threw: ${v}`,isError:!0})}}}let f=[];for(let m=0;m<u.length;m++){let w=u[m],v=p[m];yield{type:"tool.output",toolUseId:w.id,content:v.content,...v.isError===!0?{isError:!0}:{},sessionId:t.ctx.sessionId},f.push({type:"tool_result",tool_use_id:w.id,content:v.content,...v.isError===!0?{is_error:!0}:{}})}let g={role:"user",content:f};t.messages.push(g),r+=1;let h=c.toolUseBlocks[c.toolUseBlocks.length-1];if(yield{type:"progress",progress:{taskId:o,description:"Tool-use loop",summary:`Iteration ${r}: used ${h?.name??"unknown"}`,lastToolName:h?.name,totalTokens:n.totalTokens??0,toolUses:r,durationMs:Date.now()-s},sessionId:t.ctx.sessionId},e>0&&r>=e){yield{type:"turn.completed",usage:{...n,stopReason:"tool_use_loop_capped"},sessionId:t.ctx.sessionId};return}}}var ao=["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(`
|
|
4
|
+
`),Yt="[Compacted summary of earlier conversation]",Jt="Acknowledged. Continuing from the summary above.";function lo(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 Qt(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&&lo(o)&&(n+=1,n===e))return r}return-1}function Xt(t,e,n){let r=co(t);return{model:e,max_tokens:n,system:ao,messages:[{role:"user",content:`Summarize the following conversation transcript. Follow the system instructions exactly.
|
|
4
5
|
|
|
5
6
|
<transcript>
|
|
6
7
|
`+r+`
|
|
7
|
-
</transcript>`}],stream:!0}}function
|
|
8
|
+
</transcript>`}],stream:!0}}function Zt(t,e,n){return[{role:"user",content:Yt+`
|
|
8
9
|
|
|
9
|
-
`+n},{role:"assistant",content:
|
|
10
|
-
`).trim()}function
|
|
10
|
+
`+n},{role:"assistant",content:Jt},...t.slice(e)]}function en(t,e,n){let r=uo(t.slice(0,e)),o=Yt.length+2+n.length+Jt.length,s=Math.max(0,r-o);return Math.round(s/4)}function co(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=tn(o.input);e.push(`[tool call: ${i} ${a}]`)}else if(s==="tool_result"){let i=o.content;e.push(`[tool result: ${nn(i)}]`)}else s==="image"?e.push("[image]"):s==="document"&&e.push("[document]")}e.push("")}return e.join(`
|
|
11
|
+
`).trim()}function tn(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function nn(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 uo(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+=tn(r.input).length:o==="tool_result"&&(e+=nn(r.content).length)}return e}import{z as T}from"zod";import{mkdir as Sn,appendFile as xn}from"fs/promises";import{join as ut}from"path";var rn={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
|
|
11
12
|
|
|
12
13
|
You are an inspector auditing skills for correct type categorization. Skills come from two sources:
|
|
13
14
|
- **User-scope** \u2014 authored directly by the user under \`~/.afk/skills/<name>/SKILL.md\`
|
|
@@ -485,9 +486,9 @@ You received SALVAGE feedback on a skill draft. Your job is to produce a structu
|
|
|
485
486
|
|
|
486
487
|
**Rework process:**
|
|
487
488
|
1. **Extract failures** \u2014 identify every rubric dimension qualify scored \u22642 (Stage 1) or 0\u20131 (Stage 2). List each with its score and qualify's stated reason.
|
|
488
|
-
2. **
|
|
489
|
+
2. **Name the failure geometry** \u2014 for the weakest Stage 2 dimensions, name the *default failure* the current design produces and the *preferred failure shape* it should produce instead. Then design a concrete structural change (sub-agent dispatch, gate/checkpoint, worktree isolation, phased execution, verification step) that transforms one into the other. Do not polish wording \u2014 change the skill's operational structure.
|
|
489
490
|
3. **Prioritize** \u2014 pick the single fix that most improves the weakest dimension while naturally pulling up adjacent ones.
|
|
490
|
-
4. **Rebuild** \u2014 rewrite the full SKILL.md incorporating that fix. Preserve the core insight; change the machinery.
|
|
491
|
+
4. **Rebuild** \u2014 rewrite the full SKILL.md incorporating that fix. Preserve the core insight; change the machinery. If the redesign changes the expected breakage pattern, declare \`failure_modes\` in frontmatter using only the modes actually implicated by the weak Stage 2 scores \u2014 not taxonomy decoration.
|
|
491
492
|
|
|
492
493
|
**Output:**
|
|
493
494
|
Return only the revised SKILL.md markdown block. No preamble, no explanation \u2014 just the refined skill definition.
|
|
@@ -501,7 +502,7 @@ You are orchestrating the creation of a new amplifier skill. Your job is to guid
|
|
|
501
502
|
3. **Qualification loop**: dispatch the qualify agent up to 3 times to validate the skill against the force multiplier criteria.
|
|
502
503
|
4. **Approval and archival**: on APPROVE, write the skill to the plugin; on final REJECT, report the best attempt and archive to failed/.
|
|
503
504
|
|
|
504
|
-
Always stamp outputs with \`surface: "
|
|
505
|
+
Always stamp outputs with \`surface: "afk"\` for telemetry.
|
|
505
506
|
`},mint:{"build.md":`# Phase 5: Build
|
|
506
507
|
|
|
507
508
|
You are a developer executing an implementation plan. Your task is to write code that realizes the specification and passes the tests defined in the plan.
|
|
@@ -799,9 +800,9 @@ Field semantics:
|
|
|
799
800
|
- \`status_reason\` \u2014 short reason when \`FAIL\`; omit when \`PASS\`.
|
|
800
801
|
- \`issues\` \u2014 concrete blockers with file:line citations where possible. Empty array when \`PASS\`.
|
|
801
802
|
- \`summary\` \u2014 optional narrative; the orchestrator may surface it to the user. Keep it concise.
|
|
802
|
-
`}};function I(t){let e=
|
|
803
|
-
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}`)}function
|
|
804
|
-
`;await
|
|
803
|
+
`}};function I(t){let e=rn[t];if(!e){let n=Object.keys(rn).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+t+". "+r)}return e}var $e=new Map;function V(t){$e.set(t.name,t)}function W(t){let e=$e.get(t);if(e)return e;let n=Array.from($e.keys()).sort(),r=n.length>0?`
|
|
804
|
+
Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}`)}function on(){return Array.from($e.keys()).sort()}var ye=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 be=0,je=5e3;async function we(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 _e(`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 sn(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 G||r instanceof q?(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 yo,writeFile as bo}from"fs/promises";import{dirname as wo,join as vo}from"path";import{join as L,dirname as po}from"path";import{homedir as fo}from"os";import{fileURLToPath as mo}from"url";function Y(){return process.env.AFK_HOME||L(fo(),".afk")}function re(){return L(Y(),"agent-framework")}function ln(){return L(re(),"forge-telemetry.jsonl")}function le(){return L(re(),"briefs")}function Le(){return L(re(),"ceiling-ledger")}function it(){return L(Y(),"skills")}function ce(){return L(Y(),"plugins")}function go(){return L(process.cwd(),".afk")}function ve(){return L(go(),"plugins")}function He(){return L(ce(),".index.json")}function at(){let t=mo(import.meta.url),e=po(t);return L(e,"bundled-plugins")}function ho(){return L(Y(),"state")}function cn(){return L(ho(),"sessions")}function ko(){return vo(re(),"routing-decisions.jsonl")}async function dn(t){if(!(process.env.VITEST||process.env.NODE_ENV==="test"))try{let e=ko();await yo(wo(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,surface:"afk",...t})+`
|
|
805
|
+
`;await bo(e,r,{flag:"a"})}catch{}}import{AsyncLocalStorage as So}from"node:async_hooks";var xo=new So;function de(){return xo.getStore()}function lt(t){let e=Po(t);return e!==void 0?e:Eo(t)}function Po(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return un(n.trim())}function Eo(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=Ao(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=un(r);if(o!==void 0)return o}}function Ao(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 un(t){try{return JSON.parse(t)}catch{return}}function pn(t,e,n,r){if(!r)return{id:t,status:e,message:n};let o=lt(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 fn(t,e,n){let r=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:r}}function C(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}var Ue=class{constructor(e,n,r,o,s,i,a,l,c,d,u,p,f){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=d;this.agentType=u;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;get status(){return this.currentStatus}async run(e){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let n=Date.now(),r=we(this.streamToFinalMessage(e),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=r;try{let o=await r;return this.lastMessage=o.content,this.lastDurationMs=Date.now()-n,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",this.onTerminal(),o}catch(o){throw this.lastDurationMs=Date.now()-n,this.currentStatus!=="cancelled"&&(this.currentStatus="failed",this.latestTerminalStatus="failed"),this.onTerminal(),o}finally{this.inFlight=null}}async streamToFinalMessage(e){let n,r="",o,s=this.progressSink??de(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let a of this.session.sendMessageStream(e))if(s&&s(a,i),a.type==="chunk"&&a.chunk.type==="content"&&(r+=a.chunk.content),a.type==="message")n=a.message;else if(a.type==="error"){o=a.error;break}else if(a.type==="done")break;if(o)throw o;if(n)return n;if(r.length>0)return{role:"assistant",content:r,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(e){try{let n=await this.run(e);return pn(this.id,this.currentStatus,n,this.outputSchema)}catch(n){return fn(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 P=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;abortGraph=new ye;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 sn(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 oe(i),l=e.parent.getInputStreamRef?.(),c=e.parent.abortSignal,d=this.progressSink??de(),u=new Ue(n,a,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??be,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},l,c,e.idPrefix,d,e.parent.sessionId);return this.active.set(n,u),await dn({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,parent_session_id:e.parent.sessionId}),u}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}};async function Ne(t,e={}){let{failFast:n=!0,teardown:r=!0}=e;if(t.length===0)return[];let o=new Array(t.length),s=new Set(t.map((a,l)=>l)),i=t.map((a,l)=>a.handle.runToResult(a.prompt).then(c=>{if(o[l]=c,s.delete(l),n&&c.status!=="succeeded")for(let d of s){let u=t[d];u&&u.handle.status==="running"&&u.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(t.map(a=>a.handle.teardown())),o}import{fileURLToPath as To}from"node:url";import{dirname as Co}from"node:path";var Io=To(import.meta.url),Al=Co(Io),H={name:"research-agent",systemPrompt:`---
|
|
805
806
|
name: research-agent
|
|
806
807
|
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.
|
|
807
808
|
model: sonnet
|
|
@@ -851,45 +852,45 @@ Unless the dispatcher specifies a different schema, return:
|
|
|
851
852
|
\`\`\`
|
|
852
853
|
|
|
853
854
|
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\`.
|
|
854
|
-
`,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{
|
|
855
|
-
`)}function
|
|
855
|
+
`,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 te,readdirSync as jo,readFileSync as Lo}from"fs";import{join as J}from"path";import{existsSync as ct,readFileSync as _o,readdirSync as Do,statSync as Oo}from"fs";import{join as ke,resolve as gn}from"path";import{existsSync as Mo,mkdirSync as Il,readFileSync as Ro,renameSync as Ml,writeFileSync as Rl,unlinkSync as _l}from"fs";function mn(t=He()){if(!Mo(t))return Be();try{let e=Ro(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Be();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 Be()}catch{return Be()}}function Be(){return{version:2,plugins:{},marketplaces:{}}}var Fo=5,hn="cache";function B(t=ce()){if(!ct(t))return[];let e=t===ce()?He():ke(t,".index.json"),n=mn(e),r=[];return yn(t,t,0,r,new Set,n.plugins),r}function yn(t,e,n,r,o,s){if(n>Fo||o.has(e))return;if(o.add(e),ct(ke(e,".claude-plugin","plugin.json"))){let a=dt(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=Do(e)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=ke(e,a),c;try{c=Oo(l)}catch{continue}c.isDirectory()&&yn(t,l,n+1,r,o,s)}}function dt(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=ke(t,hn,s),l=$o(i,e)??r[2];if(l)return{layout:"cache",key:`${s}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function $o(t,e){let n=ke(t,".claude-plugin","marketplace.json");if(!ct(n))return null;let r;try{r=JSON.parse(_o(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=gn(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("../"))&&gn(t,a.source)===s)return a.name}return null}var bn=["command","agent"];function wn(t=Y()){let e=[],n=J(t,"skills");if(te(n))for(let r of Ge(n)){let o=J(n,r,"SKILL.md");te(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of bn){let o=J(t,`${r}s`);if(te(o))for(let s of Ge(o))s.endsWith(".md")&&e.push({path:J(o,s),type:r,source:"user"})}return e}function vn(t=ce()){if(!te(t))return[];let e=[],n=B(t);for(let r of n){let s=dt(t,r.path)?.key,i=J(r.path,"skills");if(te(i))for(let a of Ge(i)){let l=J(i,a,"SKILL.md");if(!te(l))continue;let c={path:l,type:"skill",source:"plugin"};s&&(c.plugin_key=s),e.push(c)}for(let a of bn){let l=J(r.path,`${a}s`);if(te(l))for(let c of Ge(l)){if(!c.endsWith(".md"))continue;let d={path:J(l,c),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function kn(t=J(Y(),"settings.json")){if(!te(t))return[];try{let e=Lo(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function Ge(t){try{return jo(t).filter(e=>!e.startsWith("."))}catch{return[]}}var En=T.object({path:T.string(),type:T.enum(["skill","command","agent","hook"]),source:T.enum(["user","plugin"]),plugin_key:T.string().optional(),verdict:T.enum(["correct","misfit","outlier"]),recommended_type:T.string(),rationale:T.string(),confidence:T.enum(["high","med","low"])}),Pn=T.record(T.string(),T.record(T.string(),T.number())),tc=T.object({inventory:T.object({user:Pn,plugin:Pn}),misfits:T.array(En),briefs_written:T.number(),total_artifacts:T.number()}),Ho=T.object({writeBriefs:T.boolean().optional(),scope:T.enum(["user","plugin","all"]).optional()}),Uo=["skill","command","agent"],An=["skill","command","agent","hook"];function No(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function Bo(t){let e=()=>{let s={};for(let i of An)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 Go(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function zo(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(`
|
|
856
|
+
`)}function Ko(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(`
|
|
856
857
|
`);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(`
|
|
857
|
-
`)}function
|
|
858
|
-
${
|
|
859
|
-
${
|
|
858
|
+
`)}function qo(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 Vo(t,e,n){let r=n?.apiKey,o=typeof t=="object"&&t!==null?t:{},s=Ho.parse(o),i=s.writeBriefs??!0,a=s.scope??"all",l=No(a);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let c=e.sessionId,d=I("audit-fit"),u={skill:d["01-skill-inspector.md"],command:d["02-command-inspector.md"],agent:d["03-agent-inspector.md"],hook:d["04-hook-inspector.md"]};for(let k of An)if(!u[k])throw new Error(`audit-fit skill missing inspector prompt for ${k}`);let p=l.runUserDiscovery?wn():[],f=l.runPluginDiscovery?vn():[],g={skill:[],command:[],agent:[]};for(let k of[...p,...f])g[k.type].push(k);let h=new P({apiKey:r}),m=()=>async k=>H.allowedTools.includes(k)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${k} not allowed for audit-fit inspectors. Allowed tools: ${H.allowedTools.join(", ")}`},w=[];for(let k of Uo){let S=g[k];if(S.length===0)continue;let E=u[k];E&&w.push({type:k,prompt:`${E}
|
|
859
|
+
${zo(S)}`,artifacts:S,runPrompt:`Inspect every ${k} listed in the artifact section.`})}if(l.runHookInspector){let k=u.hook;if(k){let S=ut(Y(),"settings.json"),E=kn(S);w.push({type:"hook",prompt:`${k}
|
|
860
|
+
${Ko(S,E)}`,artifacts:[],runPrompt:`Inspect every hook listed in the Discovered hooks section. Settings file: ${S}.`})}}let v=[];if(w.length>0){let k=await Promise.all(w.map(y=>h.forkSubagent({parent:{sessionId:c},config:{model:"sonnet",systemPrompt:`${H.systemPrompt}
|
|
860
861
|
|
|
861
|
-
${
|
|
862
|
-
`);throw new Error(`audit-fit: ${
|
|
863
|
-
${
|
|
862
|
+
${y.prompt}`,canUseTool:m()},idPrefix:`inspector-${y.type}`,outputSchema:T.array(En)}))),S=await Ne(w.map((y,O)=>{let F=k[O];if(!F)throw new Error(`audit-fit: missing handle for ${y.type} inspector`);return{handle:F,prompt:y.runPrompt}}),{failFast:!1}),E=[];for(let y=0;y<S.length;y++){let O=S[y],F=w[y];if(!F)continue;let ee=qo(F.type,O);if(ee.kind==="failure"){E.push(ee.message);continue}let Me=new Map;for(let N of F.artifacts)Me.set(N.path,N.source);for(let N of ee.output){if(F.type==="hook"){if(N.source!=="user"){E.push(`${F.type}: hook verdict has source=${N.source} (must be 'user')`);continue}}else{let Re=Me.get(N.path);if(Re===void 0){E.push(`${F.type}: verdict for unknown path ${N.path} (not in discovered list)`);continue}if(N.source!==Re){E.push(`${F.type}: verdict source mismatch for ${N.path} (expected ${Re}, got ${N.source})`);continue}}v.push(N)}}if(E.length>0){let y=E.map(O=>` - ${O}`).join(`
|
|
863
|
+
`);throw new Error(`audit-fit: ${E.length} inspector failure(s):
|
|
864
|
+
${y}`)}}let{inventory:$,misfits:K}=Bo(v),U=0;if(i){let k=le();await Sn(k,{recursive:!0});for(let S of K.filter(Go)){let E=S.path.replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,30),y=ut(k,`audit-fit-${E}.md`),O=`---
|
|
864
865
|
theme: audit-fit
|
|
865
866
|
session_count: 1
|
|
866
867
|
---
|
|
867
868
|
|
|
868
|
-
# Audit: ${
|
|
869
|
+
# Audit: ${S.path}
|
|
869
870
|
|
|
870
|
-
**Current type:** ${
|
|
871
|
-
**Recommended type:** ${
|
|
871
|
+
**Current type:** ${S.type}
|
|
872
|
+
**Recommended type:** ${S.recommended_type}
|
|
872
873
|
|
|
873
874
|
## Rationale
|
|
874
875
|
|
|
875
|
-
${
|
|
876
|
+
${S.rationale}
|
|
876
877
|
|
|
877
878
|
## Migration Steps
|
|
878
879
|
|
|
879
|
-
1. Review the artifact in \`${
|
|
880
|
-
2. Evaluate the recommended change to \`${
|
|
880
|
+
1. Review the artifact in \`${S.path}\`
|
|
881
|
+
2. Evaluate the recommended change to \`${S.recommended_type}\`
|
|
881
882
|
3. If appropriate, refactor using the patterns in \`/forge\` or the public plugin
|
|
882
883
|
|
|
883
884
|
---
|
|
884
885
|
Generated by audit-fit on ${new Date().toISOString().split(".")[0]}Z
|
|
885
|
-
`;await
|
|
886
|
-
`),{inventory
|
|
886
|
+
`;await xn(y,O),U++}}let M=re();await Sn(M,{recursive:!0});let x=k=>{let S=0;for(let E of Object.values(k))for(let y of Object.values(E))S+=y;return S},_=k=>{let S=$.user[k]??{},E=$.plugin[k]??{},y=O=>Object.values(O).reduce((F,ee)=>F+ee,0);return y(S)+y(E)},j={timestamp:new Date().toISOString(),surface:"afk",scope:a,total_artifacts:v.length,misfits_count:K.length,briefs_written:U,by_source:{user:x($.user),plugin:x($.plugin)},by_type:{skill:_("skill"),command:_("command"),agent:_("agent"),hook:_("hook")}},Z=ut(M,"audit-fit-telemetry.jsonl");return await xn(Z,JSON.stringify(j)+`
|
|
887
|
+
`),{inventory:$,misfits:K,briefs_written:U,total_artifacts:v.length}}var Wo={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:Vo,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"]};V(Wo);import{z as b}from"zod";import{execFile as Xo}from"node:child_process";import{promisify as Zo}from"node:util";import{tmpdir as es}from"node:os";import{join as ts}from"node:path";function Tn(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 Yo}from"node:url";import{dirname as Jo}from"node:path";var Qo=Yo(import.meta.url),ac=Jo(Qo),pt={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 ft(t){let e={description:t.description,prompt:t.systemPrompt};return t.allowedTools&&(e.tools=[...t.allowedTools]),t.model&&(e.model=t.model),e}var Cn=Zo(Xo),Rn=b.object({id:b.string(),claim:b.string(),confidence:b.number().min(0).max(1),evidence_sources:b.array(b.string()),location:b.string().optional(),proposed_fix:b.string().optional(),coverage_gaps:b.array(b.string()).optional(),boundary_flag:b.string().optional()}),ns=b.object({hypothesis_id:b.string(),claim:b.string(),verdict:b.enum(["VERIFIED","REFUTED","INCONCLUSIVE"]),evidence:b.string(),gate_reason:b.string()}),_n=b.object({hypothesis_id:b.string(),reproducer_passed:b.boolean(),regressions:b.array(b.string()),confidence:b.number().min(0).max(1),verification_log:b.string()}),Pc=b.object({reproducer:b.string().optional(),hypotheses:b.array(Rn),premise_verifications:b.array(ns).optional(),winner:b.object({hypothesis_id:b.string(),verification_log:b.string(),proposed_fix:b.string()}).optional(),verification_results:b.array(_n).optional()});async function rs(t,e){let n=t.map(l=>({hypothesis:l,decision:Tn(l)})).filter(l=>l.decision.verify);if(n.length===0)return{premise_verifications:[],hypotheses_to_test:t};let r=[],o;try{r=await e(n.map(l=>l.hypothesis.claim))}catch(l){o=l instanceof Error?l.message:String(l)}let s=n.map((l,c)=>{let d=r[c];return o!==void 0?{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:`shadow-verify dispatch failed: ${o}`,gate_reason:l.decision.reason}:d?{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:d.verdict,evidence:d.evidence,gate_reason:l.decision.reason}:{hypothesis_id:l.hypothesis.id,claim:l.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:"no verifier result for this claim",gate_reason:l.decision.reason}}),i=new Set(s.filter(l=>l.verdict==="REFUTED").map(l=>l.hypothesis_id)),a=i.size===0?t:t.filter(l=>!i.has(l.id));return{premise_verifications:s,hypotheses_to_test:a}}async function 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 y=t;if(typeof y.failure=="string")return{failure:y.failure,repoPath:y.repoPath||process.cwd(),context:y.context||"",maxHypotheses:Math.min(y.maxHypotheses||4,4)}}throw new Error("diagnose handler requires input.failure (string) or a string argument")})();if(!e?.sessionId)throw new Error("diagnose requires a parent session with sessionId");let s=e.sessionId,i=I("diagnose"),a=i["system.md"],l=i["research.md"],c=i["hypothesis.md"],d=i["verify.md"];if(!a||!l||!c||!d)throw new Error("diagnose skill missing required prompts (system.md, research.md, hypothesis.md, verify.md)");let u=new P({apiKey:r}),p=ss(o.context),f=`${H.systemPrompt}
|
|
887
888
|
|
|
888
889
|
${l}
|
|
889
890
|
|
|
890
891
|
Focus: CODEBASE
|
|
891
892
|
Failure: ${o.failure}${o.context?`
|
|
892
|
-
Context: ${o.context}`:""}`,g=`${
|
|
893
|
+
Context: ${o.context}`:""}`,g=`${H.systemPrompt}
|
|
893
894
|
|
|
894
895
|
${l}
|
|
895
896
|
|
|
@@ -897,26 +898,26 @@ Focus: GIT HISTORY
|
|
|
897
898
|
Failure: ${o.failure}${o.context?`
|
|
898
899
|
Context: ${o.context}`:""}
|
|
899
900
|
|
|
900
|
-
Repo: ${o.repoPath}`,
|
|
901
|
+
Repo: ${o.repoPath}`,h=await u.forkSubagent({parent:{sessionId:s},config:{model:"sonnet",systemPrompt:f,canUseTool:In()},idPrefix:"diagnose-codebase-research"}),m=await u.forkSubagent({parent:{sessionId:s},config:{model:"sonnet",systemPrompt:g,cwd:o.repoPath,agents:{"git-investigator":ft(pt)},canUseTool:is()},idPrefix:"diagnose-git-research"}),[w,v]=await Ne([{handle:h,prompt:"Analyze the codebase for potential causes of this failure."},{handle:m,prompt:"Analyze git history for recent changes that could cause this failure."}],{failFast:!1}),$={codebase:w?.output||w?.message||"No output",git:v?.output||v?.message||"No output"},K=await u.forkSubagent({parent:{sessionId:s},config:{model:"sonnet",systemPrompt:`${a}
|
|
901
902
|
|
|
902
|
-
${c}`,canUseTool:
|
|
903
|
+
${c}`,canUseTool:In()},idPrefix:"diagnose-hypothesis-synthesis",outputSchema:b.object({hypotheses:b.array(Rn)})}),U=`Given these research findings, synthesize 2\u20134 hypotheses (max 4):
|
|
903
904
|
|
|
904
905
|
CODEBASE RESEARCH:
|
|
905
|
-
${JSON.stringify(
|
|
906
|
+
${JSON.stringify($.codebase,null,2)}
|
|
906
907
|
|
|
907
908
|
GIT RESEARCH:
|
|
908
|
-
${JSON.stringify(
|
|
909
|
+
${JSON.stringify($.git,null,2)}
|
|
909
910
|
|
|
910
|
-
Original failure: ${o.failure}`,
|
|
911
|
+
Original failure: ${o.failure}`,M;try{M=await K.runToResult(U)}finally{await K.teardown().catch(()=>{})}if(M.status!=="succeeded"||!M.output)throw new Error(`hypothesis synthesis failed: ${C(M)}`);let x=M.output.hypotheses.slice(0,o.maxHypotheses);if(x.length===0)return{reproducer:p,hypotheses:[],verification_results:[]};let{premise_verifications:_,hypotheses_to_test:j}=await rs(x,async y=>{let O=W("shadow-verify");if(!O)throw new Error("shadow-verify skill not registered");return(await O.handler({claims:y,context:`Original failure: ${o.failure}`},e)).verifications});if(j.length===0)return{reproducer:p,hypotheses:x,premise_verifications:_,verification_results:[]};let Z=p||o.failure,k=j.map(y=>as(y,Z,o.repoPath,s,d,u)),S=await Promise.all(k),E=S.find(y=>y.reproducer_passed);return{reproducer:p,hypotheses:x,premise_verifications:_.length>0?_:void 0,winner:E?{hypothesis_id:E.hypothesis_id,verification_log:E.verification_log,proposed_fix:x.find(y=>y.id===E.hypothesis_id)?.proposed_fix||""}:void 0,verification_results:S}}function ss(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 In(){return async t=>H.allowedTools.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed. Allowed tools: ${H.allowedTools.join(", ")}`}}var Mn=[...H.allowedTools,"Agent"];function is(){return async t=>Mn.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed for git orchestrator. Allowed tools: ${Mn.join(", ")}`}}async function as(t,e,n,r,o,s){let i=ts(es(),`diagnose-hyp-${t.id}-${Date.now()}`),a;try{await Cn("git",["worktree","add","--detach",i,"HEAD"],{cwd:n}),a=await s.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:`${o}
|
|
911
912
|
|
|
912
|
-
You are testing in an isolated worktree at: ${i}`,canUseTool:
|
|
913
|
+
You are testing in an isolated worktree at: ${i}`,canUseTool:ls()},idPrefix:`diagnose-verifier-${t.id}`,outputSchema:_n});let l=`Test this hypothesis:
|
|
913
914
|
|
|
914
915
|
Claim: ${t.claim}
|
|
915
916
|
Location: ${t.location||"unknown"}
|
|
916
917
|
Proposed fix: ${t.proposed_fix||"unknown"}
|
|
917
918
|
Reproducer: ${e}
|
|
918
919
|
|
|
919
|
-
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
|
|
920
|
+
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 Cn("git",["worktree","remove","--force",i],{cwd:n})}catch{}}}function ls(){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.`}:H.allowedTools.includes(e)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${e} not allowed. Allowed tools: ${H.allowedTools.join(", ")}`}}var cs={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."};V(cs);import{z}from"zod";import{execFile as xs}from"child_process";import{promisify as Ps}from"util";import{mkdir as Nn,writeFile as Bn}from"fs/promises";import{existsSync as Un}from"fs";import{join as se}from"path";import{fileURLToPath as Es}from"url";import{fileURLToPath as ds}from"node:url";import{dirname as us}from"node:path";var ps=ds(import.meta.url),Ic=us(ps),mt={name:"qualify",systemPrompt:`---
|
|
920
921
|
name: qualify
|
|
921
922
|
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.
|
|
922
923
|
model: sonnet
|
|
@@ -1149,31 +1150,31 @@ If the append fails (permissions, disk full, unwritable path), do not retry and
|
|
|
1149
1150
|
- 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).
|
|
1150
1151
|
|
|
1151
1152
|
Be skeptical. Protect the plugin from fluff. Stage 2 catches patterns that are strong when they work and catastrophic when they don't.
|
|
1152
|
-
`,sourcePath:"agent-framework-local/agents/qualify.md"};import{fileURLToPath as
|
|
1153
|
-
`;return await
|
|
1154
|
-
`;await
|
|
1155
|
-
`).map(
|
|
1156
|
-
`).trim();return{verdict:
|
|
1157
|
-
`),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
|
|
1158
|
-
`;return await
|
|
1153
|
+
`,sourcePath:"agent-framework-local/agents/qualify.md"};import{fileURLToPath as fs}from"node:url";import{dirname as ms}from"node:path";var gs=fs(import.meta.url),Oc=ms(gs);import{mkdir as Dn,writeFile as On}from"fs/promises";import{dirname as hs,join as ys}from"path";async function Q(t){let e=ln();await Dn(hs(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r={timestamp:n,surface:"afk",...t},o=JSON.stringify(r)+`
|
|
1154
|
+
`;return await On(e,o,{flag:"a"}),n}async function Fn(){let t=Le(),e=ys(t,"forge-thaw-history.jsonl");await Dn(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)+`
|
|
1155
|
+
`;await On(e,o,{flag:"a"})}import{readFile as $n,readdir as bs,writeFile as ws,mkdir as vs,unlink as ks}from"fs/promises";import{join as ze}from"path";import{existsSync as Ss}from"fs";async function jn(t){let e=ze(le(),t+".md"),n=await $n(e,"utf-8");return{id:t,content:n}}async function Ln(){let t=le();return Ss(t)?(await bs(t,{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".md")).map(r=>r.name.slice(0,-3)):[]}async function gt(t,e){let n=le(),r=ze(n,t+".md"),o=ze(n,e),s=ze(o,t+".md");await vs(o,{recursive:!0});let i=await $n(r,"utf-8");await ws(s,i,"utf-8"),await ks(r)}function Hn(t){let e=/^\*{0,2}(APPROVE|SALVAGE|REJECT)\*{0,2}/,n=t.split(`
|
|
1156
|
+
`).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(`
|
|
1157
|
+
`).trim();return{verdict:o,score:i,feedback:l||r}}var As=Ps(xs);function Ts(){let t=process.env.AFK_EVAL_HARNESS_ROOT;if(t){let o=se(t,"scripts","eval-harness","runner.py");if(Un(o))return o}let e=Es(import.meta.url),n=se(e,"../../../.."),r=se(n,"..","awa-private","scripts","eval-harness","runner.py");if(Un(r))return r;throw new Error(`Could not find eval-harness runner.py. Tried: ${r}`)}function Cs(t){return se(t,"..","..","..","plugins","awa-private")}function Is(){return Le()}function Ms(t){let e=t.split(`
|
|
1158
|
+
`),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 Rs(t){let e=Is(),n=se(e,"qualifications.jsonl");await Nn(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"})+`
|
|
1159
|
+
`;return await Bn(n,i,{flag:"a"}),o}async function _s(){let t;try{t=Ts()}catch(l){throw new Error(`Failed to resolve eval-harness runner.py: ${l instanceof Error?l.message:String(l)}`)}let e=Cs(t),n="",r="",o=0;try{let l=await As("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"?Ms(n):void 0,a;if(s==="OPEN"){let l=new Date().toISOString().split(".")[0]+"Z";a=await Rs(l)}return{gate_status:s,exit_code:o,stdout:n,stderr:r||void 0,tasks_failed:i,ledger_entry_ref:a}}var Ds=z.object({iteration:z.number().int().positive(),verdict:z.enum(["APPROVE","SALVAGE","REJECT"]),score:z.number().optional(),feedback:z.string()}),gd=z.object({status:z.enum(["APPROVED","REJECTED","GATE_CLOSED","MAX_ITERATIONS"]),skill_path:z.string().optional(),qualify_verdicts:z.array(Ds),brief_id:z.string().optional(),telemetry_ref:z.string()});async function Os(t,e,n){let r=n?.apiKey,o=typeof t=="string"?{brief:t}:typeof t=="object"&&t!==null?t:{},s=o.brief,i=o.forceThaw??!1,a=o.maxIterations??3,l="",c=[],d="REJECTED",u,p;try{let f=await _s();if(f.gate_status==="CLOSED"&&!i)return l=await Q({event:"forge.gate_check",gate_status:"CLOSED"}),{status:"GATE_CLOSED",qualify_verdicts:[],telemetry_ref:l};i&&f.gate_status==="CLOSED"&&(await Fn(),l=await Q({event:"forge.thaw_override",gate_status:"CLOSED"})),l=await Q({event:"forge.gate_check",gate_status:"OPEN"});let g="",h=!1;if(s)g=s,h=!0;else{let x=await Ln();if(x.length>0){let _=x[0],j=await jn(_);g=j.content,p=j.id,h=!0}else{if(!e?.sessionId)throw new Error("forge requires parent session for gap discovery");let j=I("forge")["gap-discovery.md"];if(!j)throw new Error("forge skill missing gap-discovery.md prompt");let S=await(await new P({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:j},idPrefix:"forge-gap-discovery"})).runToResult("Identify the most impactful skill gap.");if(S.status!=="succeeded")throw new Error(`gap discovery failed: ${C(S)}`);if(g=S.message?.content||"",!g)throw new Error("gap discovery returned no concept")}}if(l=await Q({event:"forge.brief_loaded",used_brief:h,brief_id:p||null}),!e?.sessionId)throw new Error("forge requires parent session for skill generation");let m=I("forge"),w=m["generate.md"],v=m["system.md"];if(!w)throw new Error("forge skill missing generate.md prompt");if(!v)throw new Error("forge skill missing system.md prompt");let U=await(await new P({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:v},idPrefix:"forge-generate"})).runToResult(`Generate a new amplifier skill based on this concept:
|
|
1159
1160
|
|
|
1160
|
-
${g}`);if(
|
|
1161
|
+
${g}`);if(U.status!=="succeeded")throw new Error(`skill generation failed: ${C(U)}`);let M=U.message?.content||"";if(!M)throw new Error("skill generation returned no output");for(let x=1;x<=a;x++){let _=mt.systemPrompt;if(!_)throw new Error("qualify agent missing system prompt");let k=await(await new P({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:_},idPrefix:`forge-qualify-${x}`})).runToResult(`Evaluate this amplifier skill against the force-multiplier criteria:
|
|
1161
1162
|
|
|
1162
|
-
${
|
|
1163
|
+
${M}`);if(k.status!=="succeeded")throw new Error(`qualify iteration ${x} failed: ${C(k)}`);let S=k.message?.content||"",{verdict:E,score:y,feedback:O}=Hn(S),F={iteration:x,verdict:E,score:y,feedback:O};if(c.push(F),l=await Q({event:"forge.qualify_iteration",iteration:x,verdict:E,score:y||null}),E==="APPROVE"){d="APPROVED";break}else if(E==="SALVAGE"&&x<a){let ee=m["qualify-rework.md"];if(!ee)throw new Error("forge skill missing qualify-rework.md prompt");let Me=ee.replace("{feedback}",O).replace("{original_skill}",M),rt=await(await new P({apiKey:r}).forkSubagent({parent:{sessionId:e.sessionId},config:{model:"sonnet",systemPrompt:Me},idPrefix:`forge-rework-${x}`})).runToResult("Refine the skill based on the feedback.");if(rt.status!=="succeeded")throw new Error(`rework iteration ${x} failed: ${C(rt)}`);if(M=rt.message?.content||"",!M)throw new Error(`rework iteration ${x} returned no output`)}else E==="REJECT"&&x>=a&&(d="MAX_ITERATIONS")}if(d==="APPROVED"){let x=M.match(/^name:\s*([^\n]+)/m),_=x&&x[1]?x[1].trim().replace(/^["']|["']$/g,""):"unknown",j=se(it(),_);await Nn(j,{recursive:!0});let Z=se(j,"SKILL.md");await Bn(Z,M,"utf-8"),u=Z,h&&p&&await gt(p,"consumed"),l=await Q({event:"forge.complete",status:"APPROVED",skill_name:_,iterations:c.length})}else d==="MAX_ITERATIONS"&&(h&&p&&await gt(p,"failed"),l=await Q({event:"forge.complete",status:"MAX_ITERATIONS",iterations:c.length}))}catch(f){throw l=await Q({event:"forge.error",error:f instanceof Error?f.message:String(f)}),f}return{status:d,skill_path:u,qualify_verdicts:c,brief_id:p,telemetry_ref:l}}var Fs={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:Os,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"]};V(Fs);var $s={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"]}},js={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"]}},Ls={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"]}},Hs={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"]}},Us={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"]}},Ns={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"]}},Bs={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"]}},Gn={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"]}},zn={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"]}},ue=[$s,js,Ls,Hs,Us,Ns,Bs],Kn=ue.map(t=>t.name);import{config as Sd}from"dotenv";var qn={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 Vn(t){return t in qn}function Wn(t){let e=qn[t];if(!e)throw new Error(`Invalid model: ${t}`);return e}function Se(t){if(t!==void 0)return typeof t=="string"&&Vn(t)?Wn(t):t}function Yn(){return process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||Ht()}function D(){return Yn()}async function Jn(t,e){let r=I("mint")["spec.md"];if(!r)throw new Error("mint skill missing spec.md prompt");let i=await(await new P().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:D()},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 Qn(t,e){let r=I("mint")["research.md"];if(!r)throw new Error("mint skill missing research.md prompt");let i=await(await new P().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:D()},idPrefix:"mint-research"})).runToResult(`Gather context and research for this specification:
|
|
1163
1164
|
|
|
1164
|
-
${t}`);if(i.status!=="succeeded"||!i.message)throw new Error(`research phase failed: ${C(i)}`);return i.message.content}async function
|
|
1165
|
+
${t}`);if(i.status!=="succeeded"||!i.message)throw new Error(`research phase failed: ${C(i)}`);return i.message.content}async function Xn(t,e,n){let o=I("mint")["plan.md"];if(!o)throw new Error("mint skill missing plan.md prompt");let i=await new P().forkSubagent({parent:{sessionId:n},config:{model:"sonnet",systemPrompt:o,apiKey:D()},idPrefix:"mint-plan"}),a=`Specification:
|
|
1165
1166
|
${t}
|
|
1166
1167
|
|
|
1167
1168
|
Research findings:
|
|
1168
1169
|
${e}
|
|
1169
1170
|
|
|
1170
|
-
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
|
|
1171
|
+
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 Ks(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 Zn(t,e){if(Ks(t)<3)return null;try{return await W("parallelize").handler({plan:t})}catch{}try{let o=er().get("parallelize");if(!o)return null;let s=new P({parentAbortSignal:e.abortSignal,apiKey:D()});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 X}from"zod";function pe(t){let e=de();e&&e({type:"panel",spec:t},{subagentId:"__main__"})}var qs=X.object({status:X.enum(["PASS","FAIL"]),status_reason:X.string().optional(),files_changed:X.array(X.string()),tests_passed:X.boolean(),build_passed:X.boolean().optional(),verification_passed:X.boolean().optional(),notes:X.string()});async function tr(t,e,n){let o=I("mint")["build.md"];if(!o)throw new Error("mint skill missing build.md prompt");let i=await new P().forkSubagent({parent:{sessionId:n},config:{model:"sonnet",systemPrompt:o,apiKey:D()},idPrefix:"mint-build",outputSchema:qs}),a=`Implementation plan:
|
|
1171
1172
|
${t}
|
|
1172
1173
|
|
|
1173
1174
|
`+(e?`Wave orchestration plan:
|
|
1174
1175
|
${JSON.stringify(e,null,2)}
|
|
1175
1176
|
|
|
1176
|
-
`:"")+"Execute the implementation plan following TDD (test-first) principles.",l=await i.runToResult(a);if(l.status!=="succeeded"||!l.output)throw new Error(`build phase failed: ${C(l)}`);let c=l.output,d={filesChanged:c.files_changed,testsPassed:c.tests_passed,notes:c.notes};return
|
|
1177
|
+
`:"")+"Execute the implementation plan following TDD (test-first) principles.",l=await i.runToResult(a);if(l.status!=="succeeded"||!l.output)throw new Error(`build phase failed: ${C(l)}`);let c=l.output,d={filesChanged:c.files_changed,testsPassed:c.tests_passed,notes:c.notes};return pe({kind:"checkpoint",title:"build",body:[`Files changed: ${d.filesChanged.length}`,`Tests: ${d.testsPassed?"passed":"failed"}`,"Next: verify"]}),d}import{z as fe}from"zod";var Vs=fe.object({status:fe.enum(["PASS","FAIL"]),status_reason:fe.string().optional(),issues:fe.array(fe.string()).default([]),summary:fe.string().optional()});async function ht(t,e,n,r,o){let i=await new P().forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:o,apiKey:D()},idPrefix:`mint-verify-${t}`,outputSchema:Vs}),a=`Plan:
|
|
1177
1178
|
${e}
|
|
1178
1179
|
|
|
1179
1180
|
Build results:
|
|
@@ -1181,12 +1182,12 @@ ${JSON.stringify(n,null,2)}
|
|
|
1181
1182
|
|
|
1182
1183
|
Mode: ${t}
|
|
1183
1184
|
|
|
1184
|
-
Run ${t} verification on the implementation.`,l;try{l=await i.runToResult(a)}finally{await i.teardown().catch(()=>{})}if(l.status!=="succeeded"||!l.output)return{passed:!1,issues:[`${t} verification failed: ${C(l)}`]};let c=l.output,d=c.status==="PASS";return{passed:d,issues:d?void 0:c.issues}}async function
|
|
1185
|
+
Run ${t} verification on the implementation.`,l;try{l=await i.runToResult(a)}finally{await i.teardown().catch(()=>{})}if(l.status!=="succeeded"||!l.output)return{passed:!1,issues:[`${t} verification failed: ${C(l)}`]};let c=l.output,d=c.status==="PASS";return{passed:d,issues:d?void 0:c.issues}}async function Ke(t,e,n){let o=I("mint")["verify.md"];if(!o)throw new Error("mint skill missing verify.md prompt");let[s,i,a]=await Promise.all([ht("test",t,e,n,o),ht("lint",t,e,n,o),ht("design-review",t,e,n,o)]),l=[];s.issues&&l.push(...s.issues),i.issues&&l.push(...i.issues),a.issues&&l.push(...a.issues);let c={testsPassed:s.passed,lintPassed:i.passed,designReviewPassed:a.passed,...l.length>0?{issues:l}:{}},d=c.testsPassed&&c.lintPassed&&c.designReviewPassed,u=p=>p?"passed":"failed";return pe({kind:d?"checkpoint":"diagnosis",title:"verify",body:[`Tests: ${u(c.testsPassed)} \xB7 Lint: ${u(c.lintPassed)}`,`Design review: ${u(c.designReviewPassed)}`,...d?["Next: ship"]:[`Issues: ${l.length} (heal loop will retry)`]]}),c}async function nr(t,e,n,r,o){if(n.testsPassed&&n.lintPassed&&n.designReviewPassed)return{healed:!0,newHealIterations:r,newVerifyResults:n};if(r>=2)return{healed:!1,newHealIterations:r,newVerifyResults:n};try{let s=W("diagnose"),i=`Verification failures:
|
|
1185
1186
|
Tests: ${n.testsPassed?"PASS":"FAIL"}
|
|
1186
1187
|
Lint: ${n.lintPassed?"PASS":"FAIL"}
|
|
1187
1188
|
Design: ${n.designReviewPassed?"PASS":"FAIL"}
|
|
1188
1189
|
Issues: ${n.issues?.join(`
|
|
1189
|
-
`)||"none"}`,a=await s.handler({failure:i,repoPath:process.cwd(),context:t}),l="";if(typeof a=="object"&&a!==null&&"winner"in a&&typeof a.winner=="object"&&a.winner!==null){let
|
|
1190
|
+
`)||"none"}`,a=await s.handler({failure:i,repoPath:process.cwd(),context:t}),l="";if(typeof a=="object"&&a!==null&&"winner"in a&&typeof a.winner=="object"&&a.winner!==null){let $=a.winner;typeof $.proposed_fix=="string"&&(l=$.proposed_fix)}let d=I("mint")["heal.md"];if(!d)throw new Error("mint skill missing heal.md prompt");let p=await new P().forkSubagent({parent:{sessionId:o.sessionId},config:{model:"sonnet",systemPrompt:d,apiKey:D()},idPrefix:"mint-heal"}),f=n.issues?.join(`
|
|
1190
1191
|
`)??"none",g=`Plan:
|
|
1191
1192
|
${t}
|
|
1192
1193
|
|
|
@@ -1196,7 +1197,7 @@ ${l}
|
|
|
1196
1197
|
Verification issues:
|
|
1197
1198
|
${f}
|
|
1198
1199
|
|
|
1199
|
-
Apply the fix and update the implementation.`,
|
|
1200
|
+
Apply the fix and update the implementation.`,h=await p.runToResult(g);if(h.status!=="succeeded"||!h.message)throw new Error(`heal phase failed: ${C(h)}`);let m=/^\s*FIX_APPLIED:\s*(true|false)/im.exec(h.message.content)?.[1]?.toLowerCase()==="true",w=r+1;if(!m)return{healed:!1,newHealIterations:w,newVerifyResults:n};if(!o.sessionId)throw new Error("Parent session ID required for verification");let v=await Ke(t,e,o.sessionId);return{healed:v.testsPassed&&v.lintPassed&&v.designReviewPassed,newHealIterations:w,newVerifyResults:v}}catch{return{healed:!1,newHealIterations:r+1,newVerifyResults:n}}}async function rr(t,e){let r=I("mint")["ship.md"];if(!r)throw new Error("mint skill missing ship.md prompt");let s=await new P().forkSubagent({parent:{sessionId:e},config:{model:"sonnet",systemPrompt:r,apiKey:D()},idPrefix:"mint-ship"}),i=`Idea: ${t.idea}
|
|
1200
1201
|
|
|
1201
1202
|
Specification:
|
|
1202
1203
|
${t.spec}
|
|
@@ -1210,23 +1211,23 @@ ${JSON.stringify(t.buildResults,null,2)}
|
|
|
1210
1211
|
Verification results:
|
|
1211
1212
|
${JSON.stringify(t.verifyResults,null,2)}
|
|
1212
1213
|
|
|
1213
|
-
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
|
|
1214
|
+
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 or,mkdirSync as Ws,readFileSync as Ys,unlinkSync as Js,writeFileSync as Qs}from"fs";import{dirname as Xs,join as Zs}from"path";function yt(t){return Zs(cn(),t,"mint-state.json")}function sr(t,e){let n=yt(t);Ws(Xs(n),{recursive:!0}),Qs(n,JSON.stringify(e,null,2),"utf-8")}function ei(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 ir(t){let e=yt(t);if(!or(e))return null;try{let n=JSON.parse(Ys(e,"utf-8"));return ei(n)?n:null}catch{return null}}function bt(t){let e=yt(t);if(or(e))try{Js(e)}catch{}}var ti=2,ar=/^\s*--continue(?:\s+(?:approved|yes|y))?\s*$/i,ni="To approve and run the rest of the pipeline, invoke /mint --continue approved (or call mint with {userApproved: true} \u2014 no idea field needed). The handler will reload the spec state from disk.";function ne(t,e,n){t.history.push({phase:e,output:n,timestamp:Date.now()})}function ri(t){if(typeof t=="string")return ar.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&&ar.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 lr(t,e){if(!e.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let n=e.sessionId;try{t.currentPhase="research",t.research=await Qn(t.spec,n),ne(t,"research",t.research),t.currentPhase="plan",t.plan=await Xn(t.spec,t.research,n),ne(t,"plan",t.plan),t.currentPhase="parallelize",t.waveOrchestrationPlan=await Zn(t.plan,e),ne(t,"parallelize",JSON.stringify(t.waveOrchestrationPlan||"skipped")),t.currentPhase="build",t.buildResults=await tr(t.plan,t.waveOrchestrationPlan,n),ne(t,"build",JSON.stringify(t.buildResults)),t.currentPhase="verify",t.verifyResults=await Ke(t.plan,t.buildResults,n),ne(t,"verify",JSON.stringify(t.verifyResults)),t.currentPhase="heal";let r=t.verifyResults.testsPassed&&t.verifyResults.lintPassed&&t.verifyResults.designReviewPassed;for(;!r&&t.healIterations<ti;){let s=await nr(t.plan,t.buildResults,t.verifyResults,t.healIterations,e);t.healIterations=s.newHealIterations,t.verifyResults=s.newVerifyResults,r=s.healed,ne(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 rr(t,n);return ne(t,"ship",o),{completed:!0,artifact:o,state:t}}catch(r){throw new Error(`mint failed at ${t.currentPhase}: ${r}`)}}function cr(t,e){return("completed"in e||e.phase==="heal-failed")&&bt(t),e}async function oi(t,e){let n=ri(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??ir(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 lr(i,e);return cr(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.");bt(r);let o={currentPhase:"spec",idea:n.idea,healIterations:0,history:[]};try{o.spec=await Jn(n.idea,r),ne(o,"spec",o.spec)}catch(i){throw new Error(`mint failed at spec: ${i}`)}if(!n.autoApprove)return sr(r,o),{paused:!0,phase:"spec",spec:o.spec,state:o,nextStep:ni};let s=await lr(o,e);return cr(r,s)}var si={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:oi,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"]};V(si);import{existsSync as ii,readdirSync as ai,readFileSync as li,statSync as ci}from"fs";import{join as di}from"path";function wt(t){let e=[];function n(r,o=0){if(o>10||!ii(r))return;let s;try{s=ai(r)}catch{return}for(let i of s){if(i.startsWith("."))continue;let a=di(r,i),l;try{l=ci(a)}catch{continue}if(l.isFile()&&i==="SKILL.md"){let c=ui(a);c.name&&e.push(c)}else l.isDirectory()&&n(a,o+1)}}return n(t),e}function ui(t){try{let e=li(t,"utf-8");if(!e.startsWith(`---
|
|
1214
1215
|
`))return{};let n=e.slice(4),r=n.indexOf(`
|
|
1215
1216
|
---`);if(r===-1)return{};let o=n.slice(0,r),s=n.slice(r+4).trim(),i={},a=o.split(`
|
|
1216
|
-
`);for(let l of a){if(!l)continue;let c=l.indexOf(":");if(c===-1)continue;let d=l.slice(0,c).trim(),u=l.slice(c+1).trim();d==="name"?i.name=u.replace(/^["']|["']$/g,""):d==="description"?i.description=u.replace(/^["']|["']$/g,""):d==="argumentHint"&&(i.argumentHint=u.replace(/^["']|["']$/g,""))}return s.length>0&&(i.body=s),i}catch{return{}}}function
|
|
1217
|
-
`)}function mt(t){let e=[],n=new Set;for(let o of Vt()){let s=K(o);e.push({name:o,description:s.description,source:s.origin==="user"?"user":s.origin==="project"?"project":"builtin",argumentHint:s.argumentHint,whenToUse:s.whenToUse}),n.add(o)}let r=t??[...Q(Le()),...Q()];for(let o of r){if(o.type!=="local")continue;let s=er(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}var Js=3,Qs="claude-haiku-4-5-20251001",Xs=1024,Zs=[{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"}],Ke=class{client;authMode;initSessionId;promptStream;toolDispatcher;maxTokens;tools;systemPrefix;userSystem;currentModel;currentPermissionMode;messages=[];closed=!1;abortController=null;pendingAbortReason=null;closedPromise;closeResolve=null;lastUsage=null;constructor(e){this.client=e.client,this.authMode=e.authMode,this.initSessionId=gt(),this.promptStream=e.promptStream,this.toolDispatcher=e.toolDispatcher,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.userSystem=e.userSystem,this.currentModel=e.model,this.currentPermissionMode=e.permissionMode??"default",this.closedPromise=new Promise(n=>{this.closeResolve=()=>n("__closed__")})}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:[],apiKeySource:this.authMode,version:"anthropic-direct-v1"}};let n=this.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let r=await Promise.race([n.next(),this.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=new AbortController;if(this.abortController=i,this.pendingAbortReason!==null&&!i.signal.aborted&&(i.abort(this.pendingAbortReason),this.pendingAbortReason=null),i.signal.aborted)return;this.messages.push({role:"user",content:s.content});let a=this.composeSystem(),l=nt(this.authMode,this.initSessionId,gt()),c={client:this.client,messages:this.messages,system:a,tools:this.tools,toolDispatcher:this.toolDispatcher,model:this.currentModel,maxTokens:this.maxTokens,headers:l,signal:i.signal,ctx:{sessionId:this.initSessionId}};try{for await(let d of jt(c)){if(this.closed)return;d.type==="turn.completed"&&(this.lastUsage=d.usage),yield d}}catch(d){if(i.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}finally{this.abortController===i&&(this.abortController=null)}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}composeSystem(){let e=this.systemPrefix,n=this.userSystem,r=[];return e&&e.length>0&&r.push(...e),n&&n.length>0&&r.push({type:"text",text:n}),r.length===0?null:De()?Rt(r,Oe()):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 mt().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return Zs.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=ei(),r=Ut(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=ti(),i=Nt(o,s,Xs),a=new AbortController;this.abortController=a,this.pendingAbortReason!==null&&!a.signal.aborted&&(a.abort(this.pendingAbortReason),this.pendingAbortReason=null);let l;try{if(a.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e};let u=nt(this.authMode,this.initSessionId,gt()),p=this.client,f=await Promise.resolve(p.messages.create(i,{headers:u,signal:a.signal}));l=await ni(f)}catch(u){return a.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e}:{compacted:!1,reason:"summarization-failed: "+(u instanceof Error?u.message:String(u)),messagesBefore:e,messagesAfter:e}}finally{this.abortController===a&&(this.abortController=null)}if(l.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:e,messagesAfter:e};let c=Gt(this.messages,r,l),d=Bt(this.messages,r,l);return this.messages.splice(0,this.messages.length,...d),{compacted:!0,messagesBefore:e,messagesAfter:this.messages.length,tokensSavedEstimate:c}}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.()}};function ei(){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 Js}function ti(){let t=process.env.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?t:Qs}async function ni(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 Te(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 ri=new Set(["agent","read_file","glob","grep","list_directory"]);function nr(t){return ri.has(t)}function oi(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 le=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??nr}get toolDefs(){return this.schemas}async execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0};if(this.hookRegistry){let s={event:"PreToolUse",toolName:e.name,input:e.input};try{await this.hookRegistry.dispatch(s,e.signal)}catch(i){if(i instanceof U)return{content:`Tool "${e.name}" blocked by PreToolUse hook: ${i.message}`,isError:!0};throw i}}let n=Te(e.name,this.permissions);if(!n.allowed)return{content:n.reason??`Tool "${e.name}" is not permitted`,isError:!0};if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s;try{s=await this.subagentExecutor.execute(e)}catch(i){s={content:`Agent tool error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}if(this.hookRegistry){let i={event:"PostToolUse",toolName:e.name,output:s.content};try{await this.hookRegistry.dispatch(i,e.signal)}catch{}}return s}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s;try{s=await this.skillExecutor.execute(e)}catch(i){s={content:`Skill tool error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}if(this.hookRegistry){let i={event:"PostToolUse",toolName:e.name,output:s.content};try{await this.hookRegistry.dispatch(i,e.signal)}catch{}}return s}let r=this.handlers.get(e.name);if(!r)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let o;try{o=await r(e.input,e.signal)}catch(s){o={content:`Tool execution error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}if(this.hookRegistry){let s={event:"PostToolUse",toolName:e.name,output:o.content};try{await this.hookRegistry.dispatch(s,e.signal)}catch{}}return o}async executeBatch(e){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let n=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){let a=e[i];if(a.signal.aborted){n[i]={content:"Tool call aborted",isError:!0},r.add(i);continue}if(this.hookRegistry){let c={event:"PreToolUse",toolName:a.name,input:a.input};try{await this.hookRegistry.dispatch(c,a.signal)}catch(d){if(d instanceof U){n[i]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${d.message}`,isError:!0},r.add(i);continue}throw d}}let l=Te(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=oi(o.map(i=>i.call),this.classifier);for(let i of s){if(e[0].signal.aborted){for(let a of i.indices){let l=o[a].originalIndex;n[l]={content:"Tool call aborted",isError:!0}}continue}if(i.isConcurrencySafe){let a=await Promise.allSettled(i.indices.map(async l=>{let{call:c,originalIndex:d}=o[l];return{result:await this.executeCore(c),originalIndex:d}}));for(let l of a)if(l.status==="fulfilled")n[l.value.originalIndex]=l.value.result;else{let c=l.reason instanceof Error?l.reason.message:String(l.reason),d=i.indices[a.indexOf(l)];n[o[d].originalIndex]={content:`Tool execution error: ${c}`,isError:!0}}}else for(let a of i.indices){let{call:l,originalIndex:c}=o[a];if(l.signal.aborted){n[c]={content:"Tool call aborted",isError:!0};continue}n[c]=await this.executeCore(l)}}return n}async executeCore(e){if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let o;try{o=await this.subagentExecutor.execute(e)}catch(s){o={content:`Agent tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let o;try{o=await this.skillExecutor.execute(e)}catch(s){o={content:`Skill tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}let n=this.handlers.get(e.name);if(!n)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r;try{r=await n(e.input,e.signal)}catch(o){r={content:`Tool execution error: ${o instanceof Error?o.message:String(o)}`,isError:!0}}return this.firePostToolUse(e.name,r.content,e.signal),r}firePostToolUse(e,n,r){if(!this.hookRegistry)return;let o={event:"PostToolUse",toolName:e,output:n};this.hookRegistry.dispatch(o,r).catch(()=>{})}};import{spawn as si}from"child_process";function ii(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 ai(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var rr=async(t,e)=>{let{command:n,timeout_ms:r}=ii(t);return e.aborted?{content:"Command aborted",isError:!0}:new Promise(o=>{let s=!1;function i(p){s||(s=!0,clearTimeout(l),e.removeEventListener("abort",u),o(p))}let a=si(n,{shell:!0,stdio:["ignore","pipe","pipe"]}),l=setTimeout(()=>{a.kill(),i({content:`Command timed out after ${r}ms`,isError:!0})},r),c="",d="";a.stdout.on("data",p=>{c+=p.toString()}),a.stderr.on("data",p=>{d+=p.toString()});let u=()=>{a.kill(),i({content:"Command aborted",isError:!0})};e.addEventListener("abort",u),a.on("close",()=>{let p=(c+d).trimEnd();p=ai(p);let f=1e5;p.length>f&&(p=p.slice(0,f)+`
|
|
1218
|
-
[output truncated \u2014 exceeded 100KB]`),i({content:p})}),a.on("error",p=>{i({content:`Failed to execute: ${p.message}`,isError:!0})})})};import{promises as
|
|
1219
|
-
`),d=Math.max(0,o-1),u=Math.min(c.length,d+s),p=c.slice(d,u),f=c.length;if(p.length===0)return{content:`... (offset ${o} is past end of file \u2014 file has ${f} lines)`};let g=String(f).length,
|
|
1220
|
-
`);if(p.length<f){let m=d+1,
|
|
1221
|
-
... (showing lines ${m}-${
|
|
1217
|
+
`);for(let l of a){if(!l)continue;let c=l.indexOf(":");if(c===-1)continue;let d=l.slice(0,c).trim(),u=l.slice(c+1).trim();d==="name"?i.name=u.replace(/^["']|["']$/g,""):d==="description"?i.description=u.replace(/^["']|["']$/g,""):d==="argumentHint"&&(i.argumentHint=u.replace(/^["']|["']$/g,""))}return s.length>0&&(i.body=s),i}catch{return{}}}function dr(t){let e=vt(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(`
|
|
1218
|
+
`)}function vt(t){let e=[],n=new Set;for(let o of on()){let s=W(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??[...B(ve()),...B(),...B(at())];for(let o of r){if(o.type!=="local")continue;let s=wt(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 er(t){let e=new Map,n=t??[...B(ve()),...B(),...B(at())];for(let r of n){if(r.type!=="local")continue;let o=wt(r.path);for(let s of o)s.name&&s.body&&s.body.length>0&&e.set(s.name,s.body)}return e}var pi=3,fi="claude-haiku-4-5-20251001",mi=1024,gi=[{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"}],Ve=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=qe(),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,qe()),c={client:this.client,messages:this.messages,system:a,tools:this.tools,toolDispatcher:this.toolDispatcher,model:this.currentModel,maxTokens:this.maxTokens,headers:l,signal:i.signal,ctx:{sessionId:this.initSessionId}};try{for await(let d of this.turnWithAuthRetry(c)){if(this.closed)return;d.type==="turn.completed"&&(this.lastUsage=d.usage),yield d}}catch(d){if(i.signal.aborted)return;yield{type:"error",error:d instanceof Error?d:new Error(String(d))};return}finally{this.abortController===i&&(this.abortController=null)}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}async*turnWithAuthRetry(e){let n=null;for await(let o of st(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,qe()),yield*st(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()?Gt(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 vt().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return gi.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=hi(),r=Qt(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=Xt(o,s,mi),a=new AbortController;this.abortController=a,this.pendingAbortReason!==null&&!a.signal.aborted&&(a.abort(this.pendingAbortReason),this.pendingAbortReason=null);let l;try{if(a.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e};let u=De(this.authMode,this.initSessionId,qe()),p=this.client,f=await Promise.resolve(p.messages.create(i,{headers:u,signal:a.signal}));l=await bi(f)}catch(u){return a.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:e,messagesAfter:e}:{compacted:!1,reason:"summarization-failed: "+(u instanceof Error?u.message:String(u)),messagesBefore:e,messagesAfter:e}}finally{this.abortController===a&&(this.abortController=null)}if(l.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:e,messagesAfter:e};let c=en(this.messages,r,l),d=Zt(this.messages,r,l);return this.messages.splice(0,this.messages.length,...d),{compacted:!0,messagesBefore:e,messagesAfter:this.messages.length,tokensSavedEstimate:c}}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.()}};function hi(){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 pi}function yi(){let t=process.env.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?t:fi}async function bi(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 Ee(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 wi=new Set(["agent","read_file","glob","grep","list_directory"]);function ur(t){return wi.has(t)}function vi(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 ie=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??ur}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 G)return{content:`Tool "${e.name}" blocked by PreToolUse hook: ${i.message}`,isError:!0};throw i}}let n=Ee(e.name,this.permissions);if(!n.allowed)return{content:n.reason??`Tool "${e.name}" is not permitted`,isError:!0};if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s;try{s=await this.subagentExecutor.execute(e)}catch(i){s={content:`Agent tool error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}if(this.hookRegistry){let i={event:"PostToolUse",toolName:e.name,output:s.content};try{await this.hookRegistry.dispatch(i,e.signal)}catch{}}return s}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s;try{s=await this.skillExecutor.execute(e)}catch(i){s={content:`Skill tool error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}if(this.hookRegistry){let i={event:"PostToolUse",toolName:e.name,output:s.content};try{await this.hookRegistry.dispatch(i,e.signal)}catch{}}return s}let r=this.handlers.get(e.name);if(!r)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let o;try{o=await r(e.input,e.signal)}catch(s){o={content:`Tool execution error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}if(this.hookRegistry){let s={event:"PostToolUse",toolName:e.name,output:o.content};try{await this.hookRegistry.dispatch(s,e.signal)}catch{}}return o}async executeBatch(e){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let n=new Array(e.length),r=new Set;for(let i=0;i<e.length;i++){let a=e[i];if(a.signal.aborted){n[i]={content:"Tool call aborted",isError:!0},r.add(i);continue}if(this.hookRegistry){let c={event:"PreToolUse",toolName:a.name,input:a.input};try{await this.hookRegistry.dispatch(c,a.signal)}catch(d){if(d instanceof G){n[i]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${d.message}`,isError:!0},r.add(i);continue}throw d}}let l=Ee(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=vi(o.map(i=>i.call),this.classifier);for(let i of s){if(e[0].signal.aborted){for(let a of i.indices){let l=o[a].originalIndex;n[l]={content:"Tool call aborted",isError:!0}}continue}if(i.isConcurrencySafe){let a=await Promise.allSettled(i.indices.map(async l=>{let{call:c,originalIndex:d}=o[l];return{result:await this.executeCore(c),originalIndex:d}}));for(let l of a)if(l.status==="fulfilled")n[l.value.originalIndex]=l.value.result;else{let c=l.reason instanceof Error?l.reason.message:String(l.reason),d=i.indices[a.indexOf(l)];n[o[d].originalIndex]={content:`Tool execution error: ${c}`,isError:!0}}}else for(let a of i.indices){let{call:l,originalIndex:c}=o[a];if(l.signal.aborted){n[c]={content:"Tool call aborted",isError:!0};continue}n[c]=await this.executeCore(l)}}return n}async executeCore(e){if(e.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let o;try{o=await this.subagentExecutor.execute(e)}catch(s){o={content:`Agent tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let o;try{o=await this.skillExecutor.execute(e)}catch(s){o={content:`Skill tool error: ${s instanceof Error?s.message:String(s)}`,isError:!0}}return this.firePostToolUse(e.name,o.content,e.signal),o}let n=this.handlers.get(e.name);if(!n)return{content:`Unknown tool "${e.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r;try{r=await n(e.input,e.signal)}catch(o){r={content:`Tool execution error: ${o instanceof Error?o.message:String(o)}`,isError:!0}}return this.firePostToolUse(e.name,r.content,e.signal),r}firePostToolUse(e,n,r){if(!this.hookRegistry)return;let o={event:"PostToolUse",toolName:e,output:n};this.hookRegistry.dispatch(o,r).catch(()=>{})}};import{spawn as ki}from"child_process";function Si(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 xi(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var pr=async(t,e)=>{let{command:n,timeout_ms:r}=Si(t);return e.aborted?{content:"Command aborted",isError:!0}:new Promise(o=>{let s=!1;function i(p){s||(s=!0,clearTimeout(l),e.removeEventListener("abort",u),o(p))}let a=ki(n,{shell:!0,stdio:["ignore","pipe","pipe"]}),l=setTimeout(()=>{a.kill(),i({content:`Command timed out after ${r}ms`,isError:!0})},r),c="",d="";a.stdout.on("data",p=>{c+=p.toString()}),a.stderr.on("data",p=>{d+=p.toString()});let u=()=>{a.kill(),i({content:"Command aborted",isError:!0})};e.addEventListener("abort",u),a.on("close",()=>{let p=(c+d).trimEnd();p=xi(p);let f=1e5;p.length>f&&(p=p.slice(0,f)+`
|
|
1219
|
+
[output truncated \u2014 exceeded 100KB]`),i({content:p})}),a.on("error",p=>{i({content:`Failed to execute: ${p.message}`,isError:!0})})})};import{promises as Pi}from"fs";var fr=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 Pi.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(`
|
|
1220
|
+
`),d=Math.max(0,o-1),u=Math.min(c.length,d+s),p=c.slice(d,u),f=c.length;if(p.length===0)return{content:`... (offset ${o} is past end of file \u2014 file has ${f} lines)`};let g=String(f).length,h=p.map((m,w)=>{let v=d+w+1;return`${String(v).padStart(g," ")} ${m}`}).join(`
|
|
1221
|
+
`);if(p.length<f){let m=d+1,w=d+p.length,v=w<f?` \u2014 pass offset=${w+1} to continue`:"";return{content:`${h}
|
|
1222
|
+
... (showing lines ${m}-${w} of ${f}${v})`}}return{content:h}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`File not found: ${r}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${r}`,isError:!0}:{content:`Error reading file: ${i.message}`,isError:!0}}return{content:"Unknown error reading file",isError:!0}}};import{writeFile as Ei}from"fs/promises";import{mkdir as Ai}from"fs/promises";import{dirname as Ti}from"path";function Ci(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 mr=async(t,e)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:n,content:r}=Ci(t);try{let o=Ti(n);return await Ai(o,{recursive:!0}),await Ei(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 Ii,writeFile as Mi}from"fs/promises";function Ri(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 _i(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 Di(t,e,n){let r=t.split(`
|
|
1222
1223
|
`),o=0,s=0;for(let c=0;c<r.length;c++){let d=r[c]?.length??0,u=o+d+1;if(o+d>=n+e.length){s=c;break}o=u}let i=Math.max(0,s-2),a=Math.min(r.length,s+3);return`...${r.slice(i,a).join(`
|
|
1223
|
-
`)}...`}var
|
|
1224
|
+
`)}...`}var gr=async(t,e)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:n,old_string:r,new_string:o,replace_all:s}=Ri(t);try{let i=await Ii(n,"utf-8"),a=_i(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 Mi(n,l,"utf-8");let d=Di(i,r,c);return{content:`${a===1?`Replaced 1 occurrence in ${n}`:`Replaced ${a} occurrences in ${n}`}
|
|
1224
1225
|
|
|
1225
|
-
${d}`}}catch(i){return{content:`Error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}};import{promises as
|
|
1226
|
+
${d}`}}catch(i){return{content:`Error: ${i instanceof Error?i.message:String(i)}`,isError:!0}}};import{promises as yr}from"fs";import Oi from"path";function Fi(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=hr(l);if(a===0){let d=n.match(new RegExp(`^${c}`));if(!d)return!1;i=d[0].length}else if(a===s.length-1){let d=new RegExp(`${c}$`);if(!n.slice(i).match(d))return!1}else{let d=new RegExp(c),u=n.slice(i).match(d);if(!u)return!1;let p=u.index??0;i+=p+u[0].length}}return!0}return new RegExp(`^${hr(r)}$`).test(n)}function hr(t){return t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]")}async function $i(t,e){let n=[];async function o(s,i){if(n.length>=500)return!0;try{let a=await yr.readdir(s,{withFileTypes:!0});for(let l of a){if(n.length>=500)return!0;let c=Oi.join(s,l.name),d=i?`${i}/${l.name}`:l.name;if(Fi(d,e)&&n.push(d),l.isDirectory()&&await o(c,d))return!0}}catch{}return!1}return await o(t,""),n}var br=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 yr.stat(o)).isDirectory())return{content:`Invalid input: path is not a directory: ${o}`,isError:!0};let i=await $i(o,r);if(i.length===0)return{content:`No files matched pattern '${r}' in ${o}`};let a=i.join(`
|
|
1226
1227
|
`);return i.length>=500&&(a+=`
|
|
1227
|
-
[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
|
|
1228
|
-
[output truncated]`),a({content:g})}),c.on("error",f=>{a({content:`Failed to execute grep: ${f.message}`,isError:!0})})})};import{promises as
|
|
1229
|
-
`)}}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
|
|
1228
|
+
[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 ji}from"child_process";function Li(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 Hi(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var wr=async(t,e)=>{let{pattern:n,path:r,include:o}=Li(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=ji("grep",l),d="",u="";c.stdout.on("data",f=>{d+=f.toString()}),c.stderr.on("data",f=>{u+=f.toString()});let p=()=>{c.kill(),a({content:"Search aborted",isError:!0})};e.addEventListener("abort",p),c.on("close",f=>{if(f===1){a({content:`No matches found for '${n}' in ${r}`});return}if(f===2){a({content:`grep error: ${u.trim()}`,isError:!0});return}let g=d.trimEnd();g=Hi(g);let h=1e5;g.length>h&&(g=g.slice(0,h)+`
|
|
1229
|
+
[output truncated]`),a({content:g})}),c.on("error",f=>{a({content:`Failed to execute grep: ${f.message}`,isError:!0})})})};import{promises as Ui}from"fs";var vr=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 Ui.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(`
|
|
1230
|
+
`)}}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 We(){return new Map([["bash",pr],["read_file",fr],["write_file",mr],["edit_file",gr],["glob",br],["grep",wr],["list_directory",vr]])}var kr=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1230
1231
|
|
|
1231
1232
|
- Use read_file before editing to verify the exact content you want to change.
|
|
1232
1233
|
- Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
|
|
@@ -1236,30 +1237,30 @@ ${d}`}}catch(i){return{content:`Error: ${i instanceof Error?i.message:String(i)}
|
|
|
1236
1237
|
- When bash output is very long, it may be truncated. If you need the full output, redirect to a file and read it.
|
|
1237
1238
|
- Use absolute paths for file operations.
|
|
1238
1239
|
|
|
1239
|
-
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
|
|
1240
|
-
- Working directory: ${
|
|
1240
|
+
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 Ni={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},Bi=64e3;function Sr(t){return Ni[t]??Bi}var Pr="anthropic-direct",Gi="claude-sonnet-4-5-20250929",Er=null;var Pe=class{name=Pr;tools;providerFactory;skillExecutor;constructor(e={}){let n=[...ue];e.subagentExecutor&&n.push(Gn),e.skillExecutor&&n.push(zn),this.tools=e.tools??new ie({handlers:We(),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(`${Pr} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let o=Dt(r),s=ot(r,o),i=this.providerFactory??Er,a=i?i(s):new xr(s),l=Ot(o),c=zi(n.systemPrompt),d=typeof n.model=="string"&&n.model.length>0?Se(n.model)??n.model:Gi,u=Ki(n,d),p=this.tools instanceof ie?[...this.tools.toolDefs]:[...ue],f=[...B(ve()),...B()],g=n.plugins??[],h=[...f,...g],m=this.skillExecutor?dr(h):"",w=n.cwd||process.cwd(),v=[kr];v.push(`# Environment
|
|
1241
|
+
- Working directory: ${w}`),m.length>0&&v.push(m),c&&v.push(c);let $=v.join(`
|
|
1241
1242
|
|
|
1242
|
-
`);return new
|
|
1243
|
+
`),K;if(o==="oauth"){let U=this.providerFactory??Er;K=async()=>{let M=await Ut();if(!M)return null;let x=ot(M,"oauth");return U?U(x):new xr(x)}}return new Ve({client:a,authMode:o,promptStream:e.prompt,toolDispatcher:this.tools,model:d,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:u,tools:p,userSystem:$,systemPrefix:l,tokenRefresher:K})}};function zi(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 Ki(t,e){let n=t.maxOutputTokens;return typeof n=="number"&&Number.isFinite(n)&&n>0?Math.floor(n):Sr(e)}var Ar=new Pe;import{Codex as Cr}from"@openai/codex-sdk";import{mkdtempSync as qi,rmSync as Vi,writeFileSync as Wi}from"node:fs";import{tmpdir as Yi}from"node:os";import{join as Tr}from"node:path";var Ae="openai-codex",Ji=[{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 Qi(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(Ae,e.join(", "),`${Ae} provider does not support AgentConfig fields: ${e.join(", ")}`)}function Ir(t){return t==="plan"?{sandboxMode:"read-only",approvalPolicy:"untrusted"}:{sandboxMode:"workspace-write",approvalPolicy:"never"}}function Xi(t){if(t)switch(t){case"minimal":case"low":case"medium":case"high":case"xhigh":return t;case"max":return"xhigh";default:return}}function Zi(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 ea(t){let e=qi(Tr(Yi(),"afk-codex-instr-")),n=Tr(e,"instructions.md");return Wi(n,t,"utf-8"),{path:n,dispose:()=>{try{Vi(e,{recursive:!0,force:!0})}catch{}}}}function ta(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*na(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*ra(t.item,t.type==="item.completed",e,n,r))}}function*ra(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}
|
|
1243
1244
|
`+(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(`
|
|
1244
|
-
`);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
|
|
1245
|
-
`);d=await this.thread.runStreamed(u,{signal:c.signal})}catch(u){if(c.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}try{for await(let u of d.events){if(this.closed)return;u.type==="thread.started"&&(o=u.thread_id),yield*
|
|
1246
|
-
`);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 Yi(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 Ji(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 Qi(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 Xi(t,e){let n=qi(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}=Wi(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 Zi(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 kr(t){try{for await(let e of t.providerStream)switch(e.type){case"session.init":Ji(t,e);break;case"session.status":Qi(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),Zi(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":Xi(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=Yi(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 Sr(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 xr(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 Pr(t){try{await vr(t.hookRegistry,{event:"SessionStart",sessionId:t.sessionId()},{signal:t.abortSignal}),await kr({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 Je=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 Er(t,e){return await new Promise((n,r)=>{let o=null,s="",i=!1,a=c=>{i||(i=!0,clearTimeout(l),c())},l=Number.isFinite(e)&&e>0?setTimeout(()=>{a(()=>r(new Error("Response timeout")))},e):void 0;(async()=>{try{for await(let c of t){if(process.env.AFK_CODEX_DEBUG&&console.log("[wait] got event:",c.type),c.type==="error"){a(()=>r(c.error));return}if(c.type==="chunk"&&c.chunk.type==="content"&&(s+=c.chunk.content),c.type==="message"&&c.message.role==="assistant"&&(o=c.message),c.type==="done"){if(process.env.AFK_CODEX_DEBUG&&console.log("[wait] settling with done; assistantMessage=",!!o,"streamedContent=",s.length),o){let d=o;a(()=>n({...d,metadata:c.metadata}));return}if(s){a(()=>n({role:"assistant",content:s,metadata:c.metadata,timestamp:new Date}));return}}}a(o?()=>n(o):s?()=>n({role:"assistant",content:s,timestamp:new Date}):()=>r(new Error("No assistant response received")))}catch(c){a(()=>r(c instanceof Error?c:new Error(String(c))))}})()})}var oe=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,Sr(e.abortSignal,this.abortController,()=>{this.onAbort()}),this.initSdkLifecycle()}initSdkLifecycle(){this.messageQueue=new ce;let e=Pe(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=xr(this.config,e);this.stateManager=new Je(n,r),this.inputStream=new Ye(()=>this.sessionId);let o=this.config.provider??We(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=Pr({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??ve;try{this.inputStream.pushUserMessage(e);let s=await we(Er(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 B("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,$e))]).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=Pe(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,$e))])}catch{}this.messageQueue.complete(),await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await wr(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 B("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`)}};function ea(t){let e=new Map,n=t.defaultMode??"ask";if(t.tools)for(let[r,o]of Object.entries(t.tools))typeof o=="string"?e.set(r,{mode:o}):e.set(r,{mode:o.mode,reason:o.reason});if(t.list)for(let r of t.list)e.set(r.tool,{mode:r.mode,reason:r.reason});return{defaultMode:n,byTool:e}}function ta(t){return t.behavior==="allow"?{behavior:"allow"}:{behavior:"deny",message:t.reason??"Tool denied by permission rules"}}function Ar(t){let{defaultMode:e,byTool:n}=ea(t.rules);return async(r,o)=>{let s={toolName:r,input:o},i=n.get(r),a=i?.mode??e,l=i?.reason,c;return a==="ask"&&t.onAsk?c=await t.onAsk(s):a==="deny"?c={behavior:"deny",reason:l}:c={behavior:"allow"},t.onDecision?.(s,c),ta(c)}}import{Telegraf as aa}from"telegraf";import{promises as Ie}from"fs";import{join as Tr}from"path";var he=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 Ie.mkdir(this.options.dataDir,{recursive:!0});let e=await Ie.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=Tr(this.options.dataDir,n),o=await Ie.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 Ie.mkdir(this.options.dataDir,{recursive:!0});for(let[e,n]of this.sessionData.entries()){let r=Tr(this.options.dataDir,`${e}.json`);await Ie.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 Me(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(`
|
|
1247
|
-
`,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
|
|
1245
|
+
`);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 kt=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 Cr(e.codexOptions),this.thread=e.resumeId?this.codex.resumeThread(e.resumeId,e.threadOptions):this.codex.startThread(e.threadOptions),this.currentModel=e.threadOptions.model,this.currentSandbox=e.threadOptions.sandboxMode??"workspace-write",this.currentApproval=e.threadOptions.approvalPolicy??"never",e.instructionsDispose!==void 0&&(this.dispose=e.instructionsDispose),this.closedPromise=new Promise(o=>{this.closeResolve=()=>o("__closed__")})}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,...this.currentModel!==void 0?{model:this.currentModel}:{},permissionMode:this.sandboxToPermissionMode(),cwd:this.startOpts.threadOptions.workingDirectory??process.cwd(),tools:["Bash","Read","Write","Edit"],slashCommands:[],skills:[],plugins:[],mcpServers:[],apiKeySource:this.startOpts.codexOptions.apiKey!==void 0?"apiKey":"codex-cli",version:"codex-sdk"}};let n=new Map,r=new Map,o=this.initSessionId,s=this.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let i=await Promise.race([s.next(),this.closedPromise]);if(i==="__closed__")break;let a=i;if(a.done)break;let l=a.value,c=new AbortController;if(this.abortController=c,this.pendingAbortReason!==null&&!c.signal.aborted&&(c.abort(this.pendingAbortReason),this.pendingAbortReason=null),c.signal.aborted)return;let d;try{let u=typeof l.content=="string"?l.content:l.content.map(p=>{if(typeof p=="object"&&p&&"type"in p){if(p.type==="text")return p.text;if(p.type==="image")return"[image omitted]"}return""}).join(`
|
|
1246
|
+
`);d=await this.thread.runStreamed(u,{signal:c.signal})}catch(u){if(c.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}try{for await(let u of d.events){if(this.closed)return;u.type==="thread.started"&&(o=u.thread_id),yield*na(u,o,n,r)}}catch(u){if(c.signal.aborted)return;yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}finally{this.abortController===c&&(this.abortController=null)}}}catch(i){yield{type:"error",error:i instanceof Error?i:new Error(String(i))}}finally{try{await s.return?.()}catch{}}}sandboxToPermissionMode(){return this.currentSandbox==="read-only"||this.currentApproval==="untrusted"?"plan":"bypassPermissions"}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){this.currentModel=e;let n={...this.startOpts.threadOptions,...e!==void 0?{model:e}:{},sandboxMode:this.currentSandbox,approvalPolicy:this.currentApproval},r=this.thread.id;this.thread=r?this.codex.resumeThread(r,n):this.codex.startThread(n),this.startOpts.threadOptions=n}async setPermissionMode(e){let{sandboxMode:n,approvalPolicy:r}=Ir(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 Ji.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(Ae,"rewindFiles",`${Ae} 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}},oa=null;var me=class{name=Ae;query(e){Qi(e.config);let n=ta(e.config),r=Xi(e.config.effort),{sandboxMode:o,approvalPolicy:s}=Ir(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=Zi(e.config),l={};n!==void 0&&(l.apiKey=n);let c;if(a!==void 0){let{path:g,dispose:h}=ea(a);l.config={...l.config??{},model_instructions_file:g},c=h}A(`\u{1F7E2} OpenAICodexProvider: creating Codex thread (model=${String(e.config.model)}, sandbox=${o}, approval=${s})`);let d=oa,u=d??(g=>new Cr(g)),p=`codex-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,f=new kt({threadOptions:i,codexOptions:l,...e.config.resume!==void 0?{resumeId:e.config.resume}:{},...c!==void 0?{instructionsDispose:c}:{}},e.prompt,p);if(d){let g=u(l);f.codex=g,f.thread=e.config.resume?g.resumeThread(e.config.resume,i):g.startThread(i)}return f}},Ye=new me;var sa=new Set(["opus","opus_1m","sonnet","sonnet_1m","haiku","auto"]);function xe(t){if(!t)return"anthropic-direct";let e=t.trim().toLowerCase();return!e||sa.has(e)||e.startsWith("claude-")||e.startsWith("claude_")?"anthropic-direct":e.startsWith("gpt-")||e.startsWith("gpt_")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")||e.startsWith("codex-")||e.startsWith("codex_")||e==="codex"?"openai-codex":"anthropic-direct"}function Je(t){return xe(t)==="openai-codex"?Ye:Ar}async function Mr(t,e,n={}){t&&await t.dispatch(e,n.signal)}async function Rr(t,e,n={}){if(t)try{await t.dispatch(e,n.signal)}catch(r){if(r instanceof G||r instanceof q){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 Qe=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 ia(t){let e=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=t.match(e);if(!n||!n[1]||!n[2]||!n[3])return null;let r=n[1],o=n[2],s=n[3],i=parseFloat(r),a=i;o==="KB"?a=i*1024:o==="MB"?a=i*1024*1024:o==="GB"&&(a=i*1024*1024*1024);let l=r;return i%1===0&&(l=String(Math.floor(i))),l+=o,{sizeLabel:l,sizeBytes:Math.round(a),absolutePath:s.trim()}}function aa(t){if(t<1024)return`${t}B`;let e=t/1024;if(e<1024)return e%1===0?`${Math.floor(e)}KB`:`${e.toFixed(1)}KB`;let n=e/1024;if(n<1024)return n%1===0?`${Math.floor(n)}MB`:`${n.toFixed(1)}MB`;let r=n/1024;return r%1===0?`${Math.floor(r)}GB`:`${r.toFixed(1)}GB`}function la(t){let e=Buffer.byteLength(t,"utf8"),n=aa(e),r=t.split(`
|
|
1247
|
+
`);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 ca(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 da(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 ua(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 pa(t,e){let n=ia(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}=la(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 fa(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 _r(t){try{for await(let e of t.providerStream)switch(e.type){case"session.init":da(t,e);break;case"session.status":ua(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),fa(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":pa(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=ca(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 Dr(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 Or(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 Fr(t){try{await Mr(t.hookRegistry,{event:"SessionStart",sessionId:t.sessionId()},{signal:t.abortSignal}),await _r({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 Xe=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 $r(t,e){return await new Promise((n,r)=>{let o=null,s="",i=!1,a=c=>{i||(i=!0,clearTimeout(l),c())},l=Number.isFinite(e)&&e>0?setTimeout(()=>{a(()=>r(new Error("Response timeout")))},e):void 0;(async()=>{try{for await(let c of t){if(process.env.AFK_CODEX_DEBUG&&console.log("[wait] got event:",c.type),c.type==="error"){a(()=>r(c.error));return}if(c.type==="chunk"&&c.chunk.type==="content"&&(s+=c.chunk.content),c.type==="message"&&c.message.role==="assistant"&&(o=c.message),c.type==="done"){if(process.env.AFK_CODEX_DEBUG&&console.log("[wait] settling with done; assistantMessage=",!!o,"streamedContent=",s.length),o){let d=o;a(()=>n({...d,metadata:c.metadata}));return}if(s){a(()=>n({role:"assistant",content:s,metadata:c.metadata,timestamp:new Date}));return}}}a(o?()=>n(o):s?()=>n({role:"assistant",content:s,timestamp:new Date}):()=>r(new Error("No assistant response received")))}catch(c){a(()=>r(c instanceof Error?c:new Error(String(c))))}})()})}var oe=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,Dr(e.abortSignal,this.abortController,()=>{this.onAbort()}),this.initSdkLifecycle()}initSdkLifecycle(){this.messageQueue=new ae;let e=Se(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=Or(this.config,e);this.stateManager=new Xe(n,r),this.inputStream=new Qe(()=>this.sessionId);let o=this.config.provider??Je(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=Fr({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??be;try{this.inputStream.pushUserMessage(e);let s=await we($r(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 q("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,je))]).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=Se(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,je))])}catch{}this.messageQueue.complete(),await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await Rr(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 q("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`)}};function ma(t){let e=new Map,n=t.defaultMode??"ask";if(t.tools)for(let[r,o]of Object.entries(t.tools))typeof o=="string"?e.set(r,{mode:o}):e.set(r,{mode:o.mode,reason:o.reason});if(t.list)for(let r of t.list)e.set(r.tool,{mode:r.mode,reason:r.reason});return{defaultMode:n,byTool:e}}function ga(t){return t.behavior==="allow"?{behavior:"allow"}:{behavior:"deny",message:t.reason??"Tool denied by permission rules"}}function jr(t){let{defaultMode:e,byTool:n}=ma(t.rules);return async(r,o)=>{let s={toolName:r,input:o},i=n.get(r),a=i?.mode??e,l=i?.reason,c;return a==="ask"&&t.onAsk?c=await t.onAsk(s):a==="deny"?c={behavior:"deny",reason:l}:c={behavior:"allow"},t.onDecision?.(s,c),ga(c)}}import{Telegraf as ka}from"telegraf";import{promises as Te}from"fs";import{join as Lr}from"path";var ge=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 Te.mkdir(this.options.dataDir,{recursive:!0});let e=await Te.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=Lr(this.options.dataDir,n),o=await Te.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 Te.mkdir(this.options.dataDir,{recursive:!0});for(let[e,n]of this.sessionData.entries()){let r=Lr(this.options.dataDir,`${e}.json`);await Te.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 Ce(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(`
|
|
1248
|
+
`,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 R(t){return`\u274C Error: ${t instanceof Error?t.message:t}`}var Hr=[{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 Ur(t){let e=["\u{1F4CB} Bot commands (aligned with agent-afk CLI):","",...Hr.map(n=>` ${n.cmd}
|
|
1248
1249
|
${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(`
|
|
1249
|
-
`)}function
|
|
1250
|
+
`)}function xt(){return`\u{1F44B} Welcome to Agent AFK Bot!
|
|
1250
1251
|
|
|
1251
1252
|
I'm powered by Claude and can help you with various tasks.
|
|
1252
1253
|
|
|
1253
1254
|
Available commands:
|
|
1254
|
-
${
|
|
1255
|
+
${Hr.map(e=>`${e.cmd} - ${e.desc}`).join(`
|
|
1255
1256
|
`)}
|
|
1256
1257
|
|
|
1257
|
-
Just send me a message to get started!`}function
|
|
1258
|
+
Just send me a message to get started!`}function Pt(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 Et(t){if(!t)return"\u{1F4E6} Conversation compacted (older messages summarized).";let e=t.tokensSavedEstimate!==void 0&&t.tokensSavedEstimate>0?` (~${ya(t.tokensSavedEstimate)} input tokens saved)`:"";return`\u{1F4E6} Compacted ${t.before} \u2192 ${t.after} messages${e}.`}function At(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 ya(t){return t>=1e3?`${Math.round(t/100)/10}k`:String(t)}async function Tt(t){await t.reply(xt())}async function Ct(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(Ur(r))}async function It(t,e,n,r){let o=t.chat?.id;if(!o){await t.reply(R("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(R(s))}}async function Nr(t,e,n){let r=t.chat?.id;if(!r){await t.reply(R("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(Et({before:s.messagesBefore,after:s.messagesAfter,...s.tokensSavedEstimate!==void 0?{tokensSavedEstimate:s.tokensSavedEstimate}:{}})):await t.reply(At(s.reason??"unknown"))}catch(o){n("Compact error:",o),await t.reply(R(o))}}async function Mt(t,e,n){let r=t.chat?.id;if(!r){await t.reply(R("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()}
|
|
1258
1259
|
|
|
1259
|
-
Usage: /model [opus|sonnet|haiku]`);return}let i=s[0];if(!i){await t.reply(
|
|
1260
|
-
Valid options: opus, sonnet, haiku`));return}try{await e.switchModel(r,a),await t.reply(
|
|
1261
|
-
\u25E6 ${
|
|
1262
|
-
\u25E6 ${
|
|
1260
|
+
Usage: /model [opus|sonnet|haiku]`);return}let i=s[0];if(!i){await t.reply(R("Please specify a model: opus, sonnet, or haiku"));return}let a=i.toLowerCase();if(!["opus","sonnet","haiku"].includes(a)){await t.reply(R(`Invalid model: ${i}
|
|
1261
|
+
Valid options: opus, sonnet, haiku`));return}try{await e.switchModel(r,a),await t.reply(Pt(a))}catch(c){n("Model switch error:",c),await t.reply(R(c))}}function Ze(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("rate limit")||e.toLowerCase().includes("too many requests")}function et(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("network")||e.toLowerCase().includes("connect")||e.toLowerCase().includes("timeout")}var ba=300,wa=9e4,va=6e4;async function Rt(t,e,n,r){let o="",s=null,i=0,a=async(l,c=!1)=>{let d=St(l||"\u2026"),u=Date.now();if(!s){let f=Ce(d);s=await t.reply(f[0]??"\u2026",{parse_mode:"HTML"});return}if(!c&&u-i<ba&&l.length<100)return;i=u;let p=Ce(d);try{await t.telegram.editMessageText(t.chat?.id,s.message_id,void 0,p[0]??d,{parse_mode:"HTML"})}catch{}};try{let l="sendMessageStream"in e&&typeof e.sendMessageStream=="function"?e.sendMessageStream(n):(async function*(){let f=await e.sendMessage(n,{stream:!1});yield{type:"message",message:f},yield{type:"done",metadata:f.metadata}})();await a("Thinking\u2026");let c=l[Symbol.asyncIterator](),d=!1,u=null,p=()=>{let f=d?va:wa;return new Promise((g,h)=>{u=setTimeout(()=>{u=null,h(new Error(d?"Response timed out. Try sending a shorter message or try again.":"Request timed out. The agent may still be starting (first message can take a minute). Try again in a moment."))},f),c.next().then(m=>{u!=null&&(clearTimeout(u),u=null),g(m)},m=>{u!=null&&(clearTimeout(u),u=null),h(m)})})};for(;;){let f=await p();if(f.done)break;let g=f.value;if(d||(d=!0,console.log("\u{1F4E1} First stream event received:",g.type),r?.("First stream event received:",g.type)),g.type==="chunk"&&g.chunk.type==="content"&&(o+=g.chunk.content,await a(o)),g.type==="message"&&g.message.role==="assistant"&&(o=g.message.content,await a(o)),g.type==="progress"){let{description:h,summary:m,lastToolName:w}=g.progress,v=w?`
|
|
1262
|
+
\u25E6 ${h} (${w})`:`
|
|
1263
|
+
\u25E6 ${h}`;o+=v,m&&(o+=`
|
|
1263
1264
|
${m}`),await a(o)}if(g.type==="suggestion"&&(o+=`
|
|
1264
1265
|
|
|
1265
|
-
\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=
|
|
1266
|
+
\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=Ce(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 Br(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 tt=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(Br(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}Ze(o)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):et(o)?await e.reply("\u{1F310} Network error. Please check your connection and try again."):await e.reply(R(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(R(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 Rt(n,o,r,this.log)}catch(o){console.error("\u274C Message handling error:",o),this.log("Message handling error:",o);let s=o;Ze(o)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):et(o)?await n.reply("\u{1F310} Network error. Please check your connection and try again."):await n.reply(R(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 _t(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 nt=class{bot;sessionManager;options;running=!1;registeredCommandChats=new Set;messageHandler;constructor(e){this.options=e,this.bot=new ka(e.botToken),this.sessionManager=new ge(e),this.messageHandler=new tt(this.bot,this.sessionManager,this.registeredCommandChats,this.log.bind(this)),this.setupHandlers()}setupHandlers(){this.bot.use(_t(this.options.allowedChatIds,this.log.bind(this))),this.bot.command("start",e=>Tt(e)),this.bot.command("help",e=>Ct(e,this.sessionManager)),this.bot.command("clear",async e=>{let n=e.chat?.id;if(!n){await e.reply(R("Could not identify chat"));return}(await this.sessionManager.getSession(n)).state!=="idle"?(this.messageHandler.enqueueClear(n,e),await e.reply("Clear queued.")):await It(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}),this.bot.command("compact",e=>Nr(e,this.sessionManager,this.log.bind(this))),this.bot.command("model",e=>Mt(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(R("An unexpected error occurred. Please try again.")).catch(r=>this.log("Failed to send error message:",r))})}async start(){if(this.running)throw new Error("Bot is already running");this.log("Loading sessions..."),await this.sessionManager.loadSessions(),this.log("Starting bot..."),await this.bot.launch(),this.log("Registering bot commands..."),await this.bot.telegram.setMyCommands([{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"}]),this.running=!0,this.log("Bot started successfully");let e=async n=>{this.log(`Received ${n}, shutting down...`),await this.stop(),process.exit(0)};process.once("SIGINT",()=>e("SIGINT")),process.once("SIGTERM",()=>e("SIGTERM"))}async stop(){if(this.running){this.log("Stopping bot..."),this.running=!1,this.log("Closing sessions..."),await this.sessionManager.closeAll(),this.log("Stopping bot polling...");try{this.bot.stop()}catch(e){this.log("Error stopping bot (may not have been started):",e)}this.log("Bot stopped")}}getStats(){return{running:this.running,activeSessions:this.sessionManager.getSessionCount(),totalChats:this.sessionManager.getChatCount()}}async handleStart(e){return Tt(e)}async handleHelp(e){return Ct(e,this.sessionManager)}async handleClear(e){let n=e.chat?.id;if(!n){await e.reply(R("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 It(e,this.sessionManager,this.registeredCommandChats,this.log.bind(this))}async handleMessage(e){return this.messageHandler.handle(e)}async handleModelSwitch(e){return Mt(e,this.sessionManager,this.log.bind(this))}log(...e){this.options.verbose&&console.log("[TelegramBot]",...e)}};export{oe as AgentSession,ae as MessageQueue,me as OpenAICodexProvider,ge as SessionManager,P as SubagentManager,nt as TelegramBot,jr as createCanUseToolHook,Ye as openaiCodexProvider,xe as providerForModel,Je as resolveProvider};
|