agent-afk 4.45.3 → 4.45.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/telegram.mjs CHANGED
@@ -145,7 +145,7 @@ Usage: /name <name>`:`\u{1F3F7}\uFE0F No name set.
145
145
  Usage: /name <name>`}function Pd(){return V("Invalid name \u2014 use letters, numbers, spaces, or hyphens.")}function Id(t,e){return e?`\u{1F3F7}\uFE0F Named: ${t}
146
146
 
147
147
  Resume from CLI:
148
- ${e}`:`\u{1F3F7}\uFE0F Named: ${t} (saves on first turn)`}function ro(t){if(!t)return"\u{1F4E6} Conversation compacted (older messages summarized).";let e=t.tokensSavedEstimate!==void 0&&t.tokensSavedEstimate>0?` (~${Dv(t.tokensSavedEstimate)} input tokens saved)`:"";return`\u{1F4E6} Compacted ${t.before} \u2192 ${t.after} messages${e}.`}function oo(t){return t==="aborted"?"\u{1F4E6} Compaction cancelled.":t==="history-too-short"?"\u{1F4E6} Not enough history to compact yet.":t==="not-supported"?"\u{1F4E6} Compaction isn't available for the current model.":t.startsWith("summarization-failed")?`\u26A0\uFE0F Compaction failed: ${t}. History unchanged.`:`\u{1F4E6} Nothing to compact (${t}).`}function Dv(t){return t>=1e3?`${Math.round(t/100)/10}k`:String(t)}var Ce=y(()=>{"use strict"});var me,Me,J,zt,ge=y(()=>{"use strict";me=class extends Error{constructor(e){super(e),this.name="AbortError"}},Me=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},J=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},zt=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd}});function Jt(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Nn(t,e,n){let r=e==="oauth"?{authToken:t}:{apiKey:t};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function Oe(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${Cd},${Fv}`:Cd,"x-app":"cli","User-Agent":Lv,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Md(t){return t!=="oauth"?null:[{type:"text",text:Nv}]}var Cd,Fv,Lv,Nv,Et=y(()=>{"use strict";Cd="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Fv="effort-2025-11-24",Lv="claude-cli/1.0.0 (external, cli)",Nv="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function ao(t){Ci=t}function Ii(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function so(t,e,n){let r={},o=Ii(t);o&&(r.id=o);let s=Ii(e);s&&(r.baseUrl=s);let i=Ii(n);return i&&(r.apiKey=i),r}function Hv(){return{local:so(S.AFK_MODEL_LOCAL,S.AFK_MODEL_LOCAL_BASE_URL,S.AFK_MODEL_LOCAL_API_KEY),small:so(S.AFK_MODEL_SMALL,S.AFK_MODEL_SMALL_BASE_URL,S.AFK_MODEL_SMALL_API_KEY),medium:so(S.AFK_MODEL_MEDIUM,S.AFK_MODEL_MEDIUM_BASE_URL,S.AFK_MODEL_MEDIUM_API_KEY),large:so(S.AFK_MODEL_LARGE,S.AFK_MODEL_LARGE_BASE_URL,S.AFK_MODEL_LARGE_API_KEY)}}function Di(t){let e=Hv(),n={};for(let r of Mi){let o=At[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function Yt(t){return t||Ci||Di()}function Xt(t,e=Yt()){let n=t.trim().toLowerCase();if(!n||n===Uv)return;for(let o of Mi){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:$v[n]}function Fi(t,e=Yt()){if(t===void 0)return{id:""};let n=Xt(t,e);if(n)return e[n];let r=Bv[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function Tt(t,e=Yt()){if(t!==void 0)return Fi(t,e).id}function Od(t,e=Yt()){if(t===void 0)return;let n=Xt(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function Dd(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Mi){let o=Kv(n[r]);o&&(e[r]=o)}return e}function jv(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai"}function io(t){return typeof t=="string"?t.trim():""}function Kv(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=io(e.id);if(!n)return;let r={id:n},o=io(e.name);o&&(r.name=o);let s=jv(e.provider);s&&(r.provider=s);let i=io(e.baseUrl);i&&(r.baseUrl=i);let a=io(e.apiKey);return a&&(r.apiKey=a),r}}var Mi,At,$v,Uv,Oi,Bv,Ci,Ve=y(()=>{"use strict";U();Mi=["local","small","medium","large"],At={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},$v={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},Uv="auto",Oi="claude-fable-5",Bv={fable:Oi}});function Ni(t){return t in Li}function se(t){return Tt(t)}var Li,De=y(()=>{"use strict";Ve();Li={opus:At.large.id,opus_1m:At.large.id,sonnet:At.medium.id,sonnet_1m:At.medium.id,haiku:At.small.id,fable:Oi}});import Wv from"@anthropic-ai/sdk";import{randomUUID as Fd}from"node:crypto";async function Ld(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=Jt(e),l=Nn(e,c),d=a?a(l):new Wv(l),u=Fd(),p=Fd(),f=Oe(c,u,p),h=se(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let v=await d.messages.create({model:h,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),b=[];for(let w of v.content)w.type==="text"&&b.push(w.text);let E=b.join("").trim();return E.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),E}var Nd=y(()=>{"use strict";Et();De()});import{execFileSync as $d}from"child_process";import{existsSync as Gv,readFileSync as qv,writeFileSync as Vv}from"fs";import{homedir as Ud,userInfo as Bd}from"os";import{join as Hd}from"path";function Ae(){let t=jd();if(t===void 0)return;let e=Kd(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 $i(){let t=jd();if(t===void 0)return;let e=Kd(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Yv)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 Xv(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}:{}},Qv(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
148
+ ${e}`:`\u{1F3F7}\uFE0F Named: ${t} (saves on first turn)`}function ro(t){if(!t)return"\u{1F4E6} Conversation compacted (older messages summarized).";let e=t.tokensSavedEstimate!==void 0&&t.tokensSavedEstimate>0?` (~${Dv(t.tokensSavedEstimate)} input tokens saved)`:"";return`\u{1F4E6} Compacted ${t.before} \u2192 ${t.after} messages${e}.`}function oo(t){return t==="aborted"?"\u{1F4E6} Compaction cancelled.":t==="history-too-short"?"\u{1F4E6} Not enough history to compact yet.":t==="not-supported"?"\u{1F4E6} Compaction isn't available for the current model.":t.startsWith("summarization-failed")?`\u26A0\uFE0F Compaction failed: ${t}. History unchanged.`:`\u{1F4E6} Nothing to compact (${t}).`}function Dv(t){return t>=1e3?`${Math.round(t/100)/10}k`:String(t)}var Ce=y(()=>{"use strict"});var me,Me,J,zt,ge=y(()=>{"use strict";me=class extends Error{constructor(e){super(e),this.name="AbortError"}},Me=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},J=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},zt=class extends Error{constructor(n,r,o){super(o??`Budget ceiling reached: $${n.toFixed(4)} cumulative >= $${r.toFixed(4)} limit`);this.runningCostUsd=n;this.maxBudgetUsd=r;this.name="BudgetExceededError"}runningCostUsd;maxBudgetUsd}});function Jt(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Nn(t,e,n){let r=e==="oauth"?{authToken:t}:{apiKey:t};return typeof n=="string"&&n.length>0?{...r,baseURL:n}:r}function Oe(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${Cd},${Fv}`:Cd,"x-app":"cli","User-Agent":Lv,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Md(t){return t!=="oauth"?null:[{type:"text",text:Nv}]}var Cd,Fv,Lv,Nv,Et=y(()=>{"use strict";Cd="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Fv="effort-2025-11-24",Lv="claude-cli/1.0.0 (external, cli)",Nv="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;"});function ao(t){Ci=t}function Ii(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function so(t,e,n){let r={},o=Ii(t);o&&(r.id=o);let s=Ii(e);s&&(r.baseUrl=s);let i=Ii(n);return i&&(r.apiKey=i),r}function Hv(){return{local:so(S.AFK_MODEL_LOCAL,S.AFK_MODEL_LOCAL_BASE_URL,S.AFK_MODEL_LOCAL_API_KEY),small:so(S.AFK_MODEL_SMALL,S.AFK_MODEL_SMALL_BASE_URL,S.AFK_MODEL_SMALL_API_KEY),medium:so(S.AFK_MODEL_MEDIUM,S.AFK_MODEL_MEDIUM_BASE_URL,S.AFK_MODEL_MEDIUM_API_KEY),large:so(S.AFK_MODEL_LARGE,S.AFK_MODEL_LARGE_BASE_URL,S.AFK_MODEL_LARGE_API_KEY)}}function Di(t){let e=Hv(),n={};for(let r of Mi){let o=At[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function Yt(t){return t||Ci||Di()}function Xt(t,e=Yt()){let n=t.trim().toLowerCase();if(!n||n===Uv)return;for(let o of Mi){let s=e[o].name;if(s&&s.trim().toLowerCase()===n)return o}return n==="local"||n==="small"||n==="medium"||n==="large"?n:$v[n]}function Fi(t,e=Yt()){if(t===void 0)return{id:""};let n=Xt(t,e);if(n)return e[n];let r=Bv[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function Tt(t,e=Yt()){if(t!==void 0)return Fi(t,e).id}function Od(t,e=Yt()){if(t===void 0)return;let n=Xt(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function Dd(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Mi){let o=Kv(n[r]);o&&(e[r]=o)}return e}function jv(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="anthropic"||e==="anthropic-direct")return"anthropic";if(e==="openai"||e==="openai-compatible")return"openai"}function io(t){return typeof t=="string"?t.trim():""}function Kv(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=io(e.id);if(!n)return;let r={id:n},o=io(e.name);o&&(r.name=o);let s=jv(e.provider);s&&(r.provider=s);let i=io(e.baseUrl);i&&(r.baseUrl=i);let a=io(e.apiKey);return a&&(r.apiKey=a),r}}var Mi,At,$v,Uv,Oi,Bv,Ci,Ve=y(()=>{"use strict";U();Mi=["local","small","medium","large"],At={local:{id:""},small:{id:"claude-haiku-4-5-20251001"},medium:{id:"claude-sonnet-4-6"},large:{id:"claude-opus-4-8"}},$v={haiku:"small",sonnet:"medium",sonnet_1m:"medium",opus:"large",opus_1m:"large"},Uv="auto",Oi="claude-fable-5",Bv={fable:Oi}});function Ni(t){return t in Li}function oe(t){return Tt(t)}var Li,De=y(()=>{"use strict";Ve();Li={opus:At.large.id,opus_1m:At.large.id,sonnet:At.medium.id,sonnet_1m:At.medium.id,haiku:At.small.id,fable:Oi}});import Wv from"@anthropic-ai/sdk";import{randomUUID as Fd}from"node:crypto";async function Ld(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=Jt(e),l=Nn(e,c),d=a?a(l):new Wv(l),u=Fd(),p=Fd(),f=Oe(c,u,p),h=oe(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let v=await d.messages.create({model:h,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),b=[];for(let w of v.content)w.type==="text"&&b.push(w.text);let E=b.join("").trim();return E.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),E}var Nd=y(()=>{"use strict";Et();De()});import{execFileSync as $d}from"child_process";import{existsSync as Gv,readFileSync as qv,writeFileSync as Vv}from"fs";import{homedir as Ud,userInfo as Bd}from"os";import{join as Hd}from"path";function Ae(){let t=jd();if(t===void 0)return;let e=Kd(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 $i(){let t=jd();if(t===void 0)return;let e=Kd(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Yv)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 Xv(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}:{}},Qv(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
149
149
  `)}return n.accessToken}function jd(){if(process.platform==="darwin")try{return $d("security",["find-generic-password","-s","Claude Code-credentials","-a",Bd().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=Hd(Ud(),".claude",".credentials.json");if(!Gv(t))return;try{return qv(t,"utf-8")}catch{return}}}function Kd(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 Xv(t){try{let e=await fetch(Jv,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:zv})});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 $n(t){if(!t||t.length<3)return"token:(unknown)";try{let n=t.split(".");if(n.length<2)throw new Error("not a JWT");let r=Buffer.from(n[1],"base64url").toString("utf-8"),o=JSON.parse(r),s=typeof o.email=="string"&&o.email||typeof o.sub=="string"&&o.sub||typeof o.account_id=="string"&&o.account_id||typeof o.preferred_username=="string"&&o.preferred_username;if(s)return s}catch{}return`token:${t.length>=8?t.slice(-8):t}`}function Qv(t){if(process.platform==="darwin")$d("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",Bd().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=Hd(Ud(),".claude",".credentials.json");Zv(e,t)}}function Zv(t,e){Vv(t,e,{encoding:"utf-8",mode:384})}var zv,Jv,Yv,Un=y(()=>{"use strict";zv="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Jv="https://platform.claude.com/v1/oauth/token",Yv=300*1e3});function Fe(t){return t==="bypassPermissions"||t==="autonomous"}var Bn=y(()=>{"use strict"});function co(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=S.AFK_DISABLE_PROMPT_CACHE;if(e===void 0||e.length===0)return!0;let n=e.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function lo(){let t=S.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":eS}function Wd(t,e){if(t.length===0)return t;let n=t[t.length-1],r=qd(n,e);return r===n?t:[...t.slice(0,-1),r]}function Gd(t,e){if(t.length===0)return t;let n=t[t.length-1],r=tS(n,e);return r===n?t:[...t.slice(0,-1),r]}function tS(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=qd(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function qd(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var eS,Ui=y(()=>{"use strict";U();eS="1h"});function Vd(t){return t!=="plan"?null:{type:"text",text:Bi}}var Bi,Hi=y(()=>{"use strict";Bi=["## Plan mode is active","","File and memory write tools (`write_file`, `edit_file`, `memory_update`, `procedure_write`) are refused at the hook layer.","`bash` runs for read-only investigation (git status/log/diff, ls, cat, grep, find \u2014 chained or not); state-mutating bash (file writes, rm, installs, commits, pushes) is refused while planning. The user has asked you to plan, not yet to act \u2014 exit plan mode to make changes.","Treat this turn as planning work.","","Traverse the shape that matches the work \u2014 skip steps the terrain already covers, do not skip steps the terrain hides:",""," unknown field \u2192 ground the current terrain \u2192 gather missing codebase context \u2192"," research missing external context \u2192 reveal chaos / constraints / risks \u2192"," name the failure geometry \u2192 form a candidate plan \u2192 apply adversarial pressure \u2192 embody the final plan","","Reach for these skills (invoke via the `skill` tool) when the cost of skipping exceeds the cost of dispatching:"," - `ground-state` \u2014 survey git, infra, memory before non-trivial work"," - `gather` \u2014 parallel context-gathering for a code area"," - `research` \u2014 parallel external + local context for the current task"," - `devils-advocate` \u2014 generate alternatives and rank them before committing"," - `shadow-verify` \u2014 independently re-derive load-bearing claims","","Do not declare readiness silently. When the plan is ready, state: chosen approach, risks named, and alternatives considered. The user will then exit plan mode with `/plan off`, which has you save this plan to a file and implement it (Shift+Tab instead advances the permission-mode ring without saving or implementing) \u2014 so keep the plan concrete and complete enough to act on directly."].join(`
150
150
  `)});function zd(t){return t!=="autonomous"?null:{type:"text",text:ji}}var ji,Ki=y(()=>{"use strict";ji=["## AFK mode is active","","The operator is away from keyboard. Your channel to them is Telegram via the `send_telegram` tool \u2014 not this transcript, which no one is watching live. At the end of each turn, push your terminal state (Done / Blocked / Asking) to Telegram so the operator can review asynchronously.","","Posture \u2014 bounded autonomy, not unchecked action:"," - Proceed autonomously on reversible work. Do not stop to confirm actions you are already authorized to take and can undo (edits, reads, tests, local commits, non-force pushes, installs)."," - At a one-way door \u2014 anything irreversible, externally visible, credential- or payment-touching, or where multiple readings lead to materially different work \u2014 do NOT guess. Push a concise Asking summary to Telegram naming the decision and your recommended default, then stop and end the turn in the Asking state."," - A mechanical gate refuses high-risk and irreversible operations at the hook layer regardless of this text. Treat a gate refusal as a signal to surface the decision to the operator, not an obstacle to work around.","","Communication discipline:"," - Batch updates. Send a Telegram message at terminal state (and at a genuinely blocking fork), not a play-by-play \u2014 the operator gets a push notification for every message."," - Keep pushes short and scannable: what happened, what changed, what (if anything) you need. Never paste raw tool output, logs, secrets, or full file contents into a push.","","Exit: the operator returns and runs `/afk off` (or Shift+Tab) to restore default permissions and terminal-channel interaction."].join(`
151
151
  `)});function Q(t){let e=Jd[t];if(!e){let n=Object.keys(Jd).sort(),r=n.length>0?"Available: "+n.join(", "):"";throw new Error("Unknown skill: "+t+". "+r)}return e}var Jd,Te=y(()=>{"use strict";Jd={"audit-fit":{"01-skill-inspector.md":`# Skill Inspector
@@ -1001,8 +1001,8 @@ Don't refuse the flow; just clarify where the wizard runs.
1001
1001
  Be terse and operational. The user is doing one-time setup; they want it done, not narrated. Confirm each step in one line, don't over-explain. Use \`\u2713\` for success, \`\u2717\` for failure, and code fences for any command they should run.
1002
1002
  `}}});function Wi(t,e){return e?!0:(t.audience??"public")==="public"}function de(t){uo.set(t.name,t)}function Le(t){let e=uo.get(t);if(e)return e;let n=Array.from(uo.keys()).sort(),r=n.length>0?`
1003
1003
  Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}`)}function Yd(){return Array.from(uo.keys()).sort()}var uo,be=y(()=>{"use strict";uo=new Map});async function Qt(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){$(`trace.emit tool_call failed: ${ze(n)}`)}}async function Zt(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){$(`trace.emit hook_decision failed: ${ze(n)}`)}}async function xt(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){$(`trace.emit subagent_lifecycle failed: ${ze(n)}`)}}async function Xd(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){$(`trace.emit budget failed: ${ze(n)}`)}}async function Qd(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){$(`trace.emit abort failed: ${ze(n)}`)}}async function Zd(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){$(`trace.emit compaction failed: ${ze(n)}`)}}async function eu(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){$(`trace.emit closure failed: ${ze(n)}`)}}async function ne(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){$(`trace.emit browser_event failed: ${ze(n)}`)}}async function re(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){$(`trace.emit session_phase failed: ${ze(n)}`)}}function ze(t){return t instanceof Error?t.message:String(t)}var ee=y(()=>{"use strict";le()});function nS(t){if(typeof t=="string")return t;if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}var po,tu=y(()=>{"use strict";ee();po=class{nodes=new Map;traceWriter;constructor(e){this.traceWriter=e}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}childrenOf(e){let n=this.nodes.get(e);return n?Array.from(n.children):[]}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 c of i.listeners)try{c(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,r="user_signal"){let o=this.nodes.get(e);if(!o||o.controller.signal.aborted)return;let s=[],i=[...o.children],a=new Set;for(;i.length;){let c=i.shift();if(a.has(c))continue;a.add(c);let l=this.nodes.get(c);if(l){l.cascading=!0,s.push(c);for(let d of l.children)i.push(d)}}Qd(this.traceWriter,{origin:r,cascadedTo:s,...n!==void 0?{reason:nS(n)}:{}}),o.controller.abort(n);for(let c of s){let l=this.nodes.get(c);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 en,Gi=y(()=>{"use strict";en=class{pendingResolve=null;bufferedMessages=[];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.bufferedMessages.push(e)}createIterable(){let e=this;return{[Symbol.asyncIterator](){return{next(){if(e.bufferedMessages.length>0){let n=e.bufferedMessages.shift(),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 fo(t,e){let n=e??Yt(),r=Xt(t.model,n);if(!r)return;let o=n[r],s=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"?"openai-compatible":z(t.model,e?{slots:e}:void 0);o.apiKey!==void 0?t.apiKey=o.apiKey:(s==="openai-compatible"||o.baseUrl!==void 0)&&(t.apiKey=void 0),o.baseUrl!==void 0&&(s==="openai-compatible"?t.openaiBaseUrl=o.baseUrl:t.baseUrl=o.baseUrl)}var qi=y(()=>{"use strict";we();Ve()});function rS(t){return typeof t=="string"?t:t.map(e=>{let n=e;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(e=>e.length>0).join(`
1004
- `)}var mo,nu=y(()=>{"use strict";Gi();qi();le();mo=class{outerIterator;baseConfig;deps;currentModel;currentPermissionMode;currentCwd;startupFamily;active;closed=!1;shadowHistory;pendingUserText;pendingAssistantText="";lastSessionId;constructor(e,n){this.outerIterator=e.prompt[Symbol.asyncIterator](),this.baseConfig=e.config,this.deps=n,this.currentModel=typeof e.config.model=="string"?e.config.model:void 0,this.currentPermissionMode=e.config.permissionMode,this.currentCwd=e.config.cwd,this.startupFamily=n.providerNameForModel(this.currentModel),this.shadowHistory=[...e.config.resumeHistory??[]]}buildInner(e,n){let r=this.deps.resolveProvider(e),o=new en(()=>this.lastSessionId),s={...this.baseConfig};s.model=e??this.baseConfig.model;let i=r.name===this.startupFamily&&this.baseConfig.apiKey!==void 0?this.baseConfig.apiKey:this.deps.resolveApiKey(e);i!==void 0?s.apiKey=i:delete s.apiKey,fo(s),this.currentPermissionMode!==void 0&&(s.permissionMode=this.currentPermissionMode),this.currentCwd!==void 0&&(s.cwd=this.currentCwd),n&&(s.resumeHistory=[...this.shadowHistory]);let a=r.query({prompt:o.createIterable(),config:s});return{family:r.name,query:a,iterator:a[Symbol.asyncIterator](),input:o}}async closeActive(){let e=this.active;if(e){this.active=void 0;try{await e.iterator.return?.(void 0)}catch{}try{await e.query.close()}catch{}}}observeEvent(e){e.type==="assistant.message"&&(this.pendingAssistantText+=(this.pendingAssistantText?`
1005
- `:"")+e.text)}commitShadowTurn(){this.pendingUserText!==void 0&&(this.shadowHistory.push({user:this.pendingUserText,assistant:this.pendingAssistantText}),this.pendingUserText=void 0,this.pendingAssistantText="")}async*[Symbol.asyncIterator](){try{for(this.active=this.buildInner(this.currentModel,!1),yield*this.driveUntilInit(!1);!this.closed;){let e=await this.outerIterator.next();if(e.done)break;let n=e.value;this.lastSessionId=n.sessionId;let r=this.deps.providerNameForModel(this.currentModel);if((!this.active||r!==this.active.family)&&(await this.closeActive(),this.active=this.buildInner(this.currentModel,!0),$(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=rS(n.content),this.pendingAssistantText="",this.active.input.pushUserMessage(n.content);;){let o=await this.active.iterator.next();if(o.done){this.closed=!0;break}let s=o.value;if(this.observeEvent(s),yield s,s.type==="turn.completed"){this.commitShadowTurn();break}if(s.type==="error"){this.commitShadowTurn();break}}}}finally{await this.closeActive()}}async*driveUntilInit(e){for(;;){let n=await this.active.iterator.next();if(n.done)return yield{type:"error",error:new Error("provider ended before initialization")},this.closed=!0,!0;let r=n.value;if(r.type==="session.init")return e||(yield r),!1;if(r.type==="error")return yield r,this.closed=!0,!0;yield r}}async interrupt(){await this.active?.query.interrupt()}async setModel(e){typeof e=="string"&&e.length>0&&(this.currentModel=e,this.active&&this.deps.providerNameForModel(e)===this.active.family&&await this.active.query.setModel(e))}async setPermissionMode(e){this.currentPermissionMode=e,await this.active?.query.setPermissionMode(e)}setCwd(e){this.currentCwd=e,this.active?.query.setCwd?.(e)}async reauth(){return await this.active?.query.reauth?.()??null}async supportedCommands(){return await this.active?.query.supportedCommands()??[]}async supportedModels(){return await this.active?.query.supportedModels()??[]}async supportedAgents(){return await this.active?.query.supportedAgents()??[]}async getContextUsage(){return await this.active?.query.getContextUsage()??{}}async mcpServerStatus(){return await this.active?.query.mcpServerStatus()??[]}async accountInfo(){return await this.active?.query.accountInfo()??{}}async rewindFiles(e,n){let r=this.active;return r?r.query.rewindFiles(e,n):{canRewind:!1,error:"no active provider"}}async compact(){let e=this.active;return e?.query.compact?e.query.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}}async reloadPlugins(...e){let n=this.active?.query;if(n&&typeof n.reloadPlugins=="function")return n.reloadPlugins(...e)}async close(){this.closed=!0,await this.closeActive()}}});function Vi(){return S.ANTHROPIC_API_KEY||S.CLAUDE_CODE_OAUTH_TOKEN||Ae()}function ru(){return S.OPENAI_API_KEY||S.CODEX_API_KEY||void 0}function Je(t){let e=z(t);return e==="openai-compatible"||e==="openai-codex"?ru():Vi()}var tn=y(()=>{"use strict";we();Un();U()});async function ho(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})`:"",c=new Me(`Operation timed out after ${e}ms${a}`,e);n.controller&&!n.controller.signal.aborted&&n.controller.abort(c),i(c)},e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}var go,zi,yo=y(()=>{"use strict";ge();go=0,zi=5e3});async function bo(t,e,n){if(!t)return;if(n.kind==="blocked"){await Zt(t,{hookEvent:e,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await Zt(t,{hookEvent:e,decision:r.decision,...r.reason!==void 0?{reason:r.reason}:{},...r.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(r.injectContext,"utf8")}:{}})}async function ou(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await bo(n.traceWriter,"SessionStart",{kind:"decision",decision:r})}catch(r){throw r instanceof J&&await bo(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function su(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await bo(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof J&&await bo(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof J||r instanceof me){$(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}$(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var iu=y(()=>{"use strict";le();ge();ee()});function oS(t){return t==="max_tokens"||t==="length"}function au(t){return t.maxTurnsHit?"max_turns_exceeded":t.hookBlocked?"hook_blocked":t.dispatchReason==="error"?"abort":t.abort!==null?t.abort:t.sawProviderError?"abort":oS(t.lastStopReason)?"truncated":"model_end_turn"}var cu=y(()=>{"use strict"});function lu(t){return t==="abort"?sS:null}var sS,du=y(()=>{"use strict";sS="Session ended via abort before reaching a terminal state. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state, or re-run the task if the interruption was intentional."});import*as nn from"node:fs";import*as rn from"node:fs/promises";function wo(t,e){return t.length>e?`${t.slice(0,e)}\u2026 [truncated]`:t}function iS(t){switch(t.type){case"message":return t.message.role!=="assistant"||!t.message.content?null:{kind:"assistant",text:wo(t.message.content,pu)};case"chunk":{let e=t.chunk;return e.type==="tool_use_detail"?{kind:"tool",toolName:e.toolName,input:wo(e.toolInput,uu)}:e.type==="tool_result"&&e.isError===!0?{kind:"tool_error",content:wo(e.content,uu)}:null}case"done":{let e=t.metadata?.totalCostUsd,n=t.metadata?.durationMs;return{kind:"done",...typeof e=="number"?{costUsd:e}:{},...typeof n=="number"?{durationMs:n}:{}}}case"error":return{kind:"error",message:t.error.message};case"paused":return{kind:"paused",...t.resetsAt?{resetsAt:t.resetsAt.toISOString()}:{}};case"resumed":return{kind:"resumed"};default:return null}}function aS(t){let e=t.trim();if(!e)return null;try{let n=JSON.parse(e);return n.v!==1||typeof n.ts!="number"||typeof n.kind!="string"?null:n}catch{return null}}async function vo(t){if(!Cn(t))return!1;try{return await rn.access($r(t)),!0}catch{return!1}}async function*fu(t,e){if(!Cn(t))return;let n=$r(t),r=Mn(t),{fromStart:o=!1,signal:s}=e??{},i=0,a="",c=!1;async function*l(){let f=null;try{f=await rn.open(n,"r");let h=await f.stat();if(h.size<=i)return;let g=h.size-i,v=Buffer.allocUnsafe(g),{bytesRead:b}=await f.read(v,0,g,i);if(b===0)return;i+=b,a+=v.toString("utf8",0,b);let E=a.split(`
1004
+ `)}var mo,nu=y(()=>{"use strict";Gi();qi();le();mo=class{outerIterator;baseConfig;deps;currentModel;currentPermissionMode;currentCwd;startupFamily;active;activeModel;closed=!1;shadowHistory;pendingUserText;pendingAssistantText="";lastSessionId;constructor(e,n){this.outerIterator=e.prompt[Symbol.asyncIterator](),this.baseConfig=e.config,this.deps=n,this.currentModel=typeof e.config.model=="string"?e.config.model:void 0,this.currentPermissionMode=e.config.permissionMode,this.currentCwd=e.config.cwd,this.startupFamily=n.providerNameForModel(this.currentModel),this.shadowHistory=[...e.config.resumeHistory??[]]}resolveInner(e){let n=this.deps.resolveProvider(e),r={...this.baseConfig};r.model=e??this.baseConfig.model;let o=n.name===this.startupFamily&&this.baseConfig.apiKey!==void 0?this.baseConfig.apiKey:this.deps.resolveApiKey(e);o!==void 0?r.apiKey=o:delete r.apiKey,fo(r);let s=[n.name,r.baseUrl??"",r.openaiBaseUrl??"",r.apiKey??""].join("\0");return{provider:n,innerConfig:r,signature:s}}buildInner(e,n){let{provider:r,innerConfig:o,signature:s}=this.resolveInner(e),i=new en(()=>this.lastSessionId);this.currentPermissionMode!==void 0&&(o.permissionMode=this.currentPermissionMode),this.currentCwd!==void 0&&(o.cwd=this.currentCwd),n&&(o.resumeHistory=[...this.shadowHistory]);let a=r.query({prompt:i.createIterable(),config:o});return{family:r.name,signature:s,query:a,iterator:a[Symbol.asyncIterator](),input:i}}async closeActive(){let e=this.active;if(e){this.active=void 0;try{await e.iterator.return?.(void 0)}catch{}try{await e.query.close()}catch{}}}observeEvent(e){e.type==="assistant.message"&&(this.pendingAssistantText+=(this.pendingAssistantText?`
1005
+ `:"")+e.text)}commitShadowTurn(){this.pendingUserText!==void 0&&(this.shadowHistory.push({user:this.pendingUserText,assistant:this.pendingAssistantText}),this.pendingUserText=void 0,this.pendingAssistantText="")}async*[Symbol.asyncIterator](){try{for(this.active=this.buildInner(this.currentModel,!1),this.activeModel=this.currentModel,yield*this.driveUntilInit(!1);!this.closed;){let e=await this.outerIterator.next();if(e.done)break;let n=e.value;this.lastSessionId=n.sessionId;let r=this.currentModel!==this.activeModel,o=!this.active||r&&this.resolveInner(this.currentModel).signature!==this.active.signature;if(this.activeModel=this.currentModel,o&&(await this.closeActive(),this.active=this.buildInner(this.currentModel,!0),$(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=rS(n.content),this.pendingAssistantText="",this.active.input.pushUserMessage(n.content);;){let s=await this.active.iterator.next();if(s.done){this.closed=!0;break}let i=s.value;if(this.observeEvent(i),yield i,i.type==="turn.completed"){this.commitShadowTurn();break}if(i.type==="error"){this.commitShadowTurn();break}}}}finally{await this.closeActive()}}async*driveUntilInit(e){for(;;){let n=await this.active.iterator.next();if(n.done)return yield{type:"error",error:new Error("provider ended before initialization")},this.closed=!0,!0;let r=n.value;if(r.type==="session.init")return e||(yield r),!1;if(r.type==="error")return yield r,this.closed=!0,!0;yield r}}async interrupt(){await this.active?.query.interrupt()}async setModel(e){typeof e=="string"&&e.length>0&&(this.currentModel=e,this.active&&this.resolveInner(e).signature===this.active.signature&&await this.active.query.setModel(e))}async setPermissionMode(e){this.currentPermissionMode=e,await this.active?.query.setPermissionMode(e)}setCwd(e){this.currentCwd=e,this.active?.query.setCwd?.(e)}async reauth(){return await this.active?.query.reauth?.()??null}async supportedCommands(){return await this.active?.query.supportedCommands()??[]}async supportedModels(){return await this.active?.query.supportedModels()??[]}async supportedAgents(){return await this.active?.query.supportedAgents()??[]}async getContextUsage(){return await this.active?.query.getContextUsage()??{}}async mcpServerStatus(){return await this.active?.query.mcpServerStatus()??[]}async accountInfo(){return await this.active?.query.accountInfo()??{}}async rewindFiles(e,n){let r=this.active;return r?r.query.rewindFiles(e,n):{canRewind:!1,error:"no active provider"}}async compact(){let e=this.active;return e?.query.compact?e.query.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}}async reloadPlugins(...e){let n=this.active?.query;if(n&&typeof n.reloadPlugins=="function")return n.reloadPlugins(...e)}async close(){this.closed=!0,await this.closeActive()}}});function Vi(){return S.ANTHROPIC_API_KEY||S.CLAUDE_CODE_OAUTH_TOKEN||Ae()}function ru(){return S.OPENAI_API_KEY||S.CODEX_API_KEY||void 0}function Je(t){let e=z(t);return e==="openai-compatible"||e==="openai-codex"?ru():Vi()}var tn=y(()=>{"use strict";we();Un();U()});async function ho(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})`:"",c=new Me(`Operation timed out after ${e}ms${a}`,e);n.controller&&!n.controller.signal.aborted&&n.controller.abort(c),i(c)},e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}var go,zi,yo=y(()=>{"use strict";ge();go=0,zi=5e3});async function bo(t,e,n){if(!t)return;if(n.kind==="blocked"){await Zt(t,{hookEvent:e,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await Zt(t,{hookEvent:e,decision:r.decision,...r.reason!==void 0?{reason:r.reason}:{},...r.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(r.injectContext,"utf8")}:{}})}async function ou(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await bo(n.traceWriter,"SessionStart",{kind:"decision",decision:r})}catch(r){throw r instanceof J&&await bo(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function su(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await bo(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof J&&await bo(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof J||r instanceof me){$(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}$(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var iu=y(()=>{"use strict";le();ge();ee()});function oS(t){return t==="max_tokens"||t==="length"}function au(t){return t.maxTurnsHit?"max_turns_exceeded":t.hookBlocked?"hook_blocked":t.dispatchReason==="error"?"abort":t.abort!==null?t.abort:t.sawProviderError?"abort":oS(t.lastStopReason)?"truncated":"model_end_turn"}var cu=y(()=>{"use strict"});function lu(t){return t==="abort"?sS:null}var sS,du=y(()=>{"use strict";sS="Session ended via abort before reaching a terminal state. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state, or re-run the task if the interruption was intentional."});import*as nn from"node:fs";import*as rn from"node:fs/promises";function wo(t,e){return t.length>e?`${t.slice(0,e)}\u2026 [truncated]`:t}function iS(t){switch(t.type){case"message":return t.message.role!=="assistant"||!t.message.content?null:{kind:"assistant",text:wo(t.message.content,pu)};case"chunk":{let e=t.chunk;return e.type==="tool_use_detail"?{kind:"tool",toolName:e.toolName,input:wo(e.toolInput,uu)}:e.type==="tool_result"&&e.isError===!0?{kind:"tool_error",content:wo(e.content,uu)}:null}case"done":{let e=t.metadata?.totalCostUsd,n=t.metadata?.durationMs;return{kind:"done",...typeof e=="number"?{costUsd:e}:{},...typeof n=="number"?{durationMs:n}:{}}}case"error":return{kind:"error",message:t.error.message};case"paused":return{kind:"paused",...t.resetsAt?{resetsAt:t.resetsAt.toISOString()}:{}};case"resumed":return{kind:"resumed"};default:return null}}function aS(t){let e=t.trim();if(!e)return null;try{let n=JSON.parse(e);return n.v!==1||typeof n.ts!="number"||typeof n.kind!="string"?null:n}catch{return null}}async function vo(t){if(!Cn(t))return!1;try{return await rn.access($r(t)),!0}catch{return!1}}async function*fu(t,e){if(!Cn(t))return;let n=$r(t),r=Mn(t),{fromStart:o=!1,signal:s}=e??{},i=0,a="",c=!1;async function*l(){let f=null;try{f=await rn.open(n,"r");let h=await f.stat();if(h.size<=i)return;let g=h.size-i,v=Buffer.allocUnsafe(g),{bytesRead:b}=await f.read(v,0,g,i);if(b===0)return;i+=b,a+=v.toString("utf8",0,b);let E=a.split(`
1006
1006
  `);a=E.pop()??"";for(let w of E){let k=aS(w);if(k&&(k.kind==="closed"&&(c=!0),yield k,c))return}}catch(h){h.code!=="ENOENT"&&process.stderr.write(`[afk] session-ledger: tail read error for ${t}: ${String(h)}
1007
1007
  `)}finally{f&&await f.close().catch(()=>{})}}if(o){if(yield*l(),c)return}else try{i=(await rn.stat(n)).size}catch{}let d=null,u=null,p=()=>new Promise(f=>{let h=setTimeout(()=>{u=null,f()},cS);u=()=>{clearTimeout(h),u=null,f()},s?.addEventListener("abort",()=>{clearTimeout(h),u=null,f()},{once:!0})});try{d=nn.watch(r,{persistent:!1},()=>{u?.()})}catch{}try{for(;!s?.aborted&&!c&&(await p(),!s?.aborted);)yield*l()}finally{d?.close()}}var pu,uu,ut,cS,So=y(()=>{"use strict";K();pu=8e3,uu=400;ut=class{sessionId;ledgerPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;constructor(e){if(this.sessionId=e,!Cn(e)){this.errored=!0,this.ledgerPath="";return}this.ledgerPath=$r(e);try{nn.mkdirSync(Mn(e),{recursive:!0})}catch(n){process.stderr.write(`[afk] session-ledger: mkdir failed for ${e}: ${String(n)}
1008
1008
  `),this.errored=!0}}get active(){return!this.errored&&!this.closed}record(e){if(this.errored||this.closed)return;let n={v:1,ts:Date.now(),...e},r=JSON.stringify(n)+`
@@ -1011,7 +1011,7 @@ Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}
1011
1011
  `),this.errored=!0,this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null}}}_writeLine(e){if(!(!this.stream||this.errored))try{this.stream.write(e,n=>{n&&(process.stderr.write(`[afk] session-ledger: write error for ${this.sessionId}: ${String(n)}
1012
1012
  `),this.errored=!0)})}catch(n){process.stderr.write(`[afk] session-ledger: write threw for ${this.sessionId}: ${String(n)}
1013
1013
  `),this.errored=!0}}async close(e){if(!this.closed)return this.record({kind:"closed",...e!==void 0?{reason:e}:{}}),this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(n=>{if(!this.stream){n();return}this.stream.end(()=>n())})}};cS=250});import{mkdir as lS,writeFile as mu,unlink as _D,readdir as dS,readFile as gu}from"fs/promises";import{unlinkSync as uS,existsSync as pS}from"fs";import{join as hu}from"path";function Ji(t){return hu(Dr(),`${t}.json`)}async function fS(){try{return await lS(Dr(),{recursive:!0}),!0}catch{return!1}}async function Hn(t){try{if(!await fS())return;let n=Ji(t.sessionId);await mu(n,JSON.stringify(t,null,2),"utf8")}catch{}}async function yu(t,e){try{let n=Ji(t),r=await gu(n,"utf8"),o=JSON.parse(r);o.cwd=e,await mu(n,JSON.stringify(o,null,2),"utf8")}catch{}}function Ye(t){try{let e=Ji(t);pS(e)&&uS(e)}catch{}}async function jn(){let t=Dr(),e;try{e=await dS(t)}catch{return[]}let n=[];for(let r of e){if(!r.endsWith(".json"))continue;let o=hu(t,r);try{let s=await gu(o,"utf8"),i=JSON.parse(s);i!==null&&typeof i=="object"&&"sessionId"in i&&typeof i.sessionId=="string"&&n.push({...i,path:o})}catch{}}return n}var Kn=y(()=>{"use strict";K()});function bu(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 wu(t,e){let n=t.permissionMode??"default",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}}var vu=y(()=>{"use strict"});var ko,Su=y(()=>{"use strict";ko=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}}});function ku(t){try{let e=JSON.parse(t);if(!Array.isArray(e))return null;let n=e.length;if(n===0)return"no results";let r=0,o=0;for(let a of e)if(a&&typeof a=="object"){let c=a.type;c==="fact"?r++:c==="procedure"&&o++}let s=`${n} result${n===1?"":"s"}`;if(r+o!==n)return s;let i=[];return r>0&&i.push(`${r} fact${r===1?"":"s"}`),o>0&&i.push(`${o} procedure${o===1?"":"s"}`),i.length===0?s:`${s} (${i.join(", ")})`}catch{return null}}function _u(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;if(n.target==="hot"&&n.saved===!0){if(n.truncated===!0)return"hot memory saved (truncated to fit cap)";let r=n.usage;if(r&&typeof r=="object"){let o=r.pct;if(typeof o=="number")return`hot memory saved (${o}% of cap)`}return"hot memory saved"}if(n.target==="fact"){if(n.action==="remove")return n.removed===!0?"fact removed":"fact not found";if(n.action==="set"&&typeof n.id=="number")return`fact #${n.id} set`;if(n.action==="supersede"&&typeof n.id=="number"&&typeof n.supersedes=="number")return`fact #${n.id} supersedes #${n.supersedes}`}return null}catch{return null}}function Eu(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;return typeof n.name=="string"&&n.written===!0?`wrote procedure '${n.name}'`:null}catch{return null}}var Au=y(()=>{"use strict"});function Yi(t){let e=t.trim();if(e.length===0)return null;let n=e[0];if(n!=="{"&&n!=="[")return null;let r=e[e.length-1];if(n==="{"&&r!=="}"||n==="["&&r!=="]")return null;let o;try{o=JSON.parse(e)}catch{return null}return Array.isArray(o)?Tu(mS(o)):o!==null&&typeof o=="object"?Tu(gS(o)):null}function mS(t){return t.length===0?"[empty array]":t.length===1?"[1 item]":`[${t.length} items]`}function gS(t){let e=Object.keys(t);if(e.length===0)return"{empty object}";let n=e.slice(0,4),r=e.length>4?", \u2026":"";return`{${n.join(", ")}${r}}`}function Tu(t){return t.length<=80?t:t.slice(0,79)+"\u2026"}var xu=y(()=>{"use strict"});function _o(t){return t.replace(Ru,"").replace(hS," ").trim()}function Xe(t){return t.replace(Ru,"")}var Ru,hS,on=y(()=>{"use strict";Ru=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,hS=/[\x00-\x1F\x7F-\x9F]/g});function Pu(t,e){if(!t)return null;let n=yS.get(t);if(!n)return null;try{let r=n(e);if(r===null)return null;let o=_o(r);return o.length>0?o:null}catch{return null}}var yS,Iu=y(()=>{"use strict";Au();xu();on();yS=new Map([["memory_search",ku],["memory_update",_u],["procedure_write",Eu],["bash",Yi],["Bash",Yi]])});function bS(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 c=r;return i%1===0&&(c=String(Math.floor(i))),c+=o,{sizeLabel:c,sizeBytes:Math.round(a),absolutePath:s.trim()}}function wS(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 vS(t){let e=Buffer.byteLength(t,"utf8"),n=wS(e),r=t.split(`
1014
- `);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 SS(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),t.contextWindowTokens!==void 0&&(n.context_window_tokens=t.contextWindowTokens),{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 kS(t){let e=t.isError===!0?null:Pu(t.toolName,t.content),n=e!==null?{display:e}:{},r=bS(t.content);if(r)return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:`Output persisted (${r.sizeLabel}) \u2192 ${r.absolutePath}`,isError:t.isError===!0,persistedPath:r.absolutePath,sizeBytes:r.sizeBytes,sizeLabel:r.sizeLabel,...n}};let{content:o,lineCount:s,sizeBytes:i,sizeLabel:a}=vS(t.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:o,isError:t.isError===!0,sizeBytes:i,sizeLabel:a,...t.truncated===!0&&{truncated:!0},...s!==void 0&&{lineCount:s},...n}}}function Xi(t,e){switch(t.type){case"session.init":{let n=t.info;return e.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}:{}})),e.updateSessionIdentity(n.sessionId),e.resolveInitialization(),null}case"session.status":return e.setSessionMetadata(n=>({...n,sessionId:t.sessionId,...t.permissionMode!==void 0?{permissionMode:t.permissionMode}:{permissionMode:n.permissionMode},...t.status!==void 0?{status:t.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:t.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:t.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(t.sessionId&&e.updateSessionIdentity(t.sessionId),t.text){let n={role:"assistant",content:t.text,timestamp:new Date};return e.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:t.toolUseId,toolName:t.toolName,toolInput:t.toolInput,toolInputRaw:t.toolInputRaw}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:t.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:t.toolUseIds}}};case"tool.output":return kS(t);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:t.toolUseId,diff:t.diff}};case"progress":return{type:"progress",progress:{taskId:t.progress.taskId,description:t.progress.description,...t.progress.summary!==void 0?{summary:t.progress.summary}:{},...t.progress.lastToolName!==void 0?{lastToolName:t.progress.lastToolName}:{},totalTokens:t.progress.totalTokens,toolUses:t.progress.toolUses,durationMs:t.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:t.suggestion};case"turn.completed":{let n=SS(t.usage,t.sessionId??e.getSessionMetadata().sessionId);e.setLastResponseMetadata(n);for(let r=e.conversationHistory.length-1;r>=0;r--){let o=e.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(e.maxBudgetUsd!==void 0&&e.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(e._runningCostUsd=(e._runningCostUsd??0)+n.totalCostUsd,e._runningCostUsd>=e.maxBudgetUsd)){Xd(e.traceWriter,{kind:"monetary",runningCostUsd:e._runningCostUsd,maxBudgetUsd:e.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new zt(e._runningCostUsd,e.maxBudgetUsd);return e.abortBudget(r.message),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:t.error};case"paused":return{type:"paused",reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:t.hotSwapped,...t.accountId!==void 0?{accountId:t.accountId}:{}};case"stream.retry":return{type:"stream_retry"};default:return null}}var Cu=y(()=>{"use strict";ge();ee();Iu()});var Rt,Mu=y(()=>{"use strict";le();ge();ee();we();nu();tn();yo();iu();ge();cu();du();Gi();So();U();De();ct();Kn();Ve();qi();vu();Su();Cu();Rt=class{config;currentState="idle";providerQuery;providerIterator;conversationHistory=[];turnCount=0;lastResponseMetadata=null;initPromise=null;inputStream;abortController;_hookRegistry;sessionEndDispatched=!1;stateManager;sessionRunningCostUsd=0;sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};lastStopReason;maxTurnsHit=!1;hookBlocked=!1;sawProviderError=!1;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=null;ledgerInitAttempted=!1;constructor(e){this.config=e,this.abortController=new AbortController,this._hookRegistry=e.hookRegistry,bu(e.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(e.model);re(e.traceWriter,{phase:"session_init_start",model:n,resolvedModel:se(e.model)??n,origin:at(e.surface),actor:qr(e.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&ao(this.config.models),fo(this.config);let e=se(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=wu(this.config,e);this.stateManager=new ko(n,r),this.inputStream=new en(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)$(`\u{1F7E2} AgentSession: Creating query session via injected provider=${this.config.provider.name}`),this.providerQuery=this.config.provider.query({prompt:o,config:this.config});else{$("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>Ou(a);this.providerQuery=new mo({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>z(a),resolveApiKey:a=>Je(a)})}this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionRunningCostUsd=0,this.sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.lastStopReason=void 0,this.maxTurnsHit=!1,this.hookBlocked=!1,this.sawProviderError=!1,this.sessionEndDispatched=!1,this.currentState="idle",this.subagentCompletedCount=0,this.subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.subagentRunningCostUsd=0;let s=this.providerQuery;this.providerIterator=s[Symbol.asyncIterator](),this.initPromise=this.pullInitialization()}async pullInitialization(){try{for(await ou(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});;){let e=await this.providerIterator.next();if(e.done){this.stateManager.resolveInitializationIfNeeded();return}let n=e.value,r=Xi(n,this.buildTransformDeps());if(n.type==="session.init"){await re(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(r&&r.type==="error"){this.sawProviderError=!0;return}}}catch(e){let n=e instanceof Error?e:new Error(String(e));n instanceof J&&(this.hookBlocked=!0),this.stateManager.isInitializationSettled()||this.stateManager.rejectInitializationOnce(n),await this.dispatchSessionEndOnce("error").catch(()=>{})}}buildTransformDeps(){return{conversationHistory:this.conversationHistory,getSessionMetadata:()=>this.stateManager.getSessionMetadata(),setSessionMetadata:e=>this.stateManager.setSessionMetadata(e),updateSessionIdentity:e=>this.stateManager.updateSessionIdentity(e),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:e=>{this.lastResponseMetadata=e,typeof e.totalCostUsd=="number"&&Number.isFinite(e.totalCostUsd)&&(this.sessionRunningCostUsd+=e.totalCostUsd);let n=e.usage;if(n&&typeof n=="object"){let r=n,o=(s,i)=>{let a=r[s];typeof a=="number"&&Number.isFinite(a)&&(this.sessionRunningTokens[i]+=a)};o("input_tokens","input"),o("output_tokens","output"),o("cache_read_input_tokens","cacheRead"),o("cache_creation_input_tokens","cacheCreation")}typeof e.stopReason=="string"&&(this.lastStopReason=e.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:e=>{this.abortController.signal.aborted||this.abortController.abort(e)},...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}}}get state(){return this.currentState}get sessionId(){return this.stateManager.getSessionId()}get cwd(){return this.config.cwd}get abortSignal(){return this.abortController.signal}get hookRegistry(){return this._hookRegistry}abort(e){if(e==="closed"||e.startsWith("Budget ")||e.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${e}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(e)}async sendMessage(e,n={}){this.assertCanSend();let r=this.config.timeoutMs??go,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(e)){if(a.type==="chunk"&&a.chunk.type==="content"&&(i+=a.chunk.content),a.type==="message"&&a.message.role==="assistant"&&(s=a.message),a.type==="error")throw a.error;if(a.type==="done"){if(s)return{...s,metadata:a.metadata};if(i)return{role:"assistant",content:i,metadata:a.metadata,timestamp:new Date}}}if(s)return s;if(i)return{role:"assistant",content:i,timestamp:new Date};throw new Error("No assistant response received")};try{return await ho(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async*sendMessageStream(e){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(e)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(e){this.initPromise&&await this.initPromise;let n=typeof e=="string"?e:this.summarizeContentBlocks(e),r={role:"user",content:n,timestamp:new Date};this.conversationHistory.push(r),this.inputStream.pushUserMessage(e),this.ensureLedger(),this.ledger?.recordUser(n);let o=this.buildTransformDeps();try{for(;;){let s=await this.providerIterator.next();if(s.done)break;let i=s.value,a=Xi(i,o);if(a&&(a.type==="done"?(this.turnCount++,this.sawProviderError=!1):a.type==="error"&&(this.sawProviderError=!0),this.ledger?.recordEvent(a),yield a,a.type==="done"||a.type==="error"))break}}finally{this.currentState==="streaming"&&(this.currentState="idle")}}ensureLedger(){if(this.ledgerInitAttempted||(this.ledgerInitAttempted=!0,this.config.depth!==void 0||this.config.parentSessionId!==void 0)||S.AFK_SESSION_LEDGER_DISABLED==="1")return;let e=this.sessionId;if(!e)return;let n=new ut(e);if(!n.active)return;this.ledger=n;let r=this.getSessionMetadata();n.record({kind:"meta",sessionId:e,model:r.model??String(this.config.model),...r.cwd!==void 0?{cwd:r.cwd}:{}})}sealLedger(e){let n=this.ledger;return n?(this.ledger=null,this.ledgerInitAttempted=!1,n.close(e)):Promise.resolve()}recordLedgerElicitation(e,n){this.ledger?.record({kind:"elicitation",reqId:e,request:n})}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 me("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset"),await this.sealLedger("reset");try{await this.providerQuery.close()}catch{}await this.providerIterator.return?.(),this.initPromise&&await Promise.race([this.initPromise,new Promise(e=>setTimeout(e,zi))]).catch(()=>{}),this.stateManager.resolveInitializationIfNeeded(),this.config={...this.config},delete this.config.resume,delete this.config.sessionId,delete this.config.resumeHistory,delete this.config.resumeSessionAt,delete this.config.continue,delete this.config.forkSession;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(){this.sealLedger("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(e){let n=se(e);typeof e=="string"&&e.length>0&&await this.providerQuery.setModel(e),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(e){await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:e}))}setCwd(e){this.config={...this.config,cwd:e},this.providerQuery.setCwd?.(e),this.config.sessionId!==void 0&&yu(this.config.sessionId,e)}async reauth(){return await this.providerQuery.reauth?.()??null}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);if(!e)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await e()}finally{this.currentState="idle"}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){throw new Error("getOutputStream() is not supported \u2014 use sendMessageStream() instead")}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",await this.sealLedger("close"),this.abortController.signal.aborted||this.abortController.abort("closed"),this.stateManager.resolveInitializationIfNeeded();try{await this.providerQuery.close()}catch{}if(await this.providerIterator.return?.(),this.initPromise)try{await Promise.race([this.initPromise,new Promise(e=>setTimeout(e,zi))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(e).catch(()=>{}),await this.sealTraceWriter(e).catch(()=>{}),await su(this._hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:e,parentSessionId:this.config.parentSessionId,...this.config.traceWriter?{tracePath:this.config.traceWriter.getTracePath()}:{}},this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}))}async emitClosure(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveClosureReason(e),o={};this.sessionRunningTokens.input>0&&(o.input=this.sessionRunningTokens.input),this.sessionRunningTokens.output>0&&(o.output=this.sessionRunningTokens.output),this.sessionRunningTokens.cacheRead>0&&(o.cacheRead=this.sessionRunningTokens.cacheRead),this.sessionRunningTokens.cacheCreation>0&&(o.cacheCreation=this.sessionRunningTokens.cacheCreation);let s=lu(r);await eu(n,{reason:r,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,finalTokens:o,...this.lastStopReason!==void 0?{lastStopReason:this.lastStopReason}:{},...s!==null?{guidance:s}:{}})}deriveClosureReason(e){let n=null,r=this.abortController.signal;if(r.aborted&&r.reason!=="closed"){let o=r.reason;o instanceof zt?n="budget_exceeded":o instanceof Me?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return au({dispatchReason:e,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,abort:n,lastStopReason:this.lastStopReason,sawProviderError:this.sawProviderError})}async sealTraceWriter(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveSealStatus(e),o=this.subagentCompletedCount>0?this.subagentCompletedCount:void 0,s=this.subagentRunningTokens,a=s.input>0||s.output>0||s.cacheRead>0||s.cacheCreation>0?{...s.input>0?{input:s.input}:{},...s.output>0?{output:s.output}:{},...s.cacheRead>0?{cacheRead:s.cacheRead}:{},...s.cacheCreation>0?{cacheCreation:s.cacheCreation}:{}}:void 0,c=this.subagentRunningCostUsd>0?this.subagentRunningCostUsd:void 0;await n.seal({status:r,finalCostUsd:this.sessionRunningCostUsd,finalTurnCount:this.turnCount,closedAt:new Date().toISOString(),...o!==void 0?{subagentCount:o}:{},...a!==void 0?{subagentTokens:a}:{},...c!==void 0?{subagentCostUsd:c}:{}})}recordSubagentCompletion(e,n){if(this.subagentCompletedCount++,e){let r=(o,s)=>{typeof o=="number"&&Number.isFinite(o)&&o>0&&(this.subagentRunningTokens[s]+=o)};r(e.inputTokens,"input"),r(e.outputTokens,"output"),r(e.cacheReadTokens,"cacheRead"),r(e.cacheCreationTokens,"cacheCreation")}typeof n=="number"&&Number.isFinite(n)&&n>0&&(this.subagentRunningCostUsd+=n)}deriveSealStatus(e){if(e==="error")return"failed";let n=this.abortController.signal;return n.aborted&&n.reason!=="closed"?"cancelled":this.sawProviderError?"failed":"succeeded"}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new me("Cannot send message: session aborted");if(this.currentState==="processing"||this.currentState==="streaming"||this.currentState==="compacting")throw new Error("Cannot send message: session is busy");if(this.config.maxTurns&&this.turnCount>=this.config.maxTurns)throw this.maxTurnsHit=!0,new Error(`Maximum turns (${this.config.maxTurns}) exceeded`)}}});var Qi=y(()=>{"use strict";Mu()});function _S(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new Pt(n,e)))},e);i.unref(),Promise.resolve(t).then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}function ES(t){return t.continue===!1||t.decision==="block"}function Zi(t,e){if(t?.aborted){let n=t.reason,r=`aborted during ${e}${n?`: ${String(n)}`:""}`;throw new me(r)}}function Du(){return new ea}var It,Pt,ea,Eo=y(()=>{"use strict";ge();It=3e4;Pt=class extends Error{constructor(n,r){super(`hook handler timed out after ${r}ms during ${n}`);this.hookEvent=n;this.timeoutMs=r;this.name="HookHandlerTimeoutError"}hookEvent;timeoutMs;code="HOOK_HANDLER_TIMEOUT"},ea=class{handlers=new Map;register(e,n,r={}){let o=this.handlers.get(e);o||(o=[],this.handlers.set(e,o));let s={handler:n,options:r};return o.push(s),()=>{let i=this.handlers.get(e);if(!i)return;let a=i.indexOf(s);a>=0&&i.splice(a,1)}}count(e){return this.handlers.get(e)?.length??0}async dispatch(e,n,r=It){Zi(n,e.event);let o=this.handlers.get(e.event);if(!o||o.length===0)return{};let s=o.slice(),i={};for(let a of s){Zi(n,e.event);let c;try{let l=a.handler(e,n);c=!a.options.longRunning&&r>0&&Number.isFinite(r)?await _S(l,r,e.event):await l}catch(l){throw l instanceof Pt?l:new J(`hook handler threw during ${e.event}`,e.event,l instanceof Error?l.message:String(l),{cause:l})}if(Zi(n,e.event),ES(c))throw new J(`hook handler blocked ${e.event}${c.reason?`: ${c.reason}`:""}`,e.event,c.reason);i=c}return i}}});async function Ne(t,e,n,r){if(!t)return;if(r.kind==="blocked"){await Zt(t,{hookEvent:e,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...e==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await Zt(t,{hookEvent:e,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function Fu(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Ne(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof J&&await Ne(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function AS(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new Pt(n,e)))},e);i.unref(),t.then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}async function Lu(t,e,n={}){if(!t)return{};try{let r=await AS(t.dispatch(e,n.signal,It),It,"SubagentStop");return await Ne(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof Pt?(console.warn(`[afk] SubagentStop hook timed out after ${It}ms (subagentId=${e.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof J&&await Ne(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof J||r instanceof me?($(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):($(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function ta(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Ne(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){throw r instanceof J&&await Ne(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r}}async function Nu(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Ne(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof J&&await Ne(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof J||r instanceof me){$(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}$(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}async function $u(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Ne(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof J&&await Ne(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof J||r instanceof me){$(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}$(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var Ao=y(()=>{"use strict";le();ge();Eo();ee()});import{mkdir as TS,writeFile as xS}from"fs/promises";import{dirname as RS,join as PS}from"path";function IS(){return PS(Wt(),"routing-decisions.jsonl")}function CS(t){let e={surface:"afk"};for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}async function Z(t){if(!(S.VITEST||S.NODE_ENV==="test"))try{let e=IS();await TS(RS(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...CS(t)})+`
1014
+ `);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 SS(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),t.contextWindowTokens!==void 0&&(n.context_window_tokens=t.contextWindowTokens),{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 kS(t){let e=t.isError===!0?null:Pu(t.toolName,t.content),n=e!==null?{display:e}:{},r=bS(t.content);if(r)return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:`Output persisted (${r.sizeLabel}) \u2192 ${r.absolutePath}`,isError:t.isError===!0,persistedPath:r.absolutePath,sizeBytes:r.sizeBytes,sizeLabel:r.sizeLabel,...n}};let{content:o,lineCount:s,sizeBytes:i,sizeLabel:a}=vS(t.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:o,isError:t.isError===!0,sizeBytes:i,sizeLabel:a,...t.truncated===!0&&{truncated:!0},...s!==void 0&&{lineCount:s},...n}}}function Xi(t,e){switch(t.type){case"session.init":{let n=t.info;return e.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}:{}})),e.updateSessionIdentity(n.sessionId),e.resolveInitialization(),null}case"session.status":return e.setSessionMetadata(n=>({...n,sessionId:t.sessionId,...t.permissionMode!==void 0?{permissionMode:t.permissionMode}:{permissionMode:n.permissionMode},...t.status!==void 0?{status:t.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:t.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:t.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(t.sessionId&&e.updateSessionIdentity(t.sessionId),t.text){let n={role:"assistant",content:t.text,timestamp:new Date};return e.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:t.toolUseId,toolName:t.toolName,toolInput:t.toolInput,toolInputRaw:t.toolInputRaw}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:t.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:t.toolUseIds}}};case"tool.output":return kS(t);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:t.toolUseId,diff:t.diff}};case"progress":return{type:"progress",progress:{taskId:t.progress.taskId,description:t.progress.description,...t.progress.summary!==void 0?{summary:t.progress.summary}:{},...t.progress.lastToolName!==void 0?{lastToolName:t.progress.lastToolName}:{},totalTokens:t.progress.totalTokens,toolUses:t.progress.toolUses,durationMs:t.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:t.suggestion};case"turn.completed":{let n=SS(t.usage,t.sessionId??e.getSessionMetadata().sessionId);e.setLastResponseMetadata(n);for(let r=e.conversationHistory.length-1;r>=0;r--){let o=e.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(e.maxBudgetUsd!==void 0&&e.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(e._runningCostUsd=(e._runningCostUsd??0)+n.totalCostUsd,e._runningCostUsd>=e.maxBudgetUsd)){Xd(e.traceWriter,{kind:"monetary",runningCostUsd:e._runningCostUsd,maxBudgetUsd:e.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new zt(e._runningCostUsd,e.maxBudgetUsd);return e.abortBudget(r.message),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:t.error};case"paused":return{type:"paused",reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:t.hotSwapped,...t.accountId!==void 0?{accountId:t.accountId}:{}};case"stream.retry":return{type:"stream_retry"};default:return null}}var Cu=y(()=>{"use strict";ge();ee();Iu()});var Rt,Mu=y(()=>{"use strict";le();ge();ee();we();nu();tn();yo();iu();ge();cu();du();Gi();So();U();De();ct();Kn();Ve();qi();vu();Su();Cu();Rt=class{config;currentState="idle";providerQuery;providerIterator;conversationHistory=[];turnCount=0;lastResponseMetadata=null;initPromise=null;inputStream;abortController;_hookRegistry;sessionEndDispatched=!1;stateManager;sessionRunningCostUsd=0;sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};lastStopReason;maxTurnsHit=!1;hookBlocked=!1;sawProviderError=!1;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=null;ledgerInitAttempted=!1;constructor(e){this.config=e,this.abortController=new AbortController,this._hookRegistry=e.hookRegistry,bu(e.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(e.model);re(e.traceWriter,{phase:"session_init_start",model:n,resolvedModel:oe(e.model)??n,origin:at(e.surface),actor:qr(e.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&ao(this.config.models),fo(this.config);let e=oe(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=wu(this.config,e);this.stateManager=new ko(n,r),this.inputStream=new en(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)$(`\u{1F7E2} AgentSession: Creating query session via injected provider=${this.config.provider.name}`),this.providerQuery=this.config.provider.query({prompt:o,config:this.config});else{$("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>Ou(a);this.providerQuery=new mo({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>z(a),resolveApiKey:a=>Je(a)})}this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionRunningCostUsd=0,this.sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.lastStopReason=void 0,this.maxTurnsHit=!1,this.hookBlocked=!1,this.sawProviderError=!1,this.sessionEndDispatched=!1,this.currentState="idle",this.subagentCompletedCount=0,this.subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.subagentRunningCostUsd=0;let s=this.providerQuery;this.providerIterator=s[Symbol.asyncIterator](),this.initPromise=this.pullInitialization()}async pullInitialization(){try{for(await ou(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});;){let e=await this.providerIterator.next();if(e.done){this.stateManager.resolveInitializationIfNeeded();return}let n=e.value,r=Xi(n,this.buildTransformDeps());if(n.type==="session.init"){await re(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(r&&r.type==="error"){this.sawProviderError=!0;return}}}catch(e){let n=e instanceof Error?e:new Error(String(e));n instanceof J&&(this.hookBlocked=!0),this.stateManager.isInitializationSettled()||this.stateManager.rejectInitializationOnce(n),await this.dispatchSessionEndOnce("error").catch(()=>{})}}buildTransformDeps(){return{conversationHistory:this.conversationHistory,getSessionMetadata:()=>this.stateManager.getSessionMetadata(),setSessionMetadata:e=>this.stateManager.setSessionMetadata(e),updateSessionIdentity:e=>this.stateManager.updateSessionIdentity(e),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:e=>{this.lastResponseMetadata=e,typeof e.totalCostUsd=="number"&&Number.isFinite(e.totalCostUsd)&&(this.sessionRunningCostUsd+=e.totalCostUsd);let n=e.usage;if(n&&typeof n=="object"){let r=n,o=(s,i)=>{let a=r[s];typeof a=="number"&&Number.isFinite(a)&&(this.sessionRunningTokens[i]+=a)};o("input_tokens","input"),o("output_tokens","output"),o("cache_read_input_tokens","cacheRead"),o("cache_creation_input_tokens","cacheCreation")}typeof e.stopReason=="string"&&(this.lastStopReason=e.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:e=>{this.abortController.signal.aborted||this.abortController.abort(e)},...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}}}get state(){return this.currentState}get sessionId(){return this.stateManager.getSessionId()}get cwd(){return this.config.cwd}get abortSignal(){return this.abortController.signal}get hookRegistry(){return this._hookRegistry}abort(e){if(e==="closed"||e.startsWith("Budget ")||e.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${e}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(e)}async sendMessage(e,n={}){this.assertCanSend();let r=this.config.timeoutMs??go,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(e)){if(a.type==="chunk"&&a.chunk.type==="content"&&(i+=a.chunk.content),a.type==="message"&&a.message.role==="assistant"&&(s=a.message),a.type==="error")throw a.error;if(a.type==="done"){if(s)return{...s,metadata:a.metadata};if(i)return{role:"assistant",content:i,metadata:a.metadata,timestamp:new Date}}}if(s)return s;if(i)return{role:"assistant",content:i,timestamp:new Date};throw new Error("No assistant response received")};try{return await ho(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async*sendMessageStream(e){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(e)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(e){this.initPromise&&await this.initPromise;let n=typeof e=="string"?e:this.summarizeContentBlocks(e),r={role:"user",content:n,timestamp:new Date};this.conversationHistory.push(r),this.inputStream.pushUserMessage(e),this.ensureLedger(),this.ledger?.recordUser(n);let o=this.buildTransformDeps();try{for(;;){let s=await this.providerIterator.next();if(s.done)break;let i=s.value,a=Xi(i,o);if(a&&(a.type==="done"?(this.turnCount++,this.sawProviderError=!1):a.type==="error"&&(this.sawProviderError=!0),this.ledger?.recordEvent(a),yield a,a.type==="done"||a.type==="error"))break}}finally{this.currentState==="streaming"&&(this.currentState="idle")}}ensureLedger(){if(this.ledgerInitAttempted||(this.ledgerInitAttempted=!0,this.config.depth!==void 0||this.config.parentSessionId!==void 0)||S.AFK_SESSION_LEDGER_DISABLED==="1")return;let e=this.sessionId;if(!e)return;let n=new ut(e);if(!n.active)return;this.ledger=n;let r=this.getSessionMetadata();n.record({kind:"meta",sessionId:e,model:r.model??String(this.config.model),...r.cwd!==void 0?{cwd:r.cwd}:{}})}sealLedger(e){let n=this.ledger;return n?(this.ledger=null,this.ledgerInitAttempted=!1,n.close(e)):Promise.resolve()}recordLedgerElicitation(e,n){this.ledger?.record({kind:"elicitation",reqId:e,request:n})}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 me("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset"),await this.sealLedger("reset");try{await this.providerQuery.close()}catch{}await this.providerIterator.return?.(),this.initPromise&&await Promise.race([this.initPromise,new Promise(e=>setTimeout(e,zi))]).catch(()=>{}),this.stateManager.resolveInitializationIfNeeded(),this.config={...this.config},delete this.config.resume,delete this.config.sessionId,delete this.config.resumeHistory,delete this.config.resumeSessionAt,delete this.config.continue,delete this.config.forkSession;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(){this.sealLedger("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(e){let n=oe(e);typeof e=="string"&&e.length>0&&await this.providerQuery.setModel(e),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(e){await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:e}))}setCwd(e){this.config={...this.config,cwd:e},this.providerQuery.setCwd?.(e),this.config.sessionId!==void 0&&yu(this.config.sessionId,e)}async reauth(){return await this.providerQuery.reauth?.()??null}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);if(!e)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await e()}finally{this.currentState="idle"}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){throw new Error("getOutputStream() is not supported \u2014 use sendMessageStream() instead")}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",await this.sealLedger("close"),this.abortController.signal.aborted||this.abortController.abort("closed"),this.stateManager.resolveInitializationIfNeeded();try{await this.providerQuery.close()}catch{}if(await this.providerIterator.return?.(),this.initPromise)try{await Promise.race([this.initPromise,new Promise(e=>setTimeout(e,zi))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(e).catch(()=>{}),await this.sealTraceWriter(e).catch(()=>{}),await su(this._hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:e,parentSessionId:this.config.parentSessionId,...this.config.traceWriter?{tracePath:this.config.traceWriter.getTracePath()}:{}},this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}))}async emitClosure(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveClosureReason(e),o={};this.sessionRunningTokens.input>0&&(o.input=this.sessionRunningTokens.input),this.sessionRunningTokens.output>0&&(o.output=this.sessionRunningTokens.output),this.sessionRunningTokens.cacheRead>0&&(o.cacheRead=this.sessionRunningTokens.cacheRead),this.sessionRunningTokens.cacheCreation>0&&(o.cacheCreation=this.sessionRunningTokens.cacheCreation);let s=lu(r);await eu(n,{reason:r,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,finalTokens:o,...this.lastStopReason!==void 0?{lastStopReason:this.lastStopReason}:{},...s!==null?{guidance:s}:{}})}deriveClosureReason(e){let n=null,r=this.abortController.signal;if(r.aborted&&r.reason!=="closed"){let o=r.reason;o instanceof zt?n="budget_exceeded":o instanceof Me?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return au({dispatchReason:e,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,abort:n,lastStopReason:this.lastStopReason,sawProviderError:this.sawProviderError})}async sealTraceWriter(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveSealStatus(e),o=this.subagentCompletedCount>0?this.subagentCompletedCount:void 0,s=this.subagentRunningTokens,a=s.input>0||s.output>0||s.cacheRead>0||s.cacheCreation>0?{...s.input>0?{input:s.input}:{},...s.output>0?{output:s.output}:{},...s.cacheRead>0?{cacheRead:s.cacheRead}:{},...s.cacheCreation>0?{cacheCreation:s.cacheCreation}:{}}:void 0,c=this.subagentRunningCostUsd>0?this.subagentRunningCostUsd:void 0;await n.seal({status:r,finalCostUsd:this.sessionRunningCostUsd,finalTurnCount:this.turnCount,closedAt:new Date().toISOString(),...o!==void 0?{subagentCount:o}:{},...a!==void 0?{subagentTokens:a}:{},...c!==void 0?{subagentCostUsd:c}:{}})}recordSubagentCompletion(e,n){if(this.subagentCompletedCount++,e){let r=(o,s)=>{typeof o=="number"&&Number.isFinite(o)&&o>0&&(this.subagentRunningTokens[s]+=o)};r(e.inputTokens,"input"),r(e.outputTokens,"output"),r(e.cacheReadTokens,"cacheRead"),r(e.cacheCreationTokens,"cacheCreation")}typeof n=="number"&&Number.isFinite(n)&&n>0&&(this.subagentRunningCostUsd+=n)}deriveSealStatus(e){if(e==="error")return"failed";let n=this.abortController.signal;return n.aborted&&n.reason!=="closed"?"cancelled":this.sawProviderError?"failed":"succeeded"}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new me("Cannot send message: session aborted");if(this.currentState==="processing"||this.currentState==="streaming"||this.currentState==="compacting")throw new Error("Cannot send message: session is busy");if(this.config.maxTurns&&this.turnCount>=this.config.maxTurns)throw this.maxTurnsHit=!0,new Error(`Maximum turns (${this.config.maxTurns}) exceeded`)}}});var Qi=y(()=>{"use strict";Mu()});function _S(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new Pt(n,e)))},e);i.unref(),Promise.resolve(t).then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}function ES(t){return t.continue===!1||t.decision==="block"}function Zi(t,e){if(t?.aborted){let n=t.reason,r=`aborted during ${e}${n?`: ${String(n)}`:""}`;throw new me(r)}}function Du(){return new ea}var It,Pt,ea,Eo=y(()=>{"use strict";ge();It=3e4;Pt=class extends Error{constructor(n,r){super(`hook handler timed out after ${r}ms during ${n}`);this.hookEvent=n;this.timeoutMs=r;this.name="HookHandlerTimeoutError"}hookEvent;timeoutMs;code="HOOK_HANDLER_TIMEOUT"},ea=class{handlers=new Map;register(e,n,r={}){let o=this.handlers.get(e);o||(o=[],this.handlers.set(e,o));let s={handler:n,options:r};return o.push(s),()=>{let i=this.handlers.get(e);if(!i)return;let a=i.indexOf(s);a>=0&&i.splice(a,1)}}count(e){return this.handlers.get(e)?.length??0}async dispatch(e,n,r=It){Zi(n,e.event);let o=this.handlers.get(e.event);if(!o||o.length===0)return{};let s=o.slice(),i={};for(let a of s){Zi(n,e.event);let c;try{let l=a.handler(e,n);c=!a.options.longRunning&&r>0&&Number.isFinite(r)?await _S(l,r,e.event):await l}catch(l){throw l instanceof Pt?l:new J(`hook handler threw during ${e.event}`,e.event,l instanceof Error?l.message:String(l),{cause:l})}if(Zi(n,e.event),ES(c))throw new J(`hook handler blocked ${e.event}${c.reason?`: ${c.reason}`:""}`,e.event,c.reason);i=c}return i}}});async function Ne(t,e,n,r){if(!t)return;if(r.kind==="blocked"){await Zt(t,{hookEvent:e,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...e==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await Zt(t,{hookEvent:e,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function Fu(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Ne(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof J&&await Ne(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function AS(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new Pt(n,e)))},e);i.unref(),t.then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}async function Lu(t,e,n={}){if(!t)return{};try{let r=await AS(t.dispatch(e,n.signal,It),It,"SubagentStop");return await Ne(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof Pt?(console.warn(`[afk] SubagentStop hook timed out after ${It}ms (subagentId=${e.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof J&&await Ne(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof J||r instanceof me?($(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):($(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function ta(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Ne(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){throw r instanceof J&&await Ne(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r}}async function Nu(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Ne(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof J&&await Ne(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof J||r instanceof me){$(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}$(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}async function $u(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await Ne(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof J&&await Ne(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof J||r instanceof me){$(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}$(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var Ao=y(()=>{"use strict";le();ge();Eo();ee()});import{mkdir as TS,writeFile as xS}from"fs/promises";import{dirname as RS,join as PS}from"path";function IS(){return PS(Wt(),"routing-decisions.jsonl")}function CS(t){let e={surface:"afk"};for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}async function Z(t){if(!(S.VITEST||S.NODE_ENV==="test"))try{let e=IS();await TS(RS(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...CS(t)})+`
1015
1015
  `;await xS(e,r,{flag:"a"})}catch{}}var Qe=y(()=>{"use strict";U();K()});import{AsyncLocalStorage as MS}from"node:async_hooks";function Bu(t,e){return Uu.run(t,e)}function ve(){return Uu.getStore()}var Uu,Ct=y(()=>{"use strict";Uu=new MS});function Hu(){return Du()}function To(t,e){return t??e}var xo=y(()=>{"use strict";Eo()});function na(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:{allowed:!0}}function Ro(t,e){if(!t?.allowedTools||e.length===0)return t;let n=new Set(t.allowedTools),r=!1;for(let o of e)n.has(o)||(n.add(o),r=!0);return r?{...t,allowedTools:[...n]}:t}var Po=y(()=>{"use strict"});function gk(t){return t.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,e=>/\$\(|`/.test(e)?e:" ")}function Co(t){if(typeof t!="string"||t.trim().length===0)return{mutating:!1};let e=t.replace(US," ");for(let s of fk)if(s.re.test(e))return{mutating:!0,reason:s.reason};let n=t.match(ok)?.[1];if(n&&sk.test(n))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let r=gk(t);for(let s of mk)if(s.re.test(r))return{mutating:!0,reason:s.reason};let o=r.replace(uk," ").replace(dk," ").replace(/&(>>?)/g,"$1");return pk.test(o)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}var OS,DS,FS,LS,NS,$S,US,BS,HS,jS,KS,WS,GS,qS,VS,zS,JS,Io,YS,XS,QS,ZS,ek,tk,nk,rk,ok,sk,ik,ak,ck,lk,dk,uk,pk,fk,mk,ra=y(()=>{"use strict";OS=/\bgit\b[^|;&]*\s(commit|push|pull|merge|rebase|reset|checkout|switch|restore|cherry-pick|revert|am|apply|clean|add|rm|mv|init)\b/i,DS=/\bgit\b[^|;&]*\s+tag\s+-/i,FS=/\bgit\b[^|;&]*\s+branch\s+-[dDmM]\b/i,LS=/\bgit\b[^|;&]*\s+remote\s+(add|remove|rm|set-url|rename)\b/i,NS=/\bgit\b[^|;&]*\s+worktree\s+(remove|prune|move|lock|unlock)\b/i,$S=/\bgit\b[^|;&]*\s+stash\b(?!\s+(list|show)\b)/i,US=/\bstash@\{[^}]*\}/gi,BS=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,HS=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,jS=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,KS=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,WS=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,GS=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,qS=/\|\s*(sh|bash|zsh|dash)\b/i,VS=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,zS=/\bfind\b[^|;&]*\s-delete\b/i,JS=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,Io=String.raw`(?:^|[\n;|&(]|\$\()\s*`,YS=new RegExp(Io+String.raw`patch\b`,"i"),XS=new RegExp(Io+String.raw`install\b`,"i"),QS=new RegExp(Io+String.raw`(?:source\b|\.\s+\S)`,"i"),ZS=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,ek=new RegExp(Io+String.raw`unzip\b`,"i"),tk=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,nk=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,rk=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,ok=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,sk=/open\s*\([^)]*,\s*['"][wax]|writeFileSync|writeFile\b|appendFileSync|appendFile\b|createWriteStream|File\.(?:write|delete)\b|IO\.write\b|FileUtils\.|\bBun\.write\b|os\.remove\b|shutil\.\w|\.write_text\b|\.write_bytes\b/i,ik=/\b(npm|pnpm|yarn|pip|pip3|brew|cargo|go|apt|apt-get|gem|poetry|bundle|composer)\s+(install|add|remove|uninstall|i|ci|up|update|upgrade|dlx|get|require)\b/i,ak=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,ck=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,lk=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,dk=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,uk=/\$\(\(.*?\)\)/g,pk=/(?<![=<>-])>>?(?!&)/,fk=[{re:OS,reason:"git repository mutation"},{re:DS,reason:"git tag create/delete"},{re:FS,reason:"git branch delete/rename"},{re:LS,reason:"git remote mutation"},{re:$S,reason:"git stash mutation (only `stash list`/`stash show` allowed)"},{re:BS,reason:"git config write flag (only reads allowed)"},{re:HS,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:jS,reason:"gh write operation"},{re:KS,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:WS,reason:"gh api field payload (-f/-F/--field)"},{re:GS,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:NS,reason:"git worktree mutation (remove/prune/move)"},{re:nk,reason:"sed in-place edit (-i)"},{re:rk,reason:"perl in-place edit (-i)"},{re:ik,reason:"package install/modify"},{re:ak,reason:"curl/wget output-to-file"},{re:ck,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:lk,reason:"curl data/form payload"},{re:JS,reason:"find -exec with mutating verb"}],mk=[{re:qS,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:VS,reason:"filesystem mutation"},{re:zS,reason:"find -delete (file removal)"},{re:YS,reason:"patch (applies a diff to files)"},{re:XS,reason:"install (writes files)"},{re:QS,reason:"source/dot-source executes a script"},{re:ZS,reason:"tar create/extract/append/update (writes files/archive)"},{re:ek,reason:"unzip (writes files)"},{re:tk,reason:"cpio extract (-i mode writes files)"}]});var hk,yk,bk,wk,vk,Sk,kk,_k,Ek,Mt,Ot,Dt,Ak,Tk,xk,Rk,Pk,Ik,Ck,Mk,Ok,Dk,Fk,Lk,Nk,Ze,Ft,IF,pt=y(()=>{"use strict";hk={name:"bash",category:"shell",concurrencySafe:!1,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"]}},yk={name:"read_file",category:"read",concurrencySafe:!0,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"]}},bk={name:"write_file",category:"write",concurrencySafe:!1,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"]}},wk={name:"edit_file",category:"write",concurrencySafe:!1,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"]}},vk={name:"glob",category:"read",concurrencySafe:!0,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"]}},Sk={name:"grep",category:"read",concurrencySafe:!0,description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Runs `grep -rn` in basic-regex (BRE) mode by default, where `|` is a LITERAL pipe \u2014 not alternation; set extended: true for extended-regex (ERE) alternation. A no-match result on a pattern containing `|` is often a false negative \u2014 re-read the returned hint. 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 (BRE) by default: `|` `+` `?` `(` `)` `{` `}` are LITERAL characters. Set extended: true for extended regex (ERE) where `|` means alternation."},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.'},extended:{type:"boolean",description:"Use extended regex (ERE, `grep -E`) so `|` is alternation and `+ ? ( ) { }` are metacharacters. Default false (BRE \u2014 those characters match literally)."}},required:["pattern"]}},kk={name:"list_directory",category:"read",concurrencySafe:!0,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"]}},_k={name:"send_telegram",category:"web",concurrencySafe:!1,riskClass:"caution",description:"Send a Telegram message to the operator. Use to surface terminal-state notifications, blocking questions, or important status updates when the user is away from keyboard (AFK). The message is delivered through the same Telegram bot the operator uses to drive this session. By default the message goes to your primary chat (the first private chat in `AFK_TELEGRAM_ALLOWED_CHAT_IDS`, or `AFK_TELEGRAM_PRIMARY_CHAT_ID` if set); set `telegram.notify` in afk.config.json to broadcast to all allowed chats or target a custom set.\n\nPlain text only \u2014 Telegram's 4096-character limit per message is enforced. Returns an error if Telegram is not configured (missing `TELEGRAM_BOT_TOKEN` or empty allowlist) so the tool is safe to attempt unconditionally.\n\nUse sparingly: this is a real push notification to a human. Reserve for terminal states (Done/Blocked/Asking) and material progress, not running commentary. When running inside the Telegram bot, prefer replying normally \u2014 your response already reaches the operator through the bot. Use this tool only from CLI or daemon sessions.",input_schema:{type:"object",properties:{message:{type:"string",description:"Plain-text message body to send to the operator. Max 4096 characters (Telegram API limit). Must be non-empty."}},required:["message"]}},Ek={name:"web_scrape",category:"web",concurrencySafe:!0,description:'Scrape a web page or run a web search and return text content suitable for reasoning over. Three modes:\n\n- `markdown` (default): fetches the URL and extracts the main content as clean markdown (Readability + Turndown). Handles JS-rendered pages: if the plain fetch yields thin content, it escalates to a headless-browser render and re-extracts. Use this for articles, docs, blog posts, and most "I want to read this page" cases. No API key required (the render fallback needs the Playwright chromium binary \u2014 `pnpm exec playwright install chromium`).\n- `raw`: GETs the URL directly with no transformation. Use for JSON APIs, robots.txt, RSS, plain-text endpoints, or when you need the literal bytes. No API key required.\n- `search`: runs a web search and returns ranked markdown results. Use when you need to FIND a URL, not read one. Provide `query` instead of `url`. Requires `EXA_API_KEY` (free tier at https://exa.ai); the handler returns a clear error if it is unset.\n\nOutputs are capped at `max_bytes` UTF-8 bytes (default 1MB, ceiling 10MB) and the request is aborted after `timeout_ms` (default 30000, ceiling 120000).',input_schema:{type:"object",properties:{mode:{type:"string",enum:["markdown","raw","search"],description:'Fetch mode. Defaults to "markdown".'},url:{type:"string",description:"Absolute http(s) URL. Required for markdown and raw modes. Ignored in search mode."},query:{type:"string",description:"Search query string. Required for search mode. Ignored otherwise."},timeout_ms:{type:"number",description:"Request timeout in milliseconds (default 30000, clamped to 120000)."},max_bytes:{type:"number",description:"Maximum UTF-8 bytes returned. Content beyond this is truncated with a marker. Default 1000000, clamped to 10000000."}},required:[]}},Mt={name:"agent",category:"subagent",concurrencySafe:!0,description:`Dispatch an independent subagent with its own context window and tool access. Use for tasks that protect the main session's context: codebase exploration, multi-file inspection, repo search, verification, debugging, failing-test investigation, PR review, parallel hypothesis testing, independent re-derivation of a claim, audit work, stale-path detection, feature-wiring checks, and any research-shaped investigation.
1016
1016
 
1017
1017
  Parallelize: dispatch multiple \`agent\` calls in a single tool-use turn to run independent investigations concurrently.
@@ -1050,7 +1050,7 @@ Note: this search ran in basic-regex (BRE) mode, where '|' is a literal pipe \u2
1050
1050
  `)}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:a.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${i.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}}});function $o(t,e=()=>{}){let n=new Set;if(!t)return n;for(let r of t.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){e("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}function dp(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 Uo=y(()=>{"use strict"});var ba=y(()=>{"use strict";U();K()});var up=y(()=>{"use strict";U();ba()});import{execFile as W_}from"node:child_process";import{promisify as G_}from"node:util";function fp(t,e){if(t.length>pp)throw new Error(`Invalid branch prefix from ${e}: length ${t.length} exceeds ${pp}.`);if(!q_.test(t))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 only [A-Za-z0-9_-./] are allowed.`);if(t.startsWith("-"))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);return t}function mp(t,e){if(t.trim().length===0)throw new Error(`Invalid worktree base ref from ${e}: '' \u2014 base ref cannot be empty.`);if(t.startsWith("-"))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);if(t.includes("\0"))throw new Error(`Invalid worktree base ref from ${e}: contains a NUL byte.`);if(/\s/.test(t))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not contain whitespace.`)}var uN,q_,pp,gp=y(()=>{"use strict";U();ba();up();uN=G_(W_),q_=/^[A-Za-z0-9_\-./]*$/,pp=64});import{existsSync as Bo,readdirSync as mN,readFileSync as V_,realpathSync as gN,statSync as hN}from"fs";import{homedir as z_}from"os";import{join as ht}from"path";function va(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of hp){let r=t[n];if(r!==void 0){if(r===!0){e[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;e[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(e).length>0?e:void 0}function J_(){return[it(),Nr()]}function qn(t=J_()){for(let e of t)if(Bo(e))try{let n=JSON.parse(V_(e,"utf-8")),r=va(n.importFrom);if(r!==void 0)return r}catch{}}function Vn(t,e=z_()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!t)return n;for(let r of hp){let o=t[r];if(!o)continue;let s=wa[r];if(o.plugins)for(let i of s.pluginRoots(e))Bo(i)&&n.pluginRoots.push(i);if(o.skills){let i=`imported:${r}`;for(let a of s.skillRoots(e))Bo(a)&&n.skillRoots.push({dir:a,origin:i})}if(o.mcp){let i=Y_(s.mcpConfigCandidates(e));i&&n.mcpConfigs.push({source:i,format:s.mcpFormat})}}return n}function Y_(t){for(let e of t)if(Bo(e))return e;return null}var hp,wa,vN,Ho=y(()=>{"use strict";K();hp=["claude-code","codex"],wa={"claude-code":{label:"Claude Code",pluginRoots:t=>[ht(t,".claude","plugins")],skillRoots:t=>[ht(t,".claude","skills")],mcpConfigCandidates:t=>[ht(t,".claude","mcp.json"),ht(t,".claude",".mcp.json"),ht(t,".claude","claude-code","mcp.json")],mcpFormat:"json"},codex:{label:"Codex",pluginRoots:t=>[ht(t,".codex","plugins")],skillRoots:t=>[ht(t,".codex","skills")],mcpConfigCandidates:t=>[ht(t,".codex","config.toml")],mcpFormat:"toml"}},vN={"claude-code":wa["claude-code"].label,codex:wa.codex.label}});import{readFileSync as wp,existsSync as ka}from"fs";import{join as Jn}from"path";import{config as X_}from"dotenv";function _a(){return Vi()}function Z_(t){let e=t.trim();if(!e)return e;let n="/chat/completions";if(e.endsWith(n)){let r=e.slice(0,-n.length);return bp.has(e)||(bp.add(e),console.warn(`[afk] AFK_OPENAI_BASE_URL: stripped trailing "/chat/completions" \u2014 the OpenAI SDK appends it automatically.
1051
1051
  Effective base URL: ${r}`)),r}return e}function eE(){if(Sa!==void 0)return Sa;if(!yp){let o=[Jn(process.cwd(),".env"),kt(),Gl()];for(let s of o)ka(s)&&X_({path:s,override:!1});yp=!0}let t={},e=S.AFK_MODEL??S.CLAUDE_MODEL;if(e){let o=e.toLowerCase();t.model=Ni(o)?o:e}if(z(e)==="anthropic-direct"){let o=_a();o!==void 0&&(t.apiKey=o)}let r=S.AFK_LOCAL_BASE_URL;if(r&&r.length>0&&(t.baseUrl=r,t.apiKey=S.AFK_LOCAL_API_KEY||"local"),S.AFK_MAX_TOKENS&&(t.maxTokens=parseInt(S.AFK_MAX_TOKENS,10)),S.AFK_TEMPERATURE&&(t.temperature=parseFloat(S.AFK_TEMPERATURE)),S.AFK_SYSTEM_PROMPT&&(t.systemPrompt=S.AFK_SYSTEM_PROMPT),S.AFK_AUTO_ROUTING){let o=S.AFK_AUTO_ROUTING.toLowerCase()==="true";t.autoRouting={interactive:o,chat:o,telegram:o,daemon:o}}return S.AFK_OPENAI_BASE_URL&&(t.openaiBaseUrl=Z_(S.AFK_OPENAI_BASE_URL)),Sa=t,t}function vp(){if(dn!==void 0)return dn;let t=[Jn(process.cwd(),"afk.config.json"),it(),Nr()];for(let e of t)if(ka(e))try{let n=wp(e,"utf-8"),r=JSON.parse(n),o={},s=Dd(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=Ni(i)?i:r.model}if(typeof r.maxTokens=="number"&&(o.maxTokens=r.maxTokens),typeof r.temperature=="number"&&(o.temperature=r.temperature),r.systemPrompt&&(o.systemPrompt=r.systemPrompt),typeof r.permissionMode=="string"){let i=r.permissionMode;(i==="default"||i==="plan"||i==="autonomous"||i==="bypassPermissions")&&(o.permissionMode=i)}if(r.autoRouting&&typeof r.autoRouting=="object"){let i={};typeof r.autoRouting.interactive=="boolean"&&(i.interactive=r.autoRouting.interactive),typeof r.autoRouting.chat=="boolean"&&(i.chat=r.autoRouting.chat),typeof r.autoRouting.telegram=="boolean"&&(i.telegram=r.autoRouting.telegram),typeof r.autoRouting.daemon=="boolean"&&(i.daemon=r.autoRouting.daemon),o.autoRouting=i}if(r.daemon&&typeof r.daemon=="object"){let i={};typeof r.daemon.task=="string"&&(i.task=r.daemon.task),typeof r.daemon.taskId=="string"&&(i.taskId=r.daemon.taskId);let a=r.daemon.worktreePrune;a&&typeof a=="object"&&(i.worktreePrune={enabled:typeof a.enabled=="boolean"?a.enabled:!0,cron:typeof a.cron=="string"?a.cron:"0 4 * * *",maxAgeDaysClean:typeof a.maxAgeDaysClean=="number"?a.maxAgeDaysClean:14,maxAgeDaysDirty:typeof a.maxAgeDaysDirty=="number"?a.maxAgeDaysDirty:30,scope:typeof a.scope=="string"?a.scope:"all"}),o.daemon=i}if(r.telegram&&typeof r.telegram=="object"){let i={},a=r.telegram.notify;if(a&&typeof a=="object"){let c={};if((a.mode==="primary"||a.mode==="broadcast"||a.mode==="custom")&&(c.mode=a.mode),typeof a.primaryChatId=="number"&&Number.isFinite(a.primaryChatId)&&(c.primaryChatId=a.primaryChatId),Array.isArray(a.targets)){let l=a.targets.filter(d=>typeof d=="number"&&Number.isFinite(d));l.length>0&&(c.targets=l)}i.notify=c}typeof r.telegram.verifyDone=="boolean"&&(i.verifyDone=r.telegram.verifyDone),o.telegram=i}if(r.updatePolicy&&["notify","auto","off"].includes(r.updatePolicy)&&(o.updatePolicy=r.updatePolicy),typeof r.autoResumeOnUsageLimit=="boolean"&&(o.autoResumeOnUsageLimit=r.autoResumeOnUsageLimit),typeof r.bgSummaries=="boolean"&&(o.bgSummaries=r.bgSummaries),typeof r.maxSummaryCallsPerSession=="number"&&(o.maxSummaryCallsPerSession=Math.min(500,Math.max(1,r.maxSummaryCallsPerSession))),r.hooks!==null&&typeof r.hooks=="object"&&!Array.isArray(r.hooks)&&(o.hooks=r.hooks),typeof r.enableShellHooks=="boolean"&&(o.enableShellHooks=r.enableShellHooks),e!==Jn(process.cwd(),"afk.config.json")){let i=va(r.importFrom);i!==void 0&&(o.importFrom=i)}if(r.interactive&&typeof r.interactive=="object"){let i={};typeof r.interactive.worktreeAutoname=="boolean"&&(i.worktreeAutoname=r.interactive.worktreeAutoname),typeof r.interactive.worktreeBranchPrefix=="string"&&(i.worktreeBranchPrefix=fp(r.interactive.worktreeBranchPrefix,`${e}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(mp(r.interactive.worktreeBase,`${e}#/interactive/worktreeBase`),i.worktreeBase=r.interactive.worktreeBase),typeof r.interactive.suggestGhost=="boolean"&&(i.suggestGhost=r.interactive.suggestGhost),Object.keys(i).length>0&&(o.interactive=i)}return dn={config:o,sourcePath:e,modelsPartial:s},dn}catch(n){console.error(`Warning: Failed to parse ${e}:`,n)}return dn={config:{},sourcePath:void 0,modelsPartial:{}},dn}function tE(){if(un!==void 0)return un.value;let t=[Jn(process.cwd(),"AFK.md"),Jn(ce(),"AFK.md")];for(let e of t)if(ka(e))try{let n=wp(e,"utf-8").trim();if(n.length>0)return un={value:{content:n,path:e}},un.value}catch{}return un={value:null},un.value}function Sp(){return vp().config.telegram??{}}function Ea(t){let e=eE(),{config:n,sourcePath:r,modelsPartial:o}=vp(),s={...zn,...e,...n,...t},i;if(e.systemPrompt!==void 0)i="env:AFK_SYSTEM_PROMPT";else if(n.systemPrompt!==void 0&&r!==void 0)i=`file:${r}`;else if(s.systemPrompt===void 0){let l=tE();l!==null&&(s.systemPrompt=l.content,i=`afk-md:${l.path}`)}let a={model:s.model??zn.model,maxTokens:s.maxTokens??zn.maxTokens,temperature:s.temperature??zn.temperature,updatePolicy:s.updatePolicy??zn.updatePolicy,...s.apiKey!==void 0?{apiKey:s.apiKey}:{},...s.baseUrl!==void 0?{baseUrl:s.baseUrl}:{},...s.openaiBaseUrl!==void 0?{openaiBaseUrl:s.openaiBaseUrl}:{},...s.systemPrompt!==void 0?{systemPrompt:s.systemPrompt}:{},...i!==void 0?{systemPromptSource:i}:{},permissionMode:s.permissionMode??Q_,...s.autoRouting!==void 0?{autoRouting:s.autoRouting}:{},...s.daemon!==void 0?{daemon:s.daemon}:{},...s.telegram!==void 0?{telegram:s.telegram}:{},...s.bgSummaries!==void 0?{bgSummaries:s.bgSummaries}:{},...s.maxSummaryCallsPerSession!==void 0?{maxSummaryCallsPerSession:s.maxSummaryCallsPerSession}:{},...s.interactive!==void 0?{interactive:s.interactive}:{},...s.hooks!==void 0?{hooks:s.hooks}:{},...s.enableShellHooks!==void 0?{enableShellHooks:s.enableShellHooks}:{},...s.importFrom!==void 0?{importFrom:s.importFrom}:{}},c=t?.models??Di(o);if(ao(c),a.models=c,typeof a.model=="string"&&a.model.toLowerCase().startsWith("local-")&&(a.baseUrl===void 0||a.baseUrl.length===0))throw new Error(`Model '${a.model}' requires AFK_LOCAL_BASE_URL to be set (e.g. AFK_LOCAL_BASE_URL=http://127.0.0.1:8080). Point it at your local Anthropic-Messages-compatible server.`);return a}var zn,Q_,yp,Sa,bp,dn,un,jo=y(()=>{"use strict";De();Ve();we();K();tn();gp();U();Ho();zn={model:"sonnet",maxTokens:4096,temperature:1,updatePolicy:"notify"},Q_="bypassPermissions",yp=!1;bp=new Set});function nE(t,e){return e!==void 0&&Number.isFinite(e)&&e!==0?e:t.find(r=>r>0)??t[0]}function rE(t,e={}){let n=[...t],r=e.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let s=(e.targets??[]).filter(i=>typeof i=="number"&&Number.isFinite(i)&&i!==0);if(s.length>0)return[...new Set(s)]}let o=nE(n,e.primaryChatId);return o!==void 0?[o]:[]}function oE(t){if(!t)return;let e=t.trim();if(!/^-?\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)&&n!==0?n:void 0}function sE(t){if(!t)return;let e=t.trim().toLowerCase();return e==="primary"||e==="broadcast"||e==="custom"?e:void 0}function iE(){let t=Sp().notify??{},e=t.mode??sE(S.AFK_TELEGRAM_NOTIFY_MODE),n=t.primaryChatId??oE(S.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...e!==void 0?{mode:e}:{},...n!==void 0?{primaryChatId:n}:{},...t.targets!==void 0?{targets:t.targets}:{}}}function Ko(){let t=$o(S.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return rE(t,iE())}var Aa=y(()=>{"use strict";Uo();jo();U()});var _p={};ui(_p,{push:()=>pn,pushIfConfigured:()=>cE,pushMarkdown:()=>kp});async function pn(t){if(!t.token)throw new Error("push: token is required");if(t.chatId===""||t.chatId==null||t.chatId===0)throw new Error("push: chatId is required");let e=t.fetchImpl??fetch,r=`${t.apiBase??aE}/bot${t.token}/sendMessage`,o={chat_id:t.chatId,text:t.text.slice(0,4096)};t.parseMode&&(o.parse_mode=t.parseMode),t.replyMarkup&&(o.reply_markup=t.replyMarkup);let s=new AbortController,i=setTimeout(()=>s.abort(),1e4);try{let a=await e(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:s.signal});if(a.ok)return{ok:!0,status:a.status};let c;try{c=(await a.json()).description}catch{c=`HTTP ${a.status}`}return{ok:!1,status:a.status,...c!==void 0?{errorMessage:c}:{}}}catch(a){return{ok:!1,status:0,errorMessage:a instanceof Error?a.message:String(a)}}finally{clearTimeout(i)}}async function kp(t){let e=_t(t.text),n=ye(e),r={ok:!0,status:200};for(let o of n)if(r=await pn({...t,text:o,parseMode:"HTML"}),!r.ok)return r.status===400&&/can't parse entities/i.test(r.errorMessage??"")?pn({...t}):r;return r}async function cE(t,e={}){let n=S.TELEGRAM_BOT_TOKEN;if(!n)return null;let r=Ko();if(r.length===0)return null;let o=ye(t),s=[];for(let i of r)for(let a=0;a<o.length;a++){let c={token:n,chatId:i,text:o[a]??"",...e.replyMarkup!==void 0&&a===0?{replyMarkup:e.replyMarkup}:{},...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{}};s.push(e.markdown?await kp(c):await pn({...c,...e.parseMode!==void 0?{parseMode:e.parseMode}:{}}))}return s}var aE,Ta=y(()=>{"use strict";Aa();Ce();U();aE="https://api.telegram.org"});function lE(t=pn){return async(e,n)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let o=e.message;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>Ep)return{content:`Invalid input: message exceeds Telegram's ${Ep}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=S.TELEGRAM_BOT_TOKEN;if(!s)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let i=Ko();if(i.length===0)return{content:"Telegram is not configured: AFK_TELEGRAM_ALLOWED_CHAT_IDS is empty or unset. Add the operator chat ID(s) before using send_telegram.",isError:!0};let a=[];for(let c of i){let l=await t({token:s,chatId:c,text:o});l.ok||a.push(`chat ${c}: ${l.errorMessage??`HTTP ${l.status}`}`)}return a.length===i.length?{content:`Failed to send Telegram message to any chat. ${a.join("; ")}`,isError:!0}:a.length>0?{content:`Sent Telegram message to ${i.length-a.length}/${i.length} chat(s); ${a.length} failed: ${a.join("; ")}`}:{content:i.length===1?`Sent Telegram message to chat ${i[0]}.`:`Sent Telegram message to ${i.length} chats.`}}}var Ep,Ap,Tp=y(()=>{"use strict";U();Ta();Aa();Ep=4096;Ap=lE()});import{JSDOM as dE}from"jsdom";import{Readability as uE}from"@mozilla/readability";import pE from"turndown";function xp(t){return t.replace(/\n{3,}/g,`
1052
1052
 
1053
- `).trim()}function fE(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}function Pp(t,e){let r=new dE(t,{url:e}).window.document,o=(r.title??"").trim(),s=null;try{let l=r.cloneNode(!0);s=new uE(l).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let l=xp(xa.turndown(s.content)),d=(s.title??"").trim()||o,u=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:d,markdown:l,textLength:u,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",c=xp(xa.turndown(a));return{title:o,markdown:c,textLength:fE(i),usedFallback:!0}}var Rp,xa,Ip=y(()=>{"use strict";Rp=200,xa=new pE({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});xa.remove(["script","style","noscript","iframe"])});import{readFileSync as mE}from"node:fs";import{join as gE}from"path";function hE(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Cp(t,e){return hE(e).test(t)}function wE(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(yE.has(e))return!0;if(bE.has(e))return!1}return!1}function Mp(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function vE(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function SE(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function kE(t){try{return mE(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function _E(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return n}function Op(t){let e=t?.env??S,n=t?.readFileSync??kE,r=t?.surface??e.AGENT_SURFACE,o=wE(e.AFK_BROWSER_HEADLESS,r),s=Mp(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Mp(e.AFK_BROWSER_BLOCKED_DOMAINS),a=SE(e.AFK_BROWSER_DOM_SNAPSHOTS),c=vE(e.AFK_BROWSER_BACKEND),l={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null},d=e.AFK_BROWSER_CONFIG,u=d!==void 0&&d.trim()!==""?d.trim():gE(We(),"browser.json"),p=n(u);if(p===void 0)return l;let f;try{f=JSON.parse(p)}catch(g){throw new Error(`Failed to parse browser config at ${u}: ${String(g)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${u} must be a JSON object`);let h=_E(l,f);return h.configPath=u,h}function Ra(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(Cp(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Cp(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var yE,bE,Pa=y(()=>{"use strict";U();K();yE=new Set(["daemon","subagent","telegram","afk"]),bE=new Set(["repl","interactive","cli"])});import EE from"node:fs";import AE from"node:path";import{chromium as TE}from"playwright";function xE(){try{return"4.45.3"}catch{}try{let t=AE.resolve(import.meta.dirname,"../../../package.json"),e=EE.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var RE,Wo,Dp=y(()=>{"use strict";RE=xE(),Wo=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(e){this.config=e}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=TE.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,e}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,s),o}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),c=await i.content(),l=i.url(),d=a!==null?a.status():null;return{html:c,finalUrl:l,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${RE}`}}}});import{createHash as PE}from"crypto";function Ia(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of IE)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Fp(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&CE.test(t.label))}function Lp(t){return PE("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Np(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var IE,CE,Yn=y(()=>{"use strict";IE=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];CE=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as ME}from"node:crypto";function OE(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function DE(t,e,n){return`el_${ME("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function FE(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function $p(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Bp(t,e){let n=t.role??"",r=t.name??"";Up.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Bp(s,e)}async function LE(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Hp).catch(()=>[])}async function NE(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,h={role:l,name:c,disabled:p};u!==void 0&&(h.value=u),f!==void 0&&(h.checked=f),o.push(h)}return o},Hp).catch(()=>[])}function $E(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Go(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=$E(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=LE(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,h,g]=await Promise.all([i,a,c,l,d]),v,b=!1;u!==null?(v=[],Bp(u,v)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,v=(await NE(t)).filter(F=>Up.has(F.role??"")));let E=new Map;for(let x of p){let F=$p(x.name),O=E.get(F);(!O||O.bbox.w===0&&x.bbox.w>0)&&E.set(F,x)}let w=v.map(x=>({ax:x,dom:E.get($p(x.name??""))})),k=r?w:w.filter(x=>x.dom?x.dom.bbox.w>0||x.dom.bbox.h>0:!0);k.sort((x,F)=>{let O=x.dom?.bbox.y??0,L=F.dom?.bbox.y??0;if(O!==L)return O-L;let M=x.dom?.bbox.x??0,C=F.dom?.bbox.x??0;return M-C}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let _=k.slice(0,n).map((x,F)=>{let O=x.ax.role??"generic",L=x.ax.name??"",M=DE(O,L,F),C=x.dom?.bbox??{x:0,y:0,w:0,h:0},R=x.dom?.type??null,N=null;x.ax.value!==void 0&&x.ax.value!==null&&(N=String(x.ax.value)),x.ax.checked!==void 0&&(N=String(x.ax.checked)),Fp({role:O,kind:R})&&(N="[redacted]");let H={disabled:x.ax.disabled??!1};x.ax.checked!==void 0&&(H.checked=x.ax.checked===!0||x.ax.checked==="mixed"),x.ax.selected!==void 0&&(H.selected=x.ax.selected),x.ax.expanded!==void 0&&(H.expanded=x.ax.expanded);let j;x.dom?.testId?j=`[data-testid="${x.dom.testId}"]`:x.dom?.id&&(j=`#${x.dom.id}`);let Y={id:M,role:O,label:OE(L),kind:R,value:N,state:H,bbox:C};return j!==void 0&&(Y.selector=j),Y}),T="idle";try{let x=await t.evaluate(()=>document.readyState);x==="loading"?T="loading":x==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let P=FE(f),I=`obs_${e.observationCounter.toString(36)}`,D=new Date().toISOString();return{observationId:I,url:h,title:g,textSummary:P,interactive:_,status:{httpStatus:e.httpStatus??null,loadingState:T,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:D}}var Up,Hp,jp=y(()=>{"use strict";Yn();Up=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Hp="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Kp(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Ca(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Kp(t,s)))).filter(o=>o!==null)}async function UE(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Ma(t,e,n){switch(e.kind){case"element_id":return BE(t,e,n);case"selector":return HE(t,e);case"semantic":return jE(t,e)}}async function BE(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Ca(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function HE(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Ca(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function jE(t,e){return e.role!==void 0?KE(t,e.text,e.role):WE(t,e.text,e)}async function KE(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Ca(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function WE(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await UE(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let v=p[g];if(v===void 0)continue;let b=await Kp(v.locator,v.index);if(b!==null){let E=`${b.role}:${b.label}:${g}`,w=0;for(let k=0;k<E.length;k++)w=w*31+E.charCodeAt(k)>>>0;f.push({...b,id:`el_${w.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Wp=y(()=>{"use strict"});import{randomBytes as GE}from"crypto";import{mkdir as qE,stat as VE,writeFile as zE}from"fs/promises";import{join as Oa}from"path";import{gzip as JE}from"zlib";import{promisify as YE}from"util";function XE(t){return Oa(Lr(t),"browser")}function QE(t){return Oa(XE(t),"screenshots")}function ZE(){return new Date().toISOString().replace(/[:.]/g,"-")}function eA(){return GE(3).toString("hex")}async function Da(t,e,n){if(e.length>Gp)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Gp} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=QE(t);await qE(r,{recursive:!0});let o=`${ZE()}-${eA()}-${n}.png`,s=Oa(r,o);await zE(s,e);let{size:i}=await VE(s);return{path:s,bytes:i}}var b$,Gp,qp=y(()=>{"use strict";K();Yn();b$=YE(JE);Gp=5*1024*1024});var zp={};ui(zp,{PlaywrightProvider:()=>Fa});function Vp(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var Fa,Jp=y(()=>{"use strict";Dp();jp();Wp();Pa();Yn();qp();Fa=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Wo(e)}async open(e){let n=Ra(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(l){a=l}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let c=await Go(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,c.interactive,c.url,c.title,"browser_open"),a!==null)throw a;return c}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Go(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Ma(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Vp(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":{let g=Ia(e.value??"");await c.fill(e.value??"");break}case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(v){l=v}else l=g}let u=r.url();if(u!==s){let g=Ra(u,this.config);if(!g.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:g.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Go(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),h=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,h),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Ma(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Vp(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await Da(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Da(n,o,r);return s}catch{return null}}}});var Nt={};ui(Nt,{__resetBrowserRegistryForTests:()=>sA,browserProviderActive:()=>rA,closeBrowserProvider:()=>La,getBrowserProvider:()=>nA,peekBrowserProvider:()=>oA});function Yp(){Promise.resolve(La()).then(()=>{process.exit(130)})}function Xp(){Promise.resolve(La()).then(()=>{process.exit(143)})}function Qp(){Ue=null}function tA(){qo||(process.on("SIGINT",Yp),process.on("SIGTERM",Xp),process.on("exit",Qp),qo=!0)}function Zp(){qo&&(process.removeListener("SIGINT",Yp),process.removeListener("SIGTERM",Xp),process.removeListener("exit",Qp),qo=!1)}async function nA(t){return Ue!==null?Ue:(Lt!==null||(Lt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Jp(),zp)),n=Op(t),r=new e(n);return tA(),Ue=r,Lt=null,r})()),Lt)}async function La(){if(Ue===null)return;let t=Ue;Ue=null,Lt=null,Zp(),await t.shutdown()}function rA(){return Ue!==null}function oA(){return Ue}function sA(){Ue=null,Lt=null,Zp()}var Ue,Lt,qo,$t=y(()=>{"use strict";Pa();Ue=null,Lt=null,qo=!1});function ef(t,e){try{return Pp(t,e)}catch(n){return $("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function dA(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>($t(),Nt));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function tf(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??dA,o=null,s=t,i=null,a=null;try{let l=await n(t,{headers:lA,redirect:"follow",signal:e.signal});i=l.status,s=l.url||t;let d=l.headers.get("content-type")??"";if(l.ok){if(cA.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await l.text();if(aA.test(d)&&!iA.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};o=ef(u,s)}}catch(l){if(e.signal.aborted||l instanceof Error&&l.message.startsWith("web_scrape markdown mode received binary"))throw l;a=l}if(!(o===null||o.textLength<Rp)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let l=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=ef(l.html,l.finalUrl);if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:l.finalUrl,usedRender:!0}}catch(l){if(e.signal.aborted)throw l;if(o===null){let d=l instanceof Error?l.message:String(l),u=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${t}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=l,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${i??"error"}).`)}var iA,aA,cA,lA,nf=y(()=>{"use strict";Ip();le();iA=/(text\/html|application\/xhtml\+xml)/i,aA=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,cA=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,lA={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function fA(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(uA,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),pA),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=_o(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function rf(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?fA({apiKey:t.exaApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function of(t,e){if(e.length===0)return`# Search results for "${t}"
1053
+ `).trim()}function fE(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}function Pp(t,e){let r=new dE(t,{url:e}).window.document,o=(r.title??"").trim(),s=null;try{let l=r.cloneNode(!0);s=new uE(l).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let l=xp(xa.turndown(s.content)),d=(s.title??"").trim()||o,u=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:d,markdown:l,textLength:u,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",c=xp(xa.turndown(a));return{title:o,markdown:c,textLength:fE(i),usedFallback:!0}}var Rp,xa,Ip=y(()=>{"use strict";Rp=200,xa=new pE({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});xa.remove(["script","style","noscript","iframe"])});import{readFileSync as mE}from"node:fs";import{join as gE}from"path";function hE(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Cp(t,e){return hE(e).test(t)}function wE(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(yE.has(e))return!0;if(bE.has(e))return!1}return!1}function Mp(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function vE(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function SE(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function kE(t){try{return mE(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function _E(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return n}function Op(t){let e=t?.env??S,n=t?.readFileSync??kE,r=t?.surface??e.AGENT_SURFACE,o=wE(e.AFK_BROWSER_HEADLESS,r),s=Mp(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Mp(e.AFK_BROWSER_BLOCKED_DOMAINS),a=SE(e.AFK_BROWSER_DOM_SNAPSHOTS),c=vE(e.AFK_BROWSER_BACKEND),l={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null},d=e.AFK_BROWSER_CONFIG,u=d!==void 0&&d.trim()!==""?d.trim():gE(We(),"browser.json"),p=n(u);if(p===void 0)return l;let f;try{f=JSON.parse(p)}catch(g){throw new Error(`Failed to parse browser config at ${u}: ${String(g)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${u} must be a JSON object`);let h=_E(l,f);return h.configPath=u,h}function Ra(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(Cp(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Cp(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var yE,bE,Pa=y(()=>{"use strict";U();K();yE=new Set(["daemon","subagent","telegram","afk"]),bE=new Set(["repl","interactive","cli"])});import EE from"node:fs";import AE from"node:path";import{chromium as TE}from"playwright";function xE(){try{return"4.45.5"}catch{}try{let t=AE.resolve(import.meta.dirname,"../../../package.json"),e=EE.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var RE,Wo,Dp=y(()=>{"use strict";RE=xE(),Wo=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(e){this.config=e}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=TE.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,e}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,s),o}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),c=await i.content(),l=i.url(),d=a!==null?a.status():null;return{html:c,finalUrl:l,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${RE}`}}}});import{createHash as PE}from"crypto";function Ia(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of IE)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Fp(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&CE.test(t.label))}function Lp(t){return PE("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Np(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var IE,CE,Yn=y(()=>{"use strict";IE=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];CE=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as ME}from"node:crypto";function OE(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function DE(t,e,n){return`el_${ME("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function FE(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function $p(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Bp(t,e){let n=t.role??"",r=t.name??"";Up.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Bp(s,e)}async function LE(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Hp).catch(()=>[])}async function NE(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,h={role:l,name:c,disabled:p};u!==void 0&&(h.value=u),f!==void 0&&(h.checked=f),o.push(h)}return o},Hp).catch(()=>[])}function $E(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Go(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=$E(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=LE(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,h,g]=await Promise.all([i,a,c,l,d]),v,b=!1;u!==null?(v=[],Bp(u,v)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,v=(await NE(t)).filter(F=>Up.has(F.role??"")));let E=new Map;for(let x of p){let F=$p(x.name),O=E.get(F);(!O||O.bbox.w===0&&x.bbox.w>0)&&E.set(F,x)}let w=v.map(x=>({ax:x,dom:E.get($p(x.name??""))})),k=r?w:w.filter(x=>x.dom?x.dom.bbox.w>0||x.dom.bbox.h>0:!0);k.sort((x,F)=>{let O=x.dom?.bbox.y??0,L=F.dom?.bbox.y??0;if(O!==L)return O-L;let M=x.dom?.bbox.x??0,C=F.dom?.bbox.x??0;return M-C}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let _=k.slice(0,n).map((x,F)=>{let O=x.ax.role??"generic",L=x.ax.name??"",M=DE(O,L,F),C=x.dom?.bbox??{x:0,y:0,w:0,h:0},R=x.dom?.type??null,N=null;x.ax.value!==void 0&&x.ax.value!==null&&(N=String(x.ax.value)),x.ax.checked!==void 0&&(N=String(x.ax.checked)),Fp({role:O,kind:R})&&(N="[redacted]");let H={disabled:x.ax.disabled??!1};x.ax.checked!==void 0&&(H.checked=x.ax.checked===!0||x.ax.checked==="mixed"),x.ax.selected!==void 0&&(H.selected=x.ax.selected),x.ax.expanded!==void 0&&(H.expanded=x.ax.expanded);let j;x.dom?.testId?j=`[data-testid="${x.dom.testId}"]`:x.dom?.id&&(j=`#${x.dom.id}`);let Y={id:M,role:O,label:OE(L),kind:R,value:N,state:H,bbox:C};return j!==void 0&&(Y.selector=j),Y}),T="idle";try{let x=await t.evaluate(()=>document.readyState);x==="loading"?T="loading":x==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let P=FE(f),I=`obs_${e.observationCounter.toString(36)}`,D=new Date().toISOString();return{observationId:I,url:h,title:g,textSummary:P,interactive:_,status:{httpStatus:e.httpStatus??null,loadingState:T,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:D}}var Up,Hp,jp=y(()=>{"use strict";Yn();Up=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Hp="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Kp(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Ca(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Kp(t,s)))).filter(o=>o!==null)}async function UE(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Ma(t,e,n){switch(e.kind){case"element_id":return BE(t,e,n);case"selector":return HE(t,e);case"semantic":return jE(t,e)}}async function BE(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Ca(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function HE(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Ca(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function jE(t,e){return e.role!==void 0?KE(t,e.text,e.role):WE(t,e.text,e)}async function KE(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Ca(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function WE(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await UE(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let v=p[g];if(v===void 0)continue;let b=await Kp(v.locator,v.index);if(b!==null){let E=`${b.role}:${b.label}:${g}`,w=0;for(let k=0;k<E.length;k++)w=w*31+E.charCodeAt(k)>>>0;f.push({...b,id:`el_${w.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Wp=y(()=>{"use strict"});import{randomBytes as GE}from"crypto";import{mkdir as qE,stat as VE,writeFile as zE}from"fs/promises";import{join as Oa}from"path";import{gzip as JE}from"zlib";import{promisify as YE}from"util";function XE(t){return Oa(Lr(t),"browser")}function QE(t){return Oa(XE(t),"screenshots")}function ZE(){return new Date().toISOString().replace(/[:.]/g,"-")}function eA(){return GE(3).toString("hex")}async function Da(t,e,n){if(e.length>Gp)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Gp} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=QE(t);await qE(r,{recursive:!0});let o=`${ZE()}-${eA()}-${n}.png`,s=Oa(r,o);await zE(s,e);let{size:i}=await VE(s);return{path:s,bytes:i}}var b$,Gp,qp=y(()=>{"use strict";K();Yn();b$=YE(JE);Gp=5*1024*1024});var zp={};ui(zp,{PlaywrightProvider:()=>Fa});function Vp(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var Fa,Jp=y(()=>{"use strict";Dp();jp();Wp();Pa();Yn();qp();Fa=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Wo(e)}async open(e){let n=Ra(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(l){a=l}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let c=await Go(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,c.interactive,c.url,c.title,"browser_open"),a!==null)throw a;return c}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Go(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await Ma(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Vp(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":{let g=Ia(e.value??"");await c.fill(e.value??"");break}case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(v){l=v}else l=g}let u=r.url();if(u!==s){let g=Ra(u,this.config);if(!g.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:g.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Go(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),h=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,h),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Ma(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Vp(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await Da(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Da(n,o,r);return s}catch{return null}}}});var Nt={};ui(Nt,{__resetBrowserRegistryForTests:()=>sA,browserProviderActive:()=>rA,closeBrowserProvider:()=>La,getBrowserProvider:()=>nA,peekBrowserProvider:()=>oA});function Yp(){Promise.resolve(La()).then(()=>{process.exit(130)})}function Xp(){Promise.resolve(La()).then(()=>{process.exit(143)})}function Qp(){Ue=null}function tA(){qo||(process.on("SIGINT",Yp),process.on("SIGTERM",Xp),process.on("exit",Qp),qo=!0)}function Zp(){qo&&(process.removeListener("SIGINT",Yp),process.removeListener("SIGTERM",Xp),process.removeListener("exit",Qp),qo=!1)}async function nA(t){return Ue!==null?Ue:(Lt!==null||(Lt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Jp(),zp)),n=Op(t),r=new e(n);return tA(),Ue=r,Lt=null,r})()),Lt)}async function La(){if(Ue===null)return;let t=Ue;Ue=null,Lt=null,Zp(),await t.shutdown()}function rA(){return Ue!==null}function oA(){return Ue}function sA(){Ue=null,Lt=null,Zp()}var Ue,Lt,qo,$t=y(()=>{"use strict";Pa();Ue=null,Lt=null,qo=!1});function ef(t,e){try{return Pp(t,e)}catch(n){return $("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function dA(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>($t(),Nt));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function tf(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??dA,o=null,s=t,i=null,a=null;try{let l=await n(t,{headers:lA,redirect:"follow",signal:e.signal});i=l.status,s=l.url||t;let d=l.headers.get("content-type")??"";if(l.ok){if(cA.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await l.text();if(aA.test(d)&&!iA.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};o=ef(u,s)}}catch(l){if(e.signal.aborted||l instanceof Error&&l.message.startsWith("web_scrape markdown mode received binary"))throw l;a=l}if(!(o===null||o.textLength<Rp)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let l=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=ef(l.html,l.finalUrl);if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:l.finalUrl,usedRender:!0}}catch(l){if(e.signal.aborted)throw l;if(o===null){let d=l instanceof Error?l.message:String(l),u=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${t}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=l,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${i??"error"}).`)}var iA,aA,cA,lA,nf=y(()=>{"use strict";Ip();le();iA=/(text\/html|application\/xhtml\+xml)/i,aA=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,cA=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,lA={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function fA(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(uA,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),pA),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=_o(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function rf(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?fA({apiKey:t.exaApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function of(t,e){if(e.length===0)return`# Search results for "${t}"
1054
1054
 
1055
1055
  (no results)`;let n=[`# Search results for "${t}"`,""];return e.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
1056
1056
  `).trimEnd()}var uA,pA,sf=y(()=>{"use strict";on();uA="https://api.exa.ai/search",pA=10});function SA(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=mA;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,gA)}let a=hA;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,yA)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Na(t,e){let n=Buffer.from(t,"utf8");return n.byteLength<=e?t:n.subarray(0,e).toString("utf8")+bA}function kA(t){let e=[],n=t;for(let o=0;o<4&&n instanceof Error;o++)e.push(n.message),n=n.cause;let r=e.join(" | ");return vA.some(o=>r.includes(o))}function _A(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;return async(r,o)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=SA(r);if("error"in s)return{content:s.error,isError:!0};if(o.aborted){let d=o.reason;return{content:`web_scrape aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let i=new AbortController,a=()=>{i.abort(o.reason)},c,l=()=>{let d=i.signal.reason;return d instanceof Error?d.message:String(d??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),c=setTimeout(()=>{i.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.mode==="raw"){let u;try{u=await e(s.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:i.signal})}catch(f){return i.signal.aborted?{content:`web_scrape aborted: ${l()}`,isError:!0}:{content:`web_scrape network error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}if(!u.ok)return{content:`web_scrape HTTP ${u.status} ${u.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let p;try{p=await u.text()}catch(f){return{content:`web_scrape read error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}return{content:Na(p,s.maxBytes)}}if(s.mode==="markdown")try{let u=await tf(s.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:s.timeoutMs,signal:i.signal});return u.markdown.trim().length===0?{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0}:{content:Na(u.markdown,s.maxBytes)}}catch(u){if(i.signal.aborted)return{content:`web_scrape aborted: ${l()}`,isError:!0};let p=u instanceof Error?u.message:String(u),f=kA(u)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${p}${f}`,isError:!0}}let d=rf({exaApiKey:n.EXA_API_KEY,fetchFn:e});if("error"in d)return{content:d.error,isError:!0};try{let u=await d.search(s.query,{limit:wA,timeoutMs:s.timeoutMs,signal:i.signal});return{content:Na(of(s.query,u),s.maxBytes)}}catch(u){return i.signal.aborted?{content:`web_scrape aborted: ${l()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${u instanceof Error?u.message:String(u)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),o.removeEventListener("abort",a)}}}var mA,gA,hA,yA,bA,wA,vA,af,cf=y(()=>{"use strict";nf();sf();mA=3e4,gA=12e4,hA=1e6,yA=1e7,bA=`
@@ -1078,15 +1078,15 @@ ${s}`:s}function bm(t,e){if(typeof t=="string")return t;if(!e.vision)return ym(t
1078
1078
  ${o}`:o}function DT(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 wm(t){let e=[],n=DT(t.config);if(n!==void 0&&e.push({role:"system",content:n}),t.resumeHistory)for(let r of t.resumeHistory)r.user&&e.push({role:"user",content:r.user}),r.assistant&&e.push({role:"assistant",content:r.assistant});if(t.priorTurns)for(let r of t.priorTurns)e.push(r);return t.currentUserText!==void 0&&e.push({role:"user",content:t.currentUserText}),t.vision===!1?e.map(r=>Array.isArray(r.content)?{...r,content:OT(r.content)}:r):e}var vm=y(()=>{"use strict"});function NT(){let t=S.AFK_VISION_MODELS,e=[],n=[];if(t)for(let r of t.split(",")){let o=r.trim().toLowerCase();if(o)if(o.startsWith("!")){let s=o.slice(1).trim();s&&n.push(s)}else e.push(o)}return{enable:e,disable:n}}function Sm(t,e){return t===e||t.includes(e)}function km(t){if(!t)return!1;let e=(Tt(t)??t).trim();if(!e)return!1;let n=e.toLowerCase(),{enable:r,disable:o}=NT();return o.some(s=>Sm(n,s))?!1:r.some(s=>Sm(n,s))||FT.has(n)?!0:LT.some(s=>s.test(e))}var FT,LT,_m=y(()=>{"use strict";U();Ve();FT=new Set(["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4-turbo","o1","o3","o4-mini"]),LT=[/^claude-/i,/^gpt-4o/i,/^gpt-4\.1/i,/^gpt-4-turbo/i,/^gpt-4-vision/i,/^gpt-5/i,/(?:^|[/_-])(?:vl|vlm)(?:[/_.-]|$)/i,/(?:^|[/_-])(?:llava|pixtral|internvl|cogvlm|idefics|moondream|janus)/i,/(?:vision|minicpm-?[vo]|qwen[\d.]*-?vl|llama-?3\.2-\d+b-vision|gemma-3|phi-3\.5-vision|phi-4-multimodal)/i]});function sc(){return{assistantText:"",reasoningText:"",toolCallsByIndex:new Map,finishReason:null,usage:null,model:null,id:null}}function*Em(t,e,n){t.id&&!e.id&&(e.id=t.id),t.model&&!e.model&&(e.model=t.model),t.usage&&(e.usage=t.usage);let r=t.choices?.[0];if(!r)return;r.finish_reason&&(e.finishReason=r.finish_reason);let o=r.delta;if(!o)return;let s=o.reasoning_content??o.reasoning;if(typeof s=="string"&&s.length>0&&(e.reasoningText+=s,yield{type:"delta.reasoning",text:s,sessionId:n}),typeof o.content=="string"&&o.content.length>0&&(e.assistantText+=o.content,yield{type:"delta.text",text:o.content,sessionId:n}),o.tool_calls&&o.tool_calls.length>0)for(let i of o.tool_calls){let a=e.toolCallsByIndex.get(i.index)??{index:i.index,id:"",name:"",argumentsRaw:"",startEmitted:!1};i.id&&(a.id=i.id),i.function?.name&&(a.name=i.function.name),i.function?.arguments&&(a.argumentsRaw+=i.function.arguments),e.toolCallsByIndex.set(i.index,a)}}function Am(t){let e=t.usage;if(!e)return{stopReason:t.finishReason??null,resultSubtype:"success",isError:!1};let n=e.prompt_tokens_details?.cached_tokens??0,r=e.prompt_tokens??0,o=e.completion_tokens??0;return{inputTokens:r,outputTokens:o,cachedInputTokens:n,totalTokens:e.total_tokens??r+o,stopReason:t.finishReason??null,resultSubtype:"success",isError:!1,raw:{...e}}}function ic(t){return[...t.toolCallsByIndex.values()].sort((e,n)=>e.index-n.index)}function ac(t){return t.finishReason==="tool_calls"||t.finishReason==="function_call"?!0:t.finishReason!==null||t.toolCallsByIndex.size===0?!1:[...t.toolCallsByIndex.values()].every(e=>e.id.length>0&&e.name.length>0)}var Tm=y(()=>{"use strict"});function xm(t){return t.map(e=>{let n={name:e.name,parameters:e.input_schema};return e.description!==void 0&&(n.description=e.description),{type:"function",function:n}})}function Rm(t,e){let n=[],r=new Map;for(let o of t){let s={};if(o.argumentsRaw.length>0)try{s=JSON.parse(o.argumentsRaw)}catch(i){let a=i instanceof Error?i.message:String(i);r.set(o.id,`Failed to parse tool arguments as JSON: ${a}`),s={}}n.push({id:o.id,name:o.name,input:s,signal:e})}return{calls:n,parseErrors:r}}function Pm(t,e,n=""){let r={role:"assistant",content:t.length>0?t:null,tool_calls:e.map(o=>({id:o.id,type:"function",function:{name:o.name,arguments:o.argumentsRaw}}))};return n.length>0&&(r.reasoning_content=n),r}function Im(t){return t.map(({call:e,result:n})=>({role:"tool",tool_call_id:e.id,content:n.isError?`[error] ${n.content}`:n.content}))}function Cm(t,e){if(!e.vision)return;let n=[],r=[];for(let{call:s,result:i}of t)i.image&&(n.push({type:"image_url",image_url:{url:`data:${i.image.mediaType};base64,${i.image.data}`}}),r.push(s.name));return n.length===0?void 0:{role:"user",content:[{type:"text",text:r.length===1?`Image output from the \`${r[0]}\` tool call (referenced above):`:`Image output from ${r.length} tool calls (${r.join(", ")}):`},...n]}}var Mm=y(()=>{"use strict"});function*Om(t,e,n){switch(t.type){case"response.output_text.delta":{typeof t.delta=="string"&&t.delta.length>0&&(e.assistantText+=t.delta,yield{type:"delta.text",text:t.delta,sessionId:n});return}case"response.reasoning_text.delta":case"response.reasoning_summary_text.delta":{typeof t.delta=="string"&&t.delta.length>0&&(e.reasoningText+=t.delta,yield{type:"delta.reasoning",text:t.delta,sessionId:n});return}case"response.output_item.added":{let r=t.item;if(r?.type==="function_call"&&typeof t.output_index=="number"){let o=e.toolCallsByIndex.get(t.output_index),s=o?.argumentsRaw??"";e.toolCallsByIndex.set(t.output_index,{index:t.output_index,id:r.call_id??o?.id??"",name:r.name??o?.name??"",argumentsRaw:s.length>0?s:r.arguments??"",startEmitted:o?.startEmitted??!1})}return}case"response.function_call_arguments.delta":{if(typeof t.output_index=="number"&&typeof t.delta=="string"){let r=e.toolCallsByIndex.get(t.output_index)??{index:t.output_index,id:"",name:"",argumentsRaw:"",startEmitted:!1};r.argumentsRaw+=t.delta,e.toolCallsByIndex.set(t.output_index,r)}return}case"response.completed":{cc(e,t),e.finishReason=e.toolCallsByIndex.size>0?"tool_calls":"stop";return}case"response.incomplete":{cc(e,t),e.finishReason=t.response?.incomplete_details?.reason??"incomplete";return}case"response.failed":{cc(e,t),e.finishReason="failed";return}default:return}}function cc(t,e){let n=e.response?.usage;if(!n)return;let r=n.input_tokens??0,o=n.output_tokens??0;t.usage={prompt_tokens:r,completion_tokens:o,total_tokens:n.total_tokens??r+o,prompt_tokens_details:{cached_tokens:n.input_tokens_details?.cached_tokens??0}}}var Dm=y(()=>{"use strict"});function Fm(t,e){let n=[],r=[];for(let i of t){if(i.role==="system"){typeof i.content=="string"&&i.content.length>0&&n.push(i.content);continue}if(i.role==="tool"){r.push({type:"function_call_output",call_id:i.tool_call_id??"",output:typeof i.content=="string"?i.content:""});continue}if(i.role==="assistant"){if(typeof i.content=="string"&&i.content.length>0&&r.push({role:"assistant",content:i.content}),Array.isArray(i.tool_calls))for(let a of i.tool_calls)r.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:a.function.arguments});continue}r.push({role:"user",content:$T(i.content)})}let o={input:r};n.length>0&&(o.instructions=n.join(`
1079
1079
 
1080
1080
  `));let s=UT(e);return s.length>0&&(o.tools=s),o}function $T(t){if(t===null)return"";if(typeof t=="string")return t;let e=[];for(let n of t)n.type==="text"?e.push({type:"input_text",text:n.text}):e.push({type:"input_image",image_url:n.image_url.url,detail:"auto"});return e}function UT(t){return!t||t.length===0?[]:t.map(e=>{let n={type:"function",name:e.function.name,parameters:e.function.parameters};return e.function.description!==void 0&&(n.description=e.function.description),n})}var Lm=y(()=>{"use strict"});function $m(t){let e=(t??"").trim().toLowerCase();return e?e.startsWith("claude-")||e.startsWith("claude_")||e==="claude"||e.startsWith("local-")||e.startsWith("local_")?!0:/^(opus|sonnet|haiku)(?:[._-].*)?$/.test(e):!1}function Um(t){if(!t)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}function HT(t){let e={"OpenAI-Beta":"responses=experimental",originator:"agent-afk"};return t&&(e["chatgpt-account-id"]=t),e}function Bm(t,e=!1){return t.source==="chatgpt-oauth"?{mode:"responses",baseURL:BT,headers:HT(t.accountId)}:e?{mode:"responses"}:{mode:"chat-completions"}}var BT,Nm,Hm=y(()=>{"use strict";BT="https://chatgpt.com/backend-api/codex",Nm="You are a helpful assistant."});function jT(t){return(t.inputTokens??0)+(t.outputTokens??0)}function hn(t){return t.contextWindowTokens??jT(t)}function ds(t){return t?{totalTokens:hn(t),apiUsage:{input_tokens:t.inputTokens??0,output_tokens:t.outputTokens??0,cache_read_input_tokens:t.cachedInputTokens??0,cache_creation_input_tokens:t.cacheCreationTokens??0}}:{totalTokens:0,apiUsage:null}}function jm(t,e,n){return e<=0||t<=0||n<=0||n>=1?!1:t/e>=n}var lc=y(()=>{"use strict"});import KT from"openai";import{randomUUID as Km}from"node:crypto";function Xm(t){if(t===null||typeof t!="object")return;let e=t;return typeof e.status=="number"?e.status:void 0}function qm(t){let e=Xm(t);return e===void 0?!1:Ym.has(e)}function Vm(t){let e=Xm(t);return e===void 0?!1:Ym.has(e)}function ps(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=setTimeout(n,t);r.unref(),e.addEventListener("abort",()=>{clearTimeout(r),n()},{once:!0})})}function Qm(t,e){let n=is(t);return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):n}function qT(t,e){let n=Qm(t,e);return Zm(t)?{max_completion_tokens:n}:{max_tokens:n}}function zm(t){return t??"default"}function Zm(t){let e=t.includes("/")?t.slice(t.lastIndexOf("/")+1):t;return/^o[0-9]/.test(e)}function VT(t){switch(t){case"low":return"low";case"medium":return"medium";case"high":case"xhigh":case"max":return"high"}}function Jm(t,e){if(t!==void 0&&Zm(e))return VT(t)}function zT(t){let e={apiKey:t.apiKey};return t.baseURL!==void 0&&(e.baseURL=t.baseURL),t.defaultHeaders!==void 0&&(e.defaultHeaders=t.defaultHeaders),new KT(e)}function JT(t,e){if(!e||typeof e!="object")return"";let n=e;if(t==="skill"||t==="Skill"){let i=n.name;return typeof i=="string"&&i.length>0?`(${i.length>60?i.slice(0,59)+"\u2026":i})`:""}let r=n.file_path??n.path??n.filePath;if(typeof r=="string")return" "+r;let o=n.command??n.cmd;if(typeof o=="string"){let i=o.split(`
1081
- `)[0];return" "+(i.length>80?i.slice(0,77)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}function eg(t,e,n={}){let r=or(t.apiKey,n.authDeps),o=t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i=se(s)??s,a={auth:r,model:i,synthesizedSessionId:o,promptStream:e,config:t};return n.baseURL!==void 0&&(a.baseURL=n.baseURL),n.toolDispatcher!==void 0&&(a.toolDispatcher=n.toolDispatcher),n.onPermissionMode!==void 0&&(a.onPermissionMode=n.onPermissionMode),n.mcpManager!==void 0&&(a.mcpManager=n.mcpManager),n.useResponsesApi!==void 0&&(a.useResponsesApi=n.useResponsesApi),t.traceWriter!==void 0&&(a.traceWriter=t.traceWriter),new fs(a)}var dc,WT,Ym,Wm,Gm,us,GT,fs,uc=y(()=>{"use strict";ee();Bn();ec();as();De();yn();rc();le();ls();vm();_m();Tm();Mm();Dm();Lm();Hm();U();lc();Hi();Ki();dc="openai-compatible",WT=50,Ym=new Set([429,500,502,503,529]),Wm=3,Gm=3,us=2e3;GT=null;fs=class{client;opts;initSessionId;toolDispatcher;onPermissionMode;openAITools;wireMode;traceWriter;priorTurns=[];currentModel;currentPermissionMode;abortController=null;pendingAbortReason=null;closed=!1;closeResolve=null;closedPromise;lastUsage=null;constructor(e){if(this.opts=e,this.initSessionId=e.synthesizedSessionId,this.currentModel=e.model,this.currentPermissionMode=zm(e.config.permissionMode),this.toolDispatcher=e.toolDispatcher,this.onPermissionMode=e.onPermissionMode,this.traceWriter=e.traceWriter,this.toolDispatcher){let o=this.toolDispatcher;Array.isArray(o.toolDefs)&&o.toolDefs.length>0&&(this.openAITools=xm(o.toolDefs))}let n=(e.useResponsesApi??!1)||Um(S.AFK_OPENAI_USE_RESPONSES),r=Bm(e.auth,n);if(this.wireMode=r.mode,e.auth.apiKey===null)this.client=null;else{let o=GT??zT,s={apiKey:e.auth.apiKey},i=r.baseURL??e.baseURL;i!==void 0&&(s.baseURL=i),r.headers!==void 0&&(s.defaultHeaders=r.headers),this.client=o(s)}this.closedPromise=new Promise(o=>{this.closeResolve=()=>o("__closed__")})}async*[Symbol.asyncIterator](){if(yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:this.openAITools?this.openAITools.map(r=>r.function.name):[],slashCommands:[],skills:[],plugins:[],mcpServers:this.opts.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.opts.auth.source,version:dc}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(oc(this.opts.auth))};return}let n=this.opts.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;yield*this.runTurn(o.value.content)}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}async*runTurn(e){let n=new AbortController;if(this.abortController=n,this.pendingAbortReason!==null&&!n.signal.aborted&&(n.abort(this.pendingAbortReason),this.pendingAbortReason=null),n.signal.aborted)return;let r=Date.now(),o=Km();re(this.traceWriter,{phase:"loop_start"});try{yield*this._runTurnInner(e,n,r,o)}finally{re(this.traceWriter,{phase:"loop_end",durationMs:Date.now()-r})}}async*_runTurnInner(e,n,r,o){let s=km(this.currentModel);this.priorTurns.push({role:"user",content:bm(e,{vision:s,model:this.currentModel})});let i={stopReason:null,resultSubtype:"success",isError:!1},a="",c="";for(let l=0;l<WT;l++){if(n.signal.aborted){this.abortController===n&&(this.abortController=null),yield*this.finishTurn(i,r);return}let d=yield*this.runIteration(n,s);if(d===null){this.abortController===n&&(this.abortController=null),(n.signal.aborted||this.closed)&&(yield*this.finishTurn(i,r));return}let u=Am(d.state);if(i=tr(i,u),i.contextWindowTokens=(u.inputTokens??0)+(u.outputTokens??0),this.lastUsage=i,d.text.length>0&&(a=d.text),c=d.state.reasoningText,!d.needsToolDispatch)break;yield*this.dispatchAndAppend(d.state,n.signal,s);{let p=ic(d.state).at(-1)?.name;yield{type:"progress",progress:{taskId:o,description:"Tool-use loop",summary:`Iteration ${l+1}: used ${p??"unknown"}`,lastToolName:p,totalTokens:i.totalTokens??0,toolUses:l+1,durationMs:Date.now()-r},sessionId:this.initSessionId}}if(n.signal.aborted){this.abortController===n&&(this.abortController=null),yield*this.finishTurn(i,r);return}}if(this.abortController===n&&(this.abortController=null),a.length>0){let l={role:"assistant",content:a};c.length>0&&(l.reasoning_content=c),this.priorTurns.push(l)}yield{type:"assistant.message",text:a,sessionId:this.initSessionId},yield*this.finishTurn(i,r)}*finishTurn(e,n){this.lastUsage=e,yield{type:"turn.completed",usage:{...e,durationMs:Date.now()-n},sessionId:this.initSessionId}}clarifyResponsesError(e,n){let r=e instanceof Error?e:new Error(String(e));if(!n||(e&&typeof e=="object"&&"status"in e?e.status:void 0)!==400&&!/\b400\b/.test(r.message))return r;let s,i=e?.error;if(i&&typeof i=="object"){let a=i;typeof a.detail=="string"?s=a.detail:typeof a.message=="string"&&(s=a.message)}return new Error(`ChatGPT/Codex backend rejected model "${this.currentModel}" (HTTP 400). A ChatGPT subscription only serves certain OpenAI models on this backend (gpt-5.5 works; gpt-5, gpt-5.1, gpt-5.2 and *-codex do not). `+(s?`Backend said: ${s}`:"No error body was returned."))}async*runIteration(e,n){let r=wm({config:this.opts.config,...this.opts.config.resumeHistory!==void 0?{resumeHistory:this.opts.config.resumeHistory}:{},priorTurns:this.priorTurns,vision:n});if(r[0]?.role==="system"){let o=this.currentPermissionMode==="plan"?Bi:this.currentPermissionMode==="autonomous"?ji:null;o!==null&&(r[0]={...r[0],content:r[0].content+`
1081
+ `)[0];return" "+(i.length>80?i.slice(0,77)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}function eg(t,e,n={}){let r=or(t.apiKey,n.authDeps),o=t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i=oe(s)??s,a={auth:r,model:i,synthesizedSessionId:o,promptStream:e,config:t};return n.baseURL!==void 0&&(a.baseURL=n.baseURL),n.toolDispatcher!==void 0&&(a.toolDispatcher=n.toolDispatcher),n.onPermissionMode!==void 0&&(a.onPermissionMode=n.onPermissionMode),n.mcpManager!==void 0&&(a.mcpManager=n.mcpManager),n.useResponsesApi!==void 0&&(a.useResponsesApi=n.useResponsesApi),t.traceWriter!==void 0&&(a.traceWriter=t.traceWriter),new fs(a)}var dc,WT,Ym,Wm,Gm,us,GT,fs,uc=y(()=>{"use strict";ee();Bn();ec();as();De();yn();rc();le();ls();vm();_m();Tm();Mm();Dm();Lm();Hm();U();lc();Hi();Ki();dc="openai-compatible",WT=50,Ym=new Set([429,500,502,503,529]),Wm=3,Gm=3,us=2e3;GT=null;fs=class{client;opts;initSessionId;toolDispatcher;onPermissionMode;openAITools;wireMode;traceWriter;priorTurns=[];currentModel;currentPermissionMode;abortController=null;pendingAbortReason=null;closed=!1;closeResolve=null;closedPromise;lastUsage=null;constructor(e){if(this.opts=e,this.initSessionId=e.synthesizedSessionId,this.currentModel=e.model,this.currentPermissionMode=zm(e.config.permissionMode),this.toolDispatcher=e.toolDispatcher,this.onPermissionMode=e.onPermissionMode,this.traceWriter=e.traceWriter,this.toolDispatcher){let o=this.toolDispatcher;Array.isArray(o.toolDefs)&&o.toolDefs.length>0&&(this.openAITools=xm(o.toolDefs))}let n=(e.useResponsesApi??!1)||Um(S.AFK_OPENAI_USE_RESPONSES),r=Bm(e.auth,n);if(this.wireMode=r.mode,e.auth.apiKey===null)this.client=null;else{let o=GT??zT,s={apiKey:e.auth.apiKey},i=r.baseURL??e.baseURL;i!==void 0&&(s.baseURL=i),r.headers!==void 0&&(s.defaultHeaders=r.headers),this.client=o(s)}this.closedPromise=new Promise(o=>{this.closeResolve=()=>o("__closed__")})}async*[Symbol.asyncIterator](){if(yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:this.openAITools?this.openAITools.map(r=>r.function.name):[],slashCommands:[],skills:[],plugins:[],mcpServers:this.opts.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.opts.auth.source,version:dc}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(oc(this.opts.auth))};return}let n=this.opts.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;yield*this.runTurn(o.value.content)}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}async*runTurn(e){let n=new AbortController;if(this.abortController=n,this.pendingAbortReason!==null&&!n.signal.aborted&&(n.abort(this.pendingAbortReason),this.pendingAbortReason=null),n.signal.aborted)return;let r=Date.now(),o=Km();re(this.traceWriter,{phase:"loop_start"});try{yield*this._runTurnInner(e,n,r,o)}finally{re(this.traceWriter,{phase:"loop_end",durationMs:Date.now()-r})}}async*_runTurnInner(e,n,r,o){let s=km(this.currentModel);this.priorTurns.push({role:"user",content:bm(e,{vision:s,model:this.currentModel})});let i={stopReason:null,resultSubtype:"success",isError:!1},a="",c="";for(let l=0;l<WT;l++){if(n.signal.aborted){this.abortController===n&&(this.abortController=null),yield*this.finishTurn(i,r);return}let d=yield*this.runIteration(n,s);if(d===null){this.abortController===n&&(this.abortController=null),(n.signal.aborted||this.closed)&&(yield*this.finishTurn(i,r));return}let u=Am(d.state);if(i=tr(i,u),i.contextWindowTokens=(u.inputTokens??0)+(u.outputTokens??0),this.lastUsage=i,d.text.length>0&&(a=d.text),c=d.state.reasoningText,!d.needsToolDispatch)break;yield*this.dispatchAndAppend(d.state,n.signal,s);{let p=ic(d.state).at(-1)?.name;yield{type:"progress",progress:{taskId:o,description:"Tool-use loop",summary:`Iteration ${l+1}: used ${p??"unknown"}`,lastToolName:p,totalTokens:i.totalTokens??0,toolUses:l+1,durationMs:Date.now()-r},sessionId:this.initSessionId}}if(n.signal.aborted){this.abortController===n&&(this.abortController=null),yield*this.finishTurn(i,r);return}}if(this.abortController===n&&(this.abortController=null),a.length>0){let l={role:"assistant",content:a};c.length>0&&(l.reasoning_content=c),this.priorTurns.push(l)}yield{type:"assistant.message",text:a,sessionId:this.initSessionId},yield*this.finishTurn(i,r)}*finishTurn(e,n){this.lastUsage=e,yield{type:"turn.completed",usage:{...e,durationMs:Date.now()-n},sessionId:this.initSessionId}}clarifyResponsesError(e,n){let r=e instanceof Error?e:new Error(String(e));if(!n||(e&&typeof e=="object"&&"status"in e?e.status:void 0)!==400&&!/\b400\b/.test(r.message))return r;let s,i=e?.error;if(i&&typeof i=="object"){let a=i;typeof a.detail=="string"?s=a.detail:typeof a.message=="string"&&(s=a.message)}return new Error(`ChatGPT/Codex backend rejected model "${this.currentModel}" (HTTP 400). A ChatGPT subscription only serves certain OpenAI models on this backend (gpt-5.5 works; gpt-5, gpt-5.1, gpt-5.2 and *-codex do not). `+(s?`Backend said: ${s}`:"No error body was returned."))}async*runIteration(e,n){let r=wm({config:this.opts.config,...this.opts.config.resumeHistory!==void 0?{resumeHistory:this.opts.config.resumeHistory}:{},priorTurns:this.priorTurns,vision:n});if(r[0]?.role==="system"){let o=this.currentPermissionMode==="plan"?Bi:this.currentPermissionMode==="autonomous"?ji:null;o!==null&&(r[0]={...r[0],content:r[0].content+`
1082
1082
 
1083
1083
  `+o})}if(this.wireMode==="responses"){let o=this.opts.auth.source==="chatgpt-oauth";if(o&&$m(this.currentModel))return yield{type:"error",error:new Error(`Model "${this.currentModel}" can't run on a ChatGPT subscription \u2014 the ChatGPT/Codex backend only supports OpenAI gpt-5.x models. This usually means a subagent or skill requested a Claude model. Pass a gpt-5.x model to it (e.g. model: "gpt-5.5"), or run it on a provider configured with the matching API key.`)},null;let s=Fm(r,this.openAITools),i={model:this.currentModel,input:s.input,stream:!0};o||(i.max_output_tokens=Qm(this.currentModel,this.opts.config.maxOutputTokens));let a=s.instructions??(o?Nm:void 0);a!==void 0&&(i.instructions=a),o&&(i.store=!1),s.tools&&s.tools.length>0&&(i.tools=s.tools);let c=Jm(this.opts.config.effort,this.currentModel);c!==void 0&&(i.reasoning={effort:c});let l=0;for(;;){let d=sc(),u=Date.now(),p,f=null;for(let v=0;;v++)try{p=await this.client.responses.create(i,{signal:e.signal});break}catch(b){if(e.signal.aborted)return null;if(qm(b)&&v<Wm){let E=us*Math.pow(2,v);if(await ps(E,e.signal),e.signal.aborted)return null;continue}f=b;break}if(f!==null)return yield{type:"error",error:this.clarifyResponsesError(f,o)},null;let h=null,g=!1;try{for await(let v of p){if(this.closed)return null;for(let b of Om(v,d,this.initSessionId))g||(g=!0,re(this.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-u,resolvedModel:this.currentModel})),yield b}}catch(v){if(e.signal.aborted)return null;if(Vm(v)&&l<Gm){if(l++,yield{type:"stream.retry",sessionId:this.initSessionId},await ps(us*Math.pow(2,l-1),e.signal),e.signal.aborted)return null;continue}h=v}return h!==null?(yield{type:"error",error:this.clarifyResponsesError(h,o)},null):{state:d,events:[],text:d.assistantText,needsToolDispatch:ac(d)&&d.toolCallsByIndex.size>0}}}else{let o={model:this.currentModel,messages:r,stream:!0,stream_options:{include_usage:!0}};Object.assign(o,qT(this.currentModel,this.opts.config.maxOutputTokens)),this.openAITools&&this.openAITools.length>0&&(o.tools=this.openAITools);let s=Jm(this.opts.config.effort,this.currentModel);s!==void 0&&(o.reasoning_effort=s);let i=0;for(;;){let a=sc(),c=Date.now(),l,d=null;for(let f=0;;f++)try{l=await this.client.chat.completions.create(o,{signal:e.signal});break}catch(h){if(e.signal.aborted)return null;if(qm(h)&&f<Wm){let g=us*Math.pow(2,f);if(await ps(g,e.signal),e.signal.aborted)return null;continue}d=h;break}if(d!==null)return yield{type:"error",error:d instanceof Error?d:new Error(String(d))},null;let u=null,p=!1;try{for await(let f of l){if(this.closed)return null;for(let h of Em(f,a,this.initSessionId))p||(p=!0,re(this.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-c,resolvedModel:this.currentModel})),yield h}}catch(f){if(e.signal.aborted)return null;if(Vm(f)&&i<Gm){if(i++,yield{type:"stream.retry",sessionId:this.initSessionId},await ps(us*Math.pow(2,i-1),e.signal),e.signal.aborted)return null;continue}u=f}return u!==null?(yield{type:"error",error:u instanceof Error?u:new Error(String(u))},null):{state:a,events:[],text:a.assistantText,needsToolDispatch:ac(a)&&a.toolCallsByIndex.size>0}}}}async*dispatchAndAppend(e,n,r){if(!this.toolDispatcher)return;let o=ic(e);for(let d of o)d.id.length===0&&(d.id=Km());let{calls:s,parseErrors:i}=Rm(o,n),a=new Map;for(let d of s){let u=Date.now();a.set(d.id,u),Qt(this.traceWriter,{phase:"started",toolUseId:d.id,name:d.name,inputBytes:Buffer.byteLength(JSON.stringify(d.input??{}),"utf8")}),yield{type:"tool.use.start",toolUseId:d.id,toolName:d.name,toolInput:JT(d.name,d.input),toolInputRaw:cs(d.input),sessionId:this.initSessionId}}let c=[];if(n.aborted)for(let d of s){let u={content:"Tool call aborted",isError:!0};c.push({call:d,result:u}),yield{type:"tool.output",toolUseId:d.id,toolName:d.name,content:u.content,isError:!0,sessionId:this.initSessionId}}else{let d;try{if(this.toolDispatcher.executeBatch)d=await this.toolDispatcher.executeBatch(s);else{d=[];for(let u of s){if(n.aborted){d.push({content:"Tool call aborted",isError:!0});continue}try{d.push(await this.toolDispatcher.execute(u))}catch(p){let f=p instanceof Error?p.message:String(p);d.push({content:`Tool execution threw: ${f}`,isError:!0})}}}}catch(u){let p=u instanceof Error?u.message:String(u);d=s.map(()=>({content:`Tool batch execution failed: ${p}`,isError:!0}))}for(let u=0;u<s.length;u++){let p=s[u],f=d[u],h=i.get(p.id);h!==void 0&&(f={content:`${h}
1084
1084
  --
1085
- ${f.content}`,isError:!0,...f.truncated===!0?{truncated:!0}:{}}),c.push({call:p,result:f});let g=a.get(p.id),v=typeof g=="number"?Date.now()-g:0,b=f.truncated===!0||f.content.includes("[output truncated");Qt(this.traceWriter,{phase:"completed",toolUseId:p.id,name:p.name,resultBytes:Buffer.byteLength(f.content,"utf8"),isError:f.isError===!0,truncated:b,durationMs:v,...f.circuitBreaker===!0?{circuitBreaker:!0}:{},...f.failureClass?{failureClass:f.failureClass}:{}}),yield{type:"tool.output",toolUseId:p.id,toolName:p.name,content:f.content,...f.isError===!0?{isError:!0}:{},...f.truncated===!0?{truncated:!0}:{},sessionId:this.initSessionId},f.render?.diff&&(yield{type:"tool.diff",toolUseId:p.id,diff:f.render.diff,sessionId:this.initSessionId})}}this.priorTurns.push(Pm(e.assistantText,o,e.reasoningText));for(let d of Im(c))this.priorTurns.push(d);let l=Cm(c,{vision:r});l&&this.priorTurns.push(l)}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){e!==void 0&&(this.currentModel=e)}async setPermissionMode(e){this.currentPermissionMode=zm(e);let n=Fe(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(e){this.toolDispatcher?.setResolveBase?.(e)}async supportedCommands(){try{return Bt().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return[{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=nr(this.currentModel),r;if(e&&n>0){let i=hn(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=ds(e);return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(e,n){return{canRewind:!1,error:`${dc} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),$(`\u{1F7E2} ${dc}: closed`)}}});import YT from"openai";async function tg(t){let{apiKey:e,baseURL:n,model:r,system:o,user:s,maxTokens:i=64,signal:a,clientFactory:c}=t,l=or(e);if(l.apiKey===null)throw new Error("oneShotChatCompletion: no usable OpenAI auth (set OPENAI_API_KEY or pass apiKey)");let d={apiKey:l.apiKey};n!==void 0&&(d.baseURL=n);let u=c??XT,p=u?u(d):new YT(d),f=r.includes("/")?r.slice(r.lastIndexOf("/")+1):r,h=/^o[0-9]/.test(f)?{max_completion_tokens:i}:{max_tokens:i},v=(await p.chat.completions.create({model:r,...h,stream:!1,messages:[{role:"system",content:o},{role:"user",content:s}]},a?{signal:a}:void 0)).choices?.[0]?.message?.content;return typeof v=="string"?v.trim():""}var XT,ng=y(()=>{"use strict";ls();XT=null});import pc from"path";import{appendFileSync as QT,mkdirSync as ZT}from"fs";import{dirname as ex}from"path";var fc,ue,tx,sr=y(()=>{"use strict";K();xo();Po();ua();Bn();Za();pt();dt();uc();ng();ft();ct();ls();uc();fc="openai-compatible",ue=class{name=fc;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_presenceSessionId=null;constructor(e={}){this.providerOpts=e,this.memoryStore=e.memoryStore??new fe;let n=[...Ze];e.subagentExecutor&&n.push(Mt),e.skillExecutor&&n.push(Ot),e.composeExecutor&&n.push(Dt),e.readOnlyMemory===!0?n.push(qt):n.push(...lt),n.push($e),this.schemas=n}query(e){let n=e.config,r=n.permissionMode??"default";this._currentPermissionMode=r,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=Wn({surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),modelName:s,providerName:fc,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof et?o.toolDefs.map(f=>f.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?Gn(this.providerOpts.tools,i):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:i,...n.isSkillDispatch?{isSkillDispatch:!0}:{},...n.isNonInteractive?{isNonInteractive:!0}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{}});let a={},c=n.openaiBaseUrl??this.providerOpts.baseURL;if(c!==void 0&&(a.baseURL=c),a.toolDispatcher=o,a.onPermissionMode=f=>{this._currentPermissionMode=f},this.providerOpts.mcpManager!==void 0&&(a.mcpManager=this.providerOpts.mcpManager),(n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let f=n.sessionId,h=i.getWorkspace();Hn({sessionId:f,surface:this.providerOpts.surface??"cli",actor:Pe(n.depth),cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:fc,name:s},workspace:h,pid:process.pid}),process.once("exit",()=>{Ye(f)}),process.once("SIGINT",()=>{Ye(f),process.exit(130)}),process.once("SIGTERM",()=>{Ye(f),process.exit(143)})}let d=sn({cwd:n.cwd??process.cwd(),...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:i.getWorkspace()}),u=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,p={...n,systemPrompt:u!==void 0?`${u}
1085
+ ${f.content}`,isError:!0,...f.truncated===!0?{truncated:!0}:{}}),c.push({call:p,result:f});let g=a.get(p.id),v=typeof g=="number"?Date.now()-g:0,b=f.truncated===!0||f.content.includes("[output truncated");Qt(this.traceWriter,{phase:"completed",toolUseId:p.id,name:p.name,resultBytes:Buffer.byteLength(f.content,"utf8"),isError:f.isError===!0,truncated:b,durationMs:v,...f.circuitBreaker===!0?{circuitBreaker:!0}:{},...f.failureClass?{failureClass:f.failureClass}:{}}),yield{type:"tool.output",toolUseId:p.id,toolName:p.name,content:f.content,...f.isError===!0?{isError:!0}:{},...f.truncated===!0?{truncated:!0}:{},sessionId:this.initSessionId},f.render?.diff&&(yield{type:"tool.diff",toolUseId:p.id,diff:f.render.diff,sessionId:this.initSessionId})}}this.priorTurns.push(Pm(e.assistantText,o,e.reasoningText));for(let d of Im(c))this.priorTurns.push(d);let l=Cm(c,{vision:r});l&&this.priorTurns.push(l)}async interrupt(){let e=this.abortController;if(e&&!e.signal.aborted){e.abort("interrupted");return}this.pendingAbortReason="interrupted"}async setModel(e){e!==void 0&&(this.currentModel=oe(e)??e)}async setPermissionMode(e){this.currentPermissionMode=zm(e);let n=Fe(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(e){this.toolDispatcher?.setResolveBase?.(e)}async supportedCommands(){try{return Bt().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return[{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=nr(this.currentModel),r;if(e&&n>0){let i=hn(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=ds(e);return{tools:[],agents:[],isAutoCompactEnabled:!1,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(e,n){return{canRewind:!1,error:`${dc} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0;let e=this.abortController;e&&!e.signal.aborted?e.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),$(`\u{1F7E2} ${dc}: closed`)}}});import YT from"openai";async function tg(t){let{apiKey:e,baseURL:n,model:r,system:o,user:s,maxTokens:i=64,signal:a,clientFactory:c}=t,l=or(e);if(l.apiKey===null)throw new Error("oneShotChatCompletion: no usable OpenAI auth (set OPENAI_API_KEY or pass apiKey)");let d={apiKey:l.apiKey};n!==void 0&&(d.baseURL=n);let u=c??XT,p=u?u(d):new YT(d),f=r.includes("/")?r.slice(r.lastIndexOf("/")+1):r,h=/^o[0-9]/.test(f)?{max_completion_tokens:i}:{max_tokens:i},v=(await p.chat.completions.create({model:r,...h,stream:!1,messages:[{role:"system",content:o},{role:"user",content:s}]},a?{signal:a}:void 0)).choices?.[0]?.message?.content;return typeof v=="string"?v.trim():""}var XT,ng=y(()=>{"use strict";ls();XT=null});import pc from"path";import{appendFileSync as QT,mkdirSync as ZT}from"fs";import{dirname as ex}from"path";var fc,ue,tx,sr=y(()=>{"use strict";K();xo();Po();ua();Bn();Za();pt();dt();uc();ng();ft();ct();ls();uc();fc="openai-compatible",ue=class{name=fc;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_presenceSessionId=null;constructor(e={}){this.providerOpts=e,this.memoryStore=e.memoryStore??new fe;let n=[...Ze];e.subagentExecutor&&n.push(Mt),e.skillExecutor&&n.push(Ot),e.composeExecutor&&n.push(Dt),e.readOnlyMemory===!0?n.push(qt):n.push(...lt),n.push($e),this.schemas=n}query(e){let n=e.config,r=n.permissionMode??"default";this._currentPermissionMode=r,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=Wn({surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),modelName:s,providerName:fc,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof et?o.toolDefs.map(f=>f.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?Gn(this.providerOpts.tools,i):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:i,...n.isSkillDispatch?{isSkillDispatch:!0}:{},...n.isNonInteractive?{isNonInteractive:!0}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{}});let a={},c=n.openaiBaseUrl??this.providerOpts.baseURL;if(c!==void 0&&(a.baseURL=c),a.toolDispatcher=o,a.onPermissionMode=f=>{this._currentPermissionMode=f},this.providerOpts.mcpManager!==void 0&&(a.mcpManager=this.providerOpts.mcpManager),(n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let f=n.sessionId,h=i.getWorkspace();Hn({sessionId:f,surface:this.providerOpts.surface??"cli",actor:Pe(n.depth),cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:fc,name:s},workspace:h,pid:process.pid}),process.once("exit",()=>{Ye(f)}),process.once("SIGINT",()=>{Ye(f),process.exit(130)}),process.once("SIGTERM",()=>{Ye(f),process.exit(143)})}let d=sn({cwd:n.cwd??process.cwd(),...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:i.getWorkspace()}),u=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,p={...n,systemPrompt:u!==void 0?`${u}
1086
1086
 
1087
1087
  ${d}`:d};return eg(p,e.prompt,a)}buildDispatcher(e,n){let r=ss(e,n.cwd),o=Dn(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[l,d]of o)this.providerOpts.readOnlyMemory===!0&&l!=="memory_search"||r.set(l,d);n.runtimeStateSource&&r.set("get_runtime_state",an(n.runtimeStateSource));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[l,d]of this.providerOpts.mcpManager.getMcpHandlers())r.set(l,d);let i=n.isSkillDispatch?this.schemas.filter(l=>l.name!=="ask_question"&&l.name!=="terminal_font_size"):n.isNonInteractive?this.schemas.filter(l=>l.name!=="ask_question"):this.schemas,a={handlers:r,schemas:[...i,...s],hookRegistry:To(n.hookRegistry,this.providerOpts.hookRegistry)},c=this.providerOpts.mcpManager?Ro(this.providerOpts.permissions,this.providerOpts.mcpManager.getMcpToolWireNames()):this.providerOpts.permissions;return c!==void 0&&(a.permissions=c),this.providerOpts.subagentExecutor!==void 0&&(a.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(a.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(a.composeExecutor=this.providerOpts.composeExecutor),n.cwd!==void 0&&(a.cwd=n.cwd),n.readRoots!==void 0&&(a.readRoots=n.readRoots),n.writeRoots!==void 0&&(a.writeRoots=n.writeRoots),n.sessionId!==void 0&&(a.sessionId=n.sessionId),n.parentSessionId!==void 0&&(a.parentSessionId=n.parentSessionId),n.traceWriter!==void 0&&(a.traceWriter=n.traceWriter),this.providerOpts.readOnlyBash===!0&&(a.readOnlyBash=!0),a.allowAll=Fe(e),new et(a)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e)}}addReadRoot(e,n="slash",r){this.ensureSharedRoots();let o=pc.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(e,n="slash",r){this.ensureSharedRoots();let o=pc.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(e,n="slash",r){if(!this._sharedReadRoots)return;let o=pc.resolve(e);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[],allowAll:Fe(this._currentPermissionMode)}}appendProviderAuditLog(e){try{let n=Gt();ZT(ex(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??null,action:e.action,path:e.path,source:e.source});QT(n,r+`
1088
1088
  `)}catch{}}close(){this.memoryStore.close()}async complete(e){let n={model:e.model??"gpt-4o-mini",system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.apiKey!==void 0&&(n.apiKey=e.apiKey);let r=e.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),e.signal&&(n.signal=e.signal),tg(n)}},tx=new ue});function yt(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}function ms(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":yt(nx,t)?"read":yt(rx,t)?"write":yt(ox,t)?"shell":yt(rg,t)?"subagent":yt(og,t)?"skill":yt(sg,t)?"dag":yt(sx,t)?"web":ix.has(t)?"browser":yt(ax,t)?"planning":cx.has(t)?"schedule":"other"}var nx,rx,ox,rg,og,sg,mH,sx,ix,ax,cx,ig,gs=y(()=>{"use strict";la();nx=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search"]),rx=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size","config_set"]),ox=new Set(["Bash","BashOutput","KillBash","bash"]),rg=new Set(["Agent","Task","agent"]),og=new Set(["Skill","skill"]),sg=new Set(["Compose","compose"]),mH=new Set([...rg,...sg,...og]),sx=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),ix=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),ax=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),cx=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);ig=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search",...xe]});function ag(t){let e=lx(t);return e!==void 0?e:dx(t)}function lx(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n,r;for(;(r=e.exec(t))!==null;)n=r[1];if(n)return cg(n.trim())}function dx(t){for(let e=t.length-1;e>=0;e--){if(t[e]!=="}")continue;let n=ux(t,e);if(n===-1)continue;let r=t.slice(n,e+1),o=cg(r);if(o!==void 0)return o}}function ux(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 cg(t){try{return JSON.parse(t)}catch{return}}var lg=y(()=>{"use strict"});import{z as bt}from"zod";function gx(t){let e=/```(?:json)?\s*([\s\S]*?)```/gi,n;for(;(n=e.exec(t))!==null;){let r=n[1];if(r===void 0)continue;let o=dg(r.trim());if(ug(o))return o}for(let r=0;r<t.length;r++){if(t[r]!=="{"||hx(t,r))continue;let o=yx(t,r);if(o===-1)continue;let s=t.slice(r,o+1),i=dg(s);if(ug(i))return i;r=o}}function hx(t,e){for(let n=e-1;n>=0;n--){let r=t[n];if(!(r===" "||r===" "||r===`
1089
- `||r==="\r"))return r==="["||r===","}return!1}function pg(t){let e=gx(t);if(e===void 0)return{ok:!1,reason:"absent"};let n=mx.safeParse(e);return n.success?{ok:!0,signal:n.data.signal}:{ok:!1,reason:"malformed"}}function dg(t){try{return JSON.parse(t)}catch{return}}function ug(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&"signal"in t}function yx(t,e){let n=0,r=!1,o=!1;for(let s=e;s<t.length;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}var px,fx,mx,fg=y(()=>{"use strict";px=bt.enum(["supports","opposes","uncertain","blocks"]),fx=bt.object({issue:bt.string().min(1),stance:px,confidence:bt.number().min(0).max(1),evidence:bt.array(bt.string()),claim:bt.string().min(1)}),mx=bt.object({signal:fx}).passthrough()});function hs(){return{toolCalls:[],toolResults:[],thinkingPresent:!1,turnCount:0}}function mg(t,e,n,r,o){let s=pg(n.content),i=s.ok?s.signal:void 0;if(!r)return{id:t,status:e,message:n,trace:o,...i!==void 0&&{signal:i}};let a=ag(n.content),c=r.safeParse(a);return c.success?{id:t,status:e,message:n,output:c.data,trace:o,...i!==void 0&&{signal:i}}:{id:t,status:"failed",message:n,error:new Error(`structured output did not match schema: ${c.error.message}`,{cause:c.error}),schemaError:c.error,trace:o,...i!==void 0&&{signal:i}}}function mc(t,e,n,r){let o=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:o,trace:r}}function oe(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}function gg(t,e){let n=t;return e.partialOutput!==void 0&&e.partialOutput!==null&&(n.partialOutput=e.partialOutput),e.subagentId!==void 0&&(n.subagentId=e.subagentId),n}var ke=y(()=>{"use strict";lg();fg()});var hg=y(()=>{"use strict";K()});var DH,ys,yg=y(()=>{"use strict";ke();le();ee();hg();K();Qe();DH=300*1e3,ys=class extends Error{constructor(e,n){super(`Background job cap reached (${e}/${n} running). Wait for existing jobs to finish or cancel them before spawning more.`),this.name="BackgroundJobCapError"}}});function vx(t){return typeof t=="string"&&t.startsWith("sk-ant-")}function ir(t){let{childModel:e,resolved:n,parentApiKey:r}=t;return n!==void 0&&n.length>0||z(e)==="openai-compatible"?n:vx(r)?r:n}var gc=y(()=>{"use strict";we()});import{isAbsolute as Sx}from"node:path";function kx(t){if(typeof t!="object"||t===null)throw new Error("Agent tool input must be an object");let e=t,n=e.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=e.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=e.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let a="agent-tool",c=e.id_prefix;if(c!==void 0){if(typeof c!="string")throw new Error("Agent tool id_prefix must be a string");a=c}let l="foreground",d=e.mode;if(d!==void 0){if(d!=="foreground"&&d!=="background")throw new Error(`Agent tool mode must be "foreground" or "background", got: ${JSON.stringify(d)}`);l=d}let u,p=e.cwd;if(p!==void 0){if(typeof p!="string")throw new Error(`Agent tool cwd must be a string, got: ${JSON.stringify(p)}`);if(p.length===0)throw new Error("Agent tool cwd must be a non-empty string");if(!Sx(p))throw new Error(`Agent tool cwd must be an absolute path, got: ${JSON.stringify(p)}`);if(p.split(/[/\\]/).includes(".."))throw new Error(`Agent tool cwd must not contain '..' segments, got: ${JSON.stringify(p)}`);u=p}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:l,...u!==void 0?{cwd:u}:{}}}function bs(t){try{return Z(t).catch(()=>{})}catch{return Promise.resolve()}}function bn(t,e=240){return t.length<=e?t:t.slice(0,e)+"\u2026"}function wg(t){if(t!=null){if(typeof t=="string")return t.length;try{return JSON.stringify(t).length}catch{return}}}function Ex(t){if(t==null)return;let e=wg(t);return e!==void 0&&e>_x?{truncated:!0,chars:e}:t}function Ax(t){let e={status:t.status,error:bn(t.errorMessage,bg),subagent_id:t.subagentId};t.schemaErrorMessage&&(e.schemaError=bn(t.schemaErrorMessage,bg));let n=Ex(t.partialOutput);return n!==void 0&&(e.partialOutput=n),e}var _x,bg,wn,hc=y(()=>{"use strict";ie();yg();we();gc();tn();Sn();Qe();le();on();ct();Sn();_x=4096,bg=1024;wn=class t{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;currentCwd;setCwd(e){this.currentCwd=e,this.ctx.subagentManager.setCwd(e)}promotionTriggers=new Map;hasPromotableForeground(){return this.ctx.backgroundRegistry!==void 0&&this.promotionTriggers.size>0}async promoteActiveForeground(){let e=[...this.promotionTriggers.values()];return e.forEach(r=>r.fire()),(await Promise.all(e.map(r=>r.ready))).filter(r=>r!==null)}getSubagentsLite(){let e=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:e,backgroundJobs:n}}async execute(e){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=kx(e.input)}catch(_){return{content:`Agent tool input validation failed: ${_ instanceof Error?_.message:String(_)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??vn,s,i=this.ctx.surface!==void 0?{origin:at(this.ctx.surface),actor:Pe(r)}:{},a=n.model??this.ctx.defaultSubagentModel??"sonnet",c=z(a)==="openai-compatible",l=ir({childModel:a,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(a):Je(a),parentApiKey:this.ctx.defaultConfig.apiKey}),d={model:a,apiKey:c?void 0:l,systemPrompt:this.ctx.defaultConfig.systemPrompt,baseUrl:c?void 0:this.ctx.defaultConfig.baseUrl,maxTurns:n.max_turns,depth:r+1,maxDepth:o,...n.cwd!==void 0?{cwd:n.cwd}:{}},u;if(this.ctx.childProviderFactory&&r<o){s=new G({parentAbortSignal:e.signal,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),u=ar(e.signal);let _=new t({subagentManager:s,parentSession:u,defaultConfig:this.ctx.defaultConfig,...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:r+1,maxDepth:o,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}}),T=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,e.signal):void 0;d.provider=this.ctx.childProviderFactory({childExecutor:_,...T!==void 0?{childSkillExecutor:T}:{},...d.model!==void 0?{model:d.model}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}})}let p;try{p=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:e.id,config:d,idPrefix:n.id_prefix,agentType:n.id_prefix&&n.id_prefix!=="agent-tool"?Xe(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":Xe(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:!0}),u!==void 0&&(u.sessionId=p.id)}catch(_){let T=_ instanceof Error?_.message:String(_);return bs({...i,event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:bn(T),depth:r}),{content:`Failed to fork subagent: ${T}`,isError:!0}}if(n.mode==="background"){let _=this.ctx.backgroundRegistry;if(!_)return await p.teardown().catch(I=>$("subagent-executor: handle teardown failed: "+(I instanceof Error?I.message:String(I)))),{content:'Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired. Re-issue the call with mode="foreground" or run inside `afk interactive`.',isError:!0};let T;try{T=_.register({handle:p,prompt:n.prompt,model:d.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(I){if(I instanceof ys)return await p.teardown().catch(D=>$("subagent-executor: handle teardown failed after cap error: "+(D instanceof Error?D.message:String(D)))),{content:I.message,isError:!0};throw I}let P={status:"running",jobId:T.jobId,subagentId:T.subagentId,label:T.label,message:`Background subagent started (jobId=${T.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${T.jobId} or ask the user to join.`};return{content:JSON.stringify(P)}}let f=()=>{p.cancel()};e.signal.addEventListener("abort",f,{once:!0});let h=Date.now(),g=this.ctx.parentSession.sessionId,v=!1,b,E=new Promise(_=>{b=_}),w,k=new Promise(_=>{w=_});this.promotionTriggers.set(p.id,{fire:b,ready:k});let A=p.runToResult(n.prompt);try{let _=await Promise.race([A.then(x=>({kind:"result",result:x})),E.then(()=>({kind:"promote"}))]);if(_.kind==="promote"){let x=this.ctx.backgroundRegistry;if(x)try{let F=x.adoptRunning({handle:p,runPromise:A,prompt:n.prompt,model:d.model??"sonnet",parentSessionId:g});return v=!0,e.signal.removeEventListener("abort",f),w({jobId:F.jobId,label:F.label}),{content:JSON.stringify({status:"running",jobId:F.jobId,subagentId:F.subagentId,label:F.label,message:`Subagent backgrounded by user (jobId=${F.jobId}). It keeps running detached and its result will NOT auto-inject into this context. Retrieve it via /bgsub:join ${F.jobId}.`})}}catch(F){$("subagent-executor: promotion failed, staying foreground: "+(F instanceof Error?F.message:String(F))),w(null)}else w(null)}let T=_.kind==="result"?_.result:await A;if(T.status==="succeeded"&&T.message){let x=T.message.content,F=typeof x=="string"?x:JSON.stringify(x),O=T.trace;return bs({...i,event:"subagent.completed",subagent_id:p.id,parent_session_id:g,status:T.status,duration_ms:Date.now()-h,content_chars:F.length,depth:r,tool_call_count:O?.toolCalls.length,thinking_present:O?.thinkingPresent,tool_names:O?.toolCalls.length?JSON.stringify([...new Set(O.toolCalls.map(L=>L.name))]):void 0}),{content:F}}let P=T.error?.message??"Subagent failed with no output",I=T.trace;bs({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:g,status:T.status,duration_ms:Date.now()-h,error_message:bn(P),schema_error:T.schemaError?bn(T.schemaError.message):void 0,partial_output_chars:wg(T.partialOutput),depth:r,tool_call_count:I?.toolCalls.length,thinking_present:I?.thinkingPresent,tool_names:I?.toolCalls.length?JSON.stringify([...new Set(I.toolCalls.map(x=>x.name))]):void 0});let D=Ax({status:T.status,errorMessage:P,schemaErrorMessage:T.schemaError?.message,partialOutput:T.partialOutput,subagentId:p.id});return{content:JSON.stringify(D),isError:!0}}catch(_){let T=_ instanceof Error?_.message:String(_);throw bs({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:g,status:"failed",duration_ms:Date.now()-h,error_message:bn(T),depth:r}),_}finally{this.promotionTriggers.delete(p.id),w(null),v||(e.signal.removeEventListener("abort",f),await s?.teardownAll(),await p.teardown())}}}});function vg(t,e){return`Skill tool not available at nesting depth ${t} (max ${e}). ${Tx}`}var Tx,Sg=y(()=>{"use strict";Tx="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function kg(t){return xx.has(t)}var xx,_g=y(()=>{"use strict";xx=new Set});function Eg(t){for(let e of Rx)e(t)}function Ag(t){for(let e of Px)e(t)}var Rx,Px,Tg=y(()=>{"use strict";Rx=new Set,Px=new Set});function xg(t){return Ix.has(t)}function Mx(t,e=Cx){return t.length<=e?t:t.slice(0,e)+"\u2026"}function Ox(t){if(typeof t!="object"||t===null)return;let e=t.name;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function Dx(t){if(typeof t!="object"||t===null)throw new Error("Skill tool input must be an object");let e=t,n=e.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=e.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var Ix,Cx,kn,bc=y(()=>{"use strict";be();ie();yn();Sn();hc();Sg();gc();tn();Ct();Te();Qe();_g();Tg();le();ct();Ix=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","intent-lock","long-bash-gate","exploration-gate","irreversible-action-gate","safe-destruct","plan-probe"]);Cx=240;kn=class{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;pluginBodies=null;currentCwd;setCwd(e){this.currentCwd=e}sessionIdentity(){return this.ctx.surface!==void 0?{origin:at(this.ctx.surface),actor:Pe(this.ctx.depth)}:{}}async execute(e){if(e.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??vn;if(n>=r){let c=Ox(e.input);return Z({...this.sessionIdentity(),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:c}).catch(()=>{}),{content:vg(n,r),isError:!0}}let o;try{o=Dx(e.input)}catch(c){return{content:`Skill tool input validation failed: ${c instanceof Error?c.message:String(c)}`,isError:!0}}try{let c=Le(o.name);return await this.executeRegistrySkill(c,o.arguments,e)}catch{}let s=this.getPluginSkillBody(o.name);if(s){if(s.context==="fork"){let l=s.readOnly===!0||yc.has(o.name);return await this.executePluginSkill(o.name,s.body,s.pluginPath,o.arguments,e,l,s.allowedTools)}let c=s.body.replace(/\$\{?PLUGIN_ROOT\}?/g,()=>s.pluginPath);return this.executeLoadedPluginSkill(o.name,c,o.arguments,e)}let a=Bt(this.ctx.pluginConfigs).map(c=>c.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(e.context==="fork")return this.executeForkedRegistrySkill(e,n,r);if(e.context==="load")return this.executeLoadedRegistrySkill(e,n,r);let o=kg(e.name);o&&Ag(e.name);let s=this.ctx.depth??0;Z({...this.sessionIdentity(),event:"skill.dispatched",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...xg(e.name)?{is_gate:!0}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{});let i=Date.now(),a,c;try{c=await e.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r)})}catch(d){a=d}finally{let d=Date.now()-i;o&&Eg({skillName:e.name,durationMs:d,...a!==void 0?{isError:!0}:{}});let u=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof c=="string"?c.length:c!=null?JSON.stringify(c).length:0:void 0;Z({...this.sessionIdentity(),event:"skill.completed",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:d,depth:s,...p!==void 0?{content_chars:p}:{},...u!==void 0?{error_message:Mx(u)}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof c=="string"?c:c!=null?JSON.stringify(c):"Skill completed successfully."}}buildForkedChildConfig(e,n,r=!1,o){let s=this.ctx.depth??0,i=this.ctx.maxDepth??vn,a={...e},c=r&&o!==void 0?o.filter(f=>ws.includes(f)):r?[...ws]:o,l=r;if(!this.ctx.childProviderFactory||s>=i)return r?a.provider=Rg(a.model):c!==void 0&&(a.provider=Pg(c,a.model)),{childConfig:a,childManager:void 0};let d=new G({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),u=new wn({subagentManager:d,parentSession:ar(n),defaultConfig:{model:a.model,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{}},...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:s+1,maxDepth:i,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{},...this.ctx.backgroundRegistry!==void 0?{backgroundRegistry:this.ctx.backgroundRegistry}:{},...c!==void 0?{allowedTools:c}:{},...l?{readOnlyBash:!0}:{}}),p=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(s+1,i,n):void 0;return a.provider=this.ctx.childProviderFactory({childExecutor:u,...p!==void 0?{childSkillExecutor:p}:{},...a.model!==void 0?{model:a.model}:{},...c!==void 0?{allowedTools:c}:{},...l?{readOnlyBash:!0}:{}}),{childConfig:a,childManager:d}}async executeForkedRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=e.readOnly===!0||yc.has(e.name),s;try{if(s=Q(e.name)["system.md"],!s)return{content:`Skill "${e.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(p){return{content:`Failed to load skill prompts: ${p instanceof Error?p.message:String(p)}`,isError:!0}}let i=e.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",a=ir({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):Je(i),parentApiKey:this.ctx.apiKey}),c=new G({parentAbortSignal:r.signal,apiKey:a,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:ve(),...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),{childConfig:l,childManager:d}=this.buildForkedChildConfig({model:i,systemPrompt:s,isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal,o),u;try{u=await c.forkSubagent({parent:this.ctx.parentSession,config:l,idPrefix:`skill-fork-${e.name}`,parentId:r.id,agentType:e.name});let p=n&&n.length>0?n:`Run the ${e.name} skill now, following the instructions in your system prompt.`,f=await u.runToResult(p);return f.status==="succeeded"&&f.message?{content:f.message.content}:f.status==="cancelled"&&typeof f.partialOutput=="string"&&f.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
1089
+ `||r==="\r"))return r==="["||r===","}return!1}function pg(t){let e=gx(t);if(e===void 0)return{ok:!1,reason:"absent"};let n=mx.safeParse(e);return n.success?{ok:!0,signal:n.data.signal}:{ok:!1,reason:"malformed"}}function dg(t){try{return JSON.parse(t)}catch{return}}function ug(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&"signal"in t}function yx(t,e){let n=0,r=!1,o=!1;for(let s=e;s<t.length;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}var px,fx,mx,fg=y(()=>{"use strict";px=bt.enum(["supports","opposes","uncertain","blocks"]),fx=bt.object({issue:bt.string().min(1),stance:px,confidence:bt.number().min(0).max(1),evidence:bt.array(bt.string()),claim:bt.string().min(1)}),mx=bt.object({signal:fx}).passthrough()});function hs(){return{toolCalls:[],toolResults:[],thinkingPresent:!1,turnCount:0}}function mg(t,e,n,r,o){let s=pg(n.content),i=s.ok?s.signal:void 0;if(!r)return{id:t,status:e,message:n,trace:o,...i!==void 0&&{signal:i}};let a=ag(n.content),c=r.safeParse(a);return c.success?{id:t,status:e,message:n,output:c.data,trace:o,...i!==void 0&&{signal:i}}:{id:t,status:"failed",message:n,error:new Error(`structured output did not match schema: ${c.error.message}`,{cause:c.error}),schemaError:c.error,trace:o,...i!==void 0&&{signal:i}}}function mc(t,e,n,r){let o=n instanceof Error?n:new Error(String(n));return{id:t,status:e,error:o,trace:r}}function se(t){return`${t.status}${t.error?`: ${t.error.message}`:""}`}function gg(t,e){let n=t;return e.partialOutput!==void 0&&e.partialOutput!==null&&(n.partialOutput=e.partialOutput),e.subagentId!==void 0&&(n.subagentId=e.subagentId),n}var ke=y(()=>{"use strict";lg();fg()});var hg=y(()=>{"use strict";K()});var DH,ys,yg=y(()=>{"use strict";ke();le();ee();hg();K();Qe();DH=300*1e3,ys=class extends Error{constructor(e,n){super(`Background job cap reached (${e}/${n} running). Wait for existing jobs to finish or cancel them before spawning more.`),this.name="BackgroundJobCapError"}}});function vx(t){return typeof t=="string"&&t.startsWith("sk-ant-")}function ir(t){let{childModel:e,resolved:n,parentApiKey:r}=t;return n!==void 0&&n.length>0||z(e)==="openai-compatible"?n:vx(r)?r:n}var gc=y(()=>{"use strict";we()});import{isAbsolute as Sx}from"node:path";function kx(t){if(typeof t!="object"||t===null)throw new Error("Agent tool input must be an object");let e=t,n=e.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=e.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=e.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let a="agent-tool",c=e.id_prefix;if(c!==void 0){if(typeof c!="string")throw new Error("Agent tool id_prefix must be a string");a=c}let l="foreground",d=e.mode;if(d!==void 0){if(d!=="foreground"&&d!=="background")throw new Error(`Agent tool mode must be "foreground" or "background", got: ${JSON.stringify(d)}`);l=d}let u,p=e.cwd;if(p!==void 0){if(typeof p!="string")throw new Error(`Agent tool cwd must be a string, got: ${JSON.stringify(p)}`);if(p.length===0)throw new Error("Agent tool cwd must be a non-empty string");if(!Sx(p))throw new Error(`Agent tool cwd must be an absolute path, got: ${JSON.stringify(p)}`);if(p.split(/[/\\]/).includes(".."))throw new Error(`Agent tool cwd must not contain '..' segments, got: ${JSON.stringify(p)}`);u=p}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:l,...u!==void 0?{cwd:u}:{}}}function bs(t){try{return Z(t).catch(()=>{})}catch{return Promise.resolve()}}function bn(t,e=240){return t.length<=e?t:t.slice(0,e)+"\u2026"}function wg(t){if(t!=null){if(typeof t=="string")return t.length;try{return JSON.stringify(t).length}catch{return}}}function Ex(t){if(t==null)return;let e=wg(t);return e!==void 0&&e>_x?{truncated:!0,chars:e}:t}function Ax(t){let e={status:t.status,error:bn(t.errorMessage,bg),subagent_id:t.subagentId};t.schemaErrorMessage&&(e.schemaError=bn(t.schemaErrorMessage,bg));let n=Ex(t.partialOutput);return n!==void 0&&(e.partialOutput=n),e}var _x,bg,wn,hc=y(()=>{"use strict";ie();yg();we();gc();tn();Sn();Qe();le();on();ct();Sn();_x=4096,bg=1024;wn=class t{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;currentCwd;setCwd(e){this.currentCwd=e,this.ctx.subagentManager.setCwd(e)}promotionTriggers=new Map;hasPromotableForeground(){return this.ctx.backgroundRegistry!==void 0&&this.promotionTriggers.size>0}async promoteActiveForeground(){let e=[...this.promotionTriggers.values()];return e.forEach(r=>r.fire()),(await Promise.all(e.map(r=>r.ready))).filter(r=>r!==null)}getSubagentsLite(){let e=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:e,backgroundJobs:n}}async execute(e){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=kx(e.input)}catch(_){return{content:`Agent tool input validation failed: ${_ instanceof Error?_.message:String(_)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??vn,s,i=this.ctx.surface!==void 0?{origin:at(this.ctx.surface),actor:Pe(r)}:{},a=n.model??this.ctx.defaultSubagentModel??"sonnet",c=z(a)==="openai-compatible",l=ir({childModel:a,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(a):Je(a),parentApiKey:this.ctx.defaultConfig.apiKey}),d={model:a,apiKey:c?void 0:l,systemPrompt:this.ctx.defaultConfig.systemPrompt,baseUrl:c?void 0:this.ctx.defaultConfig.baseUrl,maxTurns:n.max_turns,depth:r+1,maxDepth:o,...n.cwd!==void 0?{cwd:n.cwd}:{}},u;if(this.ctx.childProviderFactory&&r<o){s=new G({parentAbortSignal:e.signal,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),u=ar(e.signal);let _=new t({subagentManager:s,parentSession:u,defaultConfig:this.ctx.defaultConfig,...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:r+1,maxDepth:o,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}}),T=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,e.signal):void 0;d.provider=this.ctx.childProviderFactory({childExecutor:_,...T!==void 0?{childSkillExecutor:T}:{},...d.model!==void 0?{model:d.model}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}})}let p;try{p=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:e.id,config:d,idPrefix:n.id_prefix,agentType:n.id_prefix&&n.id_prefix!=="agent-tool"?Xe(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":Xe(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:!0}),u!==void 0&&(u.sessionId=p.id)}catch(_){let T=_ instanceof Error?_.message:String(_);return bs({...i,event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:bn(T),depth:r}),{content:`Failed to fork subagent: ${T}`,isError:!0}}if(n.mode==="background"){let _=this.ctx.backgroundRegistry;if(!_)return await p.teardown().catch(I=>$("subagent-executor: handle teardown failed: "+(I instanceof Error?I.message:String(I)))),{content:'Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired. Re-issue the call with mode="foreground" or run inside `afk interactive`.',isError:!0};let T;try{T=_.register({handle:p,prompt:n.prompt,model:d.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(I){if(I instanceof ys)return await p.teardown().catch(D=>$("subagent-executor: handle teardown failed after cap error: "+(D instanceof Error?D.message:String(D)))),{content:I.message,isError:!0};throw I}let P={status:"running",jobId:T.jobId,subagentId:T.subagentId,label:T.label,message:`Background subagent started (jobId=${T.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${T.jobId} or ask the user to join.`};return{content:JSON.stringify(P)}}let f=()=>{p.cancel()};e.signal.addEventListener("abort",f,{once:!0});let h=Date.now(),g=this.ctx.parentSession.sessionId,v=!1,b,E=new Promise(_=>{b=_}),w,k=new Promise(_=>{w=_});this.promotionTriggers.set(p.id,{fire:b,ready:k});let A=p.runToResult(n.prompt);try{let _=await Promise.race([A.then(x=>({kind:"result",result:x})),E.then(()=>({kind:"promote"}))]);if(_.kind==="promote"){let x=this.ctx.backgroundRegistry;if(x)try{let F=x.adoptRunning({handle:p,runPromise:A,prompt:n.prompt,model:d.model??"sonnet",parentSessionId:g});return v=!0,e.signal.removeEventListener("abort",f),w({jobId:F.jobId,label:F.label}),{content:JSON.stringify({status:"running",jobId:F.jobId,subagentId:F.subagentId,label:F.label,message:`Subagent backgrounded by user (jobId=${F.jobId}). It keeps running detached and its result will NOT auto-inject into this context. Retrieve it via /bgsub:join ${F.jobId}.`})}}catch(F){$("subagent-executor: promotion failed, staying foreground: "+(F instanceof Error?F.message:String(F))),w(null)}else w(null)}let T=_.kind==="result"?_.result:await A;if(T.status==="succeeded"&&T.message){let x=T.message.content,F=typeof x=="string"?x:JSON.stringify(x),O=T.trace;return bs({...i,event:"subagent.completed",subagent_id:p.id,parent_session_id:g,status:T.status,duration_ms:Date.now()-h,content_chars:F.length,depth:r,tool_call_count:O?.toolCalls.length,thinking_present:O?.thinkingPresent,tool_names:O?.toolCalls.length?JSON.stringify([...new Set(O.toolCalls.map(L=>L.name))]):void 0}),{content:F}}let P=T.error?.message??"Subagent failed with no output",I=T.trace;bs({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:g,status:T.status,duration_ms:Date.now()-h,error_message:bn(P),schema_error:T.schemaError?bn(T.schemaError.message):void 0,partial_output_chars:wg(T.partialOutput),depth:r,tool_call_count:I?.toolCalls.length,thinking_present:I?.thinkingPresent,tool_names:I?.toolCalls.length?JSON.stringify([...new Set(I.toolCalls.map(x=>x.name))]):void 0});let D=Ax({status:T.status,errorMessage:P,schemaErrorMessage:T.schemaError?.message,partialOutput:T.partialOutput,subagentId:p.id});return{content:JSON.stringify(D),isError:!0}}catch(_){let T=_ instanceof Error?_.message:String(_);throw bs({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:g,status:"failed",duration_ms:Date.now()-h,error_message:bn(T),depth:r}),_}finally{this.promotionTriggers.delete(p.id),w(null),v||(e.signal.removeEventListener("abort",f),await s?.teardownAll(),await p.teardown())}}}});function vg(t,e){return`Skill tool not available at nesting depth ${t} (max ${e}). ${Tx}`}var Tx,Sg=y(()=>{"use strict";Tx="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function kg(t){return xx.has(t)}var xx,_g=y(()=>{"use strict";xx=new Set});function Eg(t){for(let e of Rx)e(t)}function Ag(t){for(let e of Px)e(t)}var Rx,Px,Tg=y(()=>{"use strict";Rx=new Set,Px=new Set});function xg(t){return Ix.has(t)}function Mx(t,e=Cx){return t.length<=e?t:t.slice(0,e)+"\u2026"}function Ox(t){if(typeof t!="object"||t===null)return;let e=t.name;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function Dx(t){if(typeof t!="object"||t===null)throw new Error("Skill tool input must be an object");let e=t,n=e.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=e.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var Ix,Cx,kn,bc=y(()=>{"use strict";be();ie();yn();Sn();hc();Sg();gc();tn();Ct();Te();Qe();_g();Tg();le();ct();Ix=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","intent-lock","long-bash-gate","exploration-gate","irreversible-action-gate","safe-destruct","plan-probe"]);Cx=240;kn=class{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;pluginBodies=null;currentCwd;setCwd(e){this.currentCwd=e}sessionIdentity(){return this.ctx.surface!==void 0?{origin:at(this.ctx.surface),actor:Pe(this.ctx.depth)}:{}}async execute(e){if(e.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??vn;if(n>=r){let c=Ox(e.input);return Z({...this.sessionIdentity(),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:c}).catch(()=>{}),{content:vg(n,r),isError:!0}}let o;try{o=Dx(e.input)}catch(c){return{content:`Skill tool input validation failed: ${c instanceof Error?c.message:String(c)}`,isError:!0}}try{let c=Le(o.name);return await this.executeRegistrySkill(c,o.arguments,e)}catch{}let s=this.getPluginSkillBody(o.name);if(s){if(s.context==="fork"){let l=s.readOnly===!0||yc.has(o.name);return await this.executePluginSkill(o.name,s.body,s.pluginPath,o.arguments,e,l,s.allowedTools)}let c=s.body.replace(/\$\{?PLUGIN_ROOT\}?/g,()=>s.pluginPath);return this.executeLoadedPluginSkill(o.name,c,o.arguments,e)}let a=Bt(this.ctx.pluginConfigs).map(c=>c.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(e.context==="fork")return this.executeForkedRegistrySkill(e,n,r);if(e.context==="load")return this.executeLoadedRegistrySkill(e,n,r);let o=kg(e.name);o&&Ag(e.name);let s=this.ctx.depth??0;Z({...this.sessionIdentity(),event:"skill.dispatched",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...xg(e.name)?{is_gate:!0}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{});let i=Date.now(),a,c;try{c=await e.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r)})}catch(d){a=d}finally{let d=Date.now()-i;o&&Eg({skillName:e.name,durationMs:d,...a!==void 0?{isError:!0}:{}});let u=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof c=="string"?c.length:c!=null?JSON.stringify(c).length:0:void 0;Z({...this.sessionIdentity(),event:"skill.completed",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:d,depth:s,...p!==void 0?{content_chars:p}:{},...u!==void 0?{error_message:Mx(u)}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof c=="string"?c:c!=null?JSON.stringify(c):"Skill completed successfully."}}buildForkedChildConfig(e,n,r=!1,o){let s=this.ctx.depth??0,i=this.ctx.maxDepth??vn,a={...e},c=r&&o!==void 0?o.filter(f=>ws.includes(f)):r?[...ws]:o,l=r;if(!this.ctx.childProviderFactory||s>=i)return r?a.provider=Rg(a.model):c!==void 0&&(a.provider=Pg(c,a.model)),{childConfig:a,childManager:void 0};let d=new G({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),u=new wn({subagentManager:d,parentSession:ar(n),defaultConfig:{model:a.model,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{}},...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:s+1,maxDepth:i,...this.currentCwd!==void 0?{cwd:this.currentCwd}:{},...this.ctx.backgroundRegistry!==void 0?{backgroundRegistry:this.ctx.backgroundRegistry}:{},...c!==void 0?{allowedTools:c}:{},...l?{readOnlyBash:!0}:{}}),p=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(s+1,i,n):void 0;return a.provider=this.ctx.childProviderFactory({childExecutor:u,...p!==void 0?{childSkillExecutor:p}:{},...a.model!==void 0?{model:a.model}:{},...c!==void 0?{allowedTools:c}:{},...l?{readOnlyBash:!0}:{}}),{childConfig:a,childManager:d}}async executeForkedRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=e.readOnly===!0||yc.has(e.name),s;try{if(s=Q(e.name)["system.md"],!s)return{content:`Skill "${e.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(p){return{content:`Failed to load skill prompts: ${p instanceof Error?p.message:String(p)}`,isError:!0}}let i=e.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",a=ir({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):Je(i),parentApiKey:this.ctx.apiKey}),c=new G({parentAbortSignal:r.signal,apiKey:a,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:ve(),...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),{childConfig:l,childManager:d}=this.buildForkedChildConfig({model:i,systemPrompt:s,isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal,o),u;try{u=await c.forkSubagent({parent:this.ctx.parentSession,config:l,idPrefix:`skill-fork-${e.name}`,parentId:r.id,agentType:e.name});let p=n&&n.length>0?n:`Run the ${e.name} skill now, following the instructions in your system prompt.`,f=await u.runToResult(p);return f.status==="succeeded"&&f.message?{content:f.message.content}:f.status==="cancelled"&&typeof f.partialOutput=="string"&&f.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
1090
1090
 
1091
1091
  ${f.partialOutput}`}:{content:f.error?.message??"Forked skill failed with no output",isError:!0}}catch(p){return{content:`Forked skill execution error: ${p instanceof Error?p.message:String(p)}`,isError:!0}}finally{u&&await u.teardown().catch($),await d?.teardownAll(),await c.teardownAll()}}formatLoadedSkillResult(e,n,r){let o=r&&r.trim().length>0?r.trim():"(none)";return{content:`${`[Skill "${e}" loaded into your current context \u2014 act on it now]
1092
1092
  The instructions below are your operating procedure for THIS task. Execute them immediately, in this session, using the tools you already have. This is an instruction set, not reference material: follow it directly \u2014 do not merely summarize or describe it. No sub-agent was forked; you are the one carrying it out.
@@ -1197,7 +1197,7 @@ Working directory (isolated): ${n}
1197
1197
 
1198
1198
  `+o}async function Mc(t,e){let n=t.map(c=>({hypothesis:c,decision:th(c)})).filter(c=>c.decision.verify);if(n.length===0)return{premise_verifications:[],hypotheses_to_test:t};let r=[],o;try{let c=await e(n.map(l=>l.hypothesis.claim));r=Array.isArray(c)?c:[]}catch(c){o=c instanceof Error?c.message:String(c)}let s=n.map((c,l)=>{let d=r[l];return o!==void 0?{hypothesis_id:c.hypothesis.id,claim:c.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:`shadow-verify dispatch failed: ${o}`,gate_reason:c.decision.reason}:d?{hypothesis_id:c.hypothesis.id,claim:c.hypothesis.claim,verdict:d.verdict,evidence:d.evidence,gate_reason:c.decision.reason}:{hypothesis_id:c.hypothesis.id,claim:c.hypothesis.claim,verdict:"INCONCLUSIVE",evidence:"no verifier result for this claim",gate_reason:c.decision.reason}}),i=new Set(s.filter(c=>c.verdict==="REFUTED").map(c=>c.hypothesis_id)),a=i.size===0?t:t.filter(c=>!i.has(c.id));return{premise_verifications:s,hypotheses_to_test:a}}var lR,Oc=y(()=>{"use strict";U();nh();Rs();lR=cR(aR)});import{fileURLToPath as fR}from"node:url";import{dirname as mR}from"node:path";var gR,LK,rh,oh=y(()=>{"use strict";gR=fR(import.meta.url),LK=mR(gR),rh={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:"vendored/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 sh(t){let e={description:t.description,prompt:t.systemPrompt};return t.allowedTools&&(e.tools=[...t.allowedTools]),t.model&&(e.model=t.model),e}var ih=y(()=>{"use strict"});import{z as ah}from"zod";import{execFile as hR}from"node:child_process";import{promisify as yR}from"node:util";import{tmpdir as bR}from"node:os";import{join as ch}from"node:path";function lh(){return async t=>_e.allowedTools.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed. Allowed tools: ${_e.allowedTools.join(", ")}`}}function wR(){return async t=>dh.includes(t)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${t} not allowed for git orchestrator. Allowed tools: ${dh.join(", ")}`}}function vR(){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.`}:_e.allowedTools.includes(e)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${e} not allowed. Allowed tools: ${_e.allowedTools.join(", ")}`}}function SR(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]}}async function kR(t,e,n,r,o,s,i,a,c="sonnet"){let l=ch(bR(),`diagnose-hyp-${t.id}-${Date.now()}`),d;try{await Is("git",["worktree","add","--detach",l,"HEAD"],{cwd:n});try{let{writeFile:h}=await import("node:fs/promises"),g="",v="";try{g=(await Is("git",["rev-parse","HEAD"],{cwd:n})).stdout.trim()}catch{}try{v=(await Is("git",["symbolic-ref","--short","HEAD"],{cwd:n})).stdout.trim()}catch{}await h(ch(l,".afk-worktree-meta.json"),JSON.stringify({owner:"diagnose",createdAt:new Date().toISOString(),baseSha:g,baseBranch:v},null,2),"utf-8")}catch{}d=await s.forkSubagent({parent:{sessionId:r},config:{model:c,systemPrompt:`${o}
1199
1199
 
1200
- You are testing in an isolated worktree at: ${l}`,canUseTool:vR()},idPrefix:`diagnose-verifier-${t.id}`,outputSchema:xs,...i?{parentId:i}:{}});let p=Cc(t,e,l,a??{skipped:!0,reason:"baseline not computed",exitCode:null,stdout:"",stderr:"",timedOut:!1}),f=await d.runToResult(p);return f.status!=="succeeded"||!f.output?{hypothesis_id:t.id,predicted_pass:!1,regressions:[],confidence:0,verification_log:`Verification failed: ${oe(f)}`}:f.output}catch(u){return{hypothesis_id:t.id,predicted_pass:!1,regressions:[],confidence:0,verification_log:`Error during verification: ${u instanceof Error?u.message:String(u)}`}}finally{if(d)try{await d.teardown()}catch{}try{await Is("git",["worktree","remove","--force",l],{cwd:n})}catch{}}}async function uh(t,e,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",s=(()=>{if(typeof t=="string")return{failure:t,repoPath:process.cwd(),context:"",maxHypotheses:4};if(typeof t=="object"&&t!==null){let q=t;if(typeof q.failure=="string")return{failure:q.failure,repoPath:q.repoPath||process.cwd(),context:q.context||"",maxHypotheses:Math.min(q.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 i=e.sessionId,a=Q("diagnose"),c=a["system.md"],l=a["research.md"],d=a["hypothesis.md"],u=a["verify.md"];if(!c||!l||!d||!u)throw new Error("diagnose skill missing required prompts (system.md, research.md, hypothesis.md, verify.md)");let p=new G({apiKey:r}),f=SR(s.context),h=Ac(s.failure,s.context),g=`Triage:
1200
+ You are testing in an isolated worktree at: ${l}`,canUseTool:vR()},idPrefix:`diagnose-verifier-${t.id}`,outputSchema:xs,...i?{parentId:i}:{}});let p=Cc(t,e,l,a??{skipped:!0,reason:"baseline not computed",exitCode:null,stdout:"",stderr:"",timedOut:!1}),f=await d.runToResult(p);return f.status!=="succeeded"||!f.output?{hypothesis_id:t.id,predicted_pass:!1,regressions:[],confidence:0,verification_log:`Verification failed: ${se(f)}`}:f.output}catch(u){return{hypothesis_id:t.id,predicted_pass:!1,regressions:[],confidence:0,verification_log:`Error during verification: ${u instanceof Error?u.message:String(u)}`}}finally{if(d)try{await d.teardown()}catch{}try{await Is("git",["worktree","remove","--force",l],{cwd:n})}catch{}}}async function uh(t,e,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",s=(()=>{if(typeof t=="string")return{failure:t,repoPath:process.cwd(),context:"",maxHypotheses:4};if(typeof t=="object"&&t!==null){let q=t;if(typeof q.failure=="string")return{failure:q.failure,repoPath:q.repoPath||process.cwd(),context:q.context||"",maxHypotheses:Math.min(q.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 i=e.sessionId,a=Q("diagnose"),c=a["system.md"],l=a["research.md"],d=a["hypothesis.md"],u=a["verify.md"];if(!c||!l||!d||!u)throw new Error("diagnose skill missing required prompts (system.md, research.md, hypothesis.md, verify.md)");let p=new G({apiKey:r}),f=SR(s.context),h=Ac(s.failure,s.context),g=`Triage:
1201
1201
  failure_type: ${h.failure_type}
1202
1202
  error_signature: ${h.error_signature}
1203
1203
  affected_area: ${h.affected_area}`,b=`${_e.systemPrompt}
@@ -1232,7 +1232,7 @@ ${JSON.stringify(P.git,null,2)}
1232
1232
 
1233
1233
  Original failure: ${s.failure}`,x;try{x=await I.runToResult(D)}finally{await I.teardown().catch(()=>{})}if(x.status!=="succeeded"||!x.output){if(x.schemaError){let q=x.message?.content||"(no response)";throw new Error(`hypothesis synthesis schema mismatch: ${x.schemaError.message}
1234
1234
  Raw response (first 500 chars): ${q.slice(0,500)}
1235
- Hint: model response must include a fenced JSON block with a hypotheses array.`)}throw new Error(`hypothesis synthesis failed: ${oe(x)}`)}let F=x.output.hypotheses.slice(0,s.maxHypotheses);if(F.length===0)return{reproducer:f,triage:h,hypotheses:[],verification_results:[],outcome:"no_hypotheses"};let{premise_verifications:O,hypotheses_to_test:L}=await Mc(F,async q=>{if(!n?.dispatchSkill)throw new Error("shadow-verify dispatch unavailable (no dispatchSkill in ctx)");let jt=JSON.stringify({claims:q,context:`Original failure: ${s.failure}
1235
+ Hint: model response must include a fenced JSON block with a hypotheses array.`)}throw new Error(`hypothesis synthesis failed: ${se(x)}`)}let F=x.output.hypotheses.slice(0,s.maxHypotheses);if(F.length===0)return{reproducer:f,triage:h,hypotheses:[],verification_results:[],outcome:"no_hypotheses"};let{premise_verifications:O,hypotheses_to_test:L}=await Mc(F,async q=>{if(!n?.dispatchSkill)throw new Error("shadow-verify dispatch unavailable (no dispatchSkill in ctx)");let jt=JSON.stringify({claims:q,context:`Original failure: ${s.failure}
1236
1236
 
1237
1237
  OUTPUT CONTRACT (required): after your verification, end your reply with a single fenced \`\`\`json block of exactly this shape \u2014 one entry per claim, in the SAME order you received them:
1238
1238
  {"verifications":[{"claim":"<echo of the claim>","verdict":"VERIFIED|REFUTED|INCONCLUSIVE","evidence":"<1-2 sentences; cite file:line or source>"}]}`}),Kt=await n.dispatchSkill("shadow-verify",jt);return Pc(Kt)});if(L.length===0)return{reproducer:f,triage:h,hypotheses:F,premise_verifications:O,verification_results:[],outcome:"no_hypotheses"};let M=f||s.failure,C;if(f)try{C=await Ic(f,s.repoPath)}catch(q){C={skipped:!0,reason:`baseline execution error: ${q instanceof Error?q.message:String(q)}`,exitCode:null,stdout:"",stderr:"",timedOut:!1}}else C={skipped:!0,reason:"no reproducer command detected",exitCode:null,stdout:"",stderr:"",timedOut:!1};let R=L.map(q=>kR(q,M,s.repoPath,i,u,p,w,C,o)),N=await Promise.all(R),j=N.filter(q=>q.predicted_pass&&q.regressions.length===0).slice().sort((q,jt)=>jt.confidence-q.confidence)[0]??N.find(q=>q.predicted_pass),Y=xc(F,N),Ee=j?F.find(q=>q.id===j.hypothesis_id):void 0,Ht=Y==="clear_winner"&&Ee&&Tc(Ee)?"spec":void 0;return{reproducer:f,triage:h,hypotheses:F,premise_verifications:O.length>0?O:void 0,winner:j?{hypothesis_id:j.hypothesis_id,verification_log:j.verification_log,proposed_fix:Ee?.proposed_fix||""}:void 0,verification_results:N,outcome:Y,recommended_next_skill:Ht}}var Is,dh,ph=y(()=>{"use strict";Te();ie();wc();ke();vc();oh();ih();Rs();Rc();Oc();Is=yR(hR);dh=[..._e.allowedTools,"Agent"]});var _R,fh=y(()=>{"use strict";Rs();Rc();Oc();ph();be();_R={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:uh,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."};de(_R)});async function ER(){throw new Error("get-started is a load skill; its handler should never be called directly. Invoke via the `skill` tool or `/get-started` slash command.")}var AR,mh=y(()=>{"use strict";be();AR={name:"get-started",description:"Guided first-run onboarding for AFK. Runs a preflight check (git repo, model provider, AFK.md, Exa/Telegram/service config), asks the user their name and gives a brief intro, detects importable Claude Code / Codex assets and offers `afk migrate`, walks optional capability setup (Exa Search, Telegram via /telegram-setup, background service via /service-setup), then recommends /init to generate project context and /clear to start fresh \u2014 ending by routing the user to their first task. Runs interactively in the current session.",handler:ER,context:"load",audience:"public",whenToUse:"When someone is setting up AFK for the first time or asks how to get going \u2014 triggers on `/get-started`, 'how do I start', 'set me up', 'onboard me', or a fresh install with no AFK.md and unconfigured capabilities. Best run in the interactive REPL."};de(AR)});function gh(){return`# Agent AFK
@@ -1393,21 +1393,21 @@ ${TR}
1393
1393
 
1394
1394
  ${r}`}function ae(){let t=S.AFK_MODEL??S.CLAUDE_MODEL;return _n(t)}function _n(t){return Je(t)}function Cs(t){let e=S.AFK_DEFAULT_SUBAGENT_MODEL;return e&&e.length>0?e:typeof t=="string"&&z(t)==="openai-compatible"?t:"sonnet"}function xR(t){if(t===void 0)return;if(t==="max")return Number.POSITIVE_INFINITY;if(t===""||t==="NaN")throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Expected a positive integer or 'max'.`);if(!/^\d+$/.test(t))throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Expected a positive integer or 'max'.`);let e=Number(t);if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw new Error(`Invalid --max-output-tokens value: ${JSON.stringify(t)}. Must be a positive integer.`);return e}function yh(){return xR(S.AFK_MAX_OUTPUT_TOKENS)}var TR,je=y(()=>{"use strict";we();sr();pt();dt();ft();jo();tn();U();TR=`# Operator configuration
1395
1395
 
1396
- The instructions below come from this operator's configuration (AFK.md, afk.config.json, or AFK_SYSTEM_PROMPT). Treat them as refinements layered on top of the operating posture above \u2014 follow them unless they conflict with the Priorities or Constraints already stated.`});async function bh(t,e,n,r,o="sonnet"){let i=Q("mint")["spec.md"];if(!i)throw new Error("mint skill missing spec.md prompt");let l=await(await new G(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:e},config:{model:o,systemPrompt:i,apiKey:ae()},idPrefix:"mint-spec",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Create a detailed specification for: ${t}`);if(l.status!=="succeeded"||!l.message)throw new Error(`spec phase failed: ${oe(l)}`);return l.message.content}var wh=y(()=>{"use strict";ie();ke();je();Te()});async function vh(t,e,n,r,o="sonnet"){let i=Q("mint")["research.md"];if(!i)throw new Error("mint skill missing research.md prompt");let l=await(await new G(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:e},config:{model:o,systemPrompt:i,apiKey:ae()},idPrefix:"mint-research",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Gather context and research for this specification:
1396
+ The instructions below come from this operator's configuration (AFK.md, afk.config.json, or AFK_SYSTEM_PROMPT). Treat them as refinements layered on top of the operating posture above \u2014 follow them unless they conflict with the Priorities or Constraints already stated.`});async function bh(t,e,n,r,o="sonnet"){let i=Q("mint")["spec.md"];if(!i)throw new Error("mint skill missing spec.md prompt");let l=await(await new G(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:e},config:{model:o,systemPrompt:i,apiKey:ae()},idPrefix:"mint-spec",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Create a detailed specification for: ${t}`);if(l.status!=="succeeded"||!l.message)throw new Error(`spec phase failed: ${se(l)}`);return l.message.content}var wh=y(()=>{"use strict";ie();ke();je();Te()});async function vh(t,e,n,r,o="sonnet"){let i=Q("mint")["research.md"];if(!i)throw new Error("mint skill missing research.md prompt");let l=await(await new G(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:e},config:{model:o,systemPrompt:i,apiKey:ae()},idPrefix:"mint-research",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Gather context and research for this specification:
1397
1397
 
1398
- ${t}`);if(l.status!=="succeeded"||!l.message)throw new Error(`research phase failed: ${oe(l)}`);return l.message.content}var Sh=y(()=>{"use strict";ie();ke();je();Te()});async function kh(t,e,n,r,o,s="sonnet"){let a=Q("mint")["plan.md"];if(!a)throw new Error("mint skill missing plan.md prompt");let l=await new G(r!==void 0?{cwd:r}:{}).forkSubagent({parent:{sessionId:n},config:{model:s,systemPrompt:a,apiKey:ae()},idPrefix:"mint-plan",phaseRole:"read-only",...o?{parentId:o}:{}}),d=`Specification:
1398
+ ${t}`);if(l.status!=="succeeded"||!l.message)throw new Error(`research phase failed: ${se(l)}`);return l.message.content}var Sh=y(()=>{"use strict";ie();ke();je();Te()});async function kh(t,e,n,r,o,s="sonnet"){let a=Q("mint")["plan.md"];if(!a)throw new Error("mint skill missing plan.md prompt");let l=await new G(r!==void 0?{cwd:r}:{}).forkSubagent({parent:{sessionId:n},config:{model:s,systemPrompt:a,apiKey:ae()},idPrefix:"mint-plan",phaseRole:"read-only",...o?{parentId:o}:{}}),d=`Specification:
1399
1399
  ${t}
1400
1400
 
1401
1401
  Research findings:
1402
1402
  ${e}
1403
1403
 
1404
- Create a detailed implementation plan based on the spec and research.`,u=await l.runToResult(d);if(u.status!=="succeeded"||!u.message)throw new Error(`plan phase failed: ${oe(u)}`);return u.message.content}var _h=y(()=>{"use strict";ie();ke();je();Te()});function RR(t){let e=/[\w./@-]*\.(?:ts|tsx|js|jsx|mjs|cjs|py|md|json|yaml|yml|toml|sh)\b/gi,n=new Set;for(let r of t.matchAll(e))n.add(r[0].toLowerCase());return n.size}async function Eh(t,e,n,r="sonnet"){if(RR(t)<3)return{kind:"skipped",reason:"too-few-files"};let s=!1;try{let i=Le("parallelize");return s=!0,{kind:"plan",plan:await i.handler({plan:t})}}catch(i){if(s)return{kind:"failed",error:`parallelize skill handler threw: ${i instanceof Error?i.message:String(i)}`}}try{let a=vs().get("parallelize");if(!a)return{kind:"skipped",reason:"skill-body-missing"};let c=new G({parentAbortSignal:e.abortSignal,apiKey:ae(),...e.cwd!==void 0?{cwd:e.cwd}:{}});try{let d=await(await c.forkSubagent({parent:{sessionId:e.sessionId},config:{model:r,systemPrompt:a.body,env:{PLUGIN_ROOT:a.pluginPath}},idPrefix:"mint-parallelize",...n?{parentId:n}:{}})).runToResult(JSON.stringify({plan:t}));return d.status==="succeeded"&&d.message?{kind:"plan",plan:d.message.content}:d.status!=="succeeded"?{kind:"failed",error:`parallelize subagent status=${d.status}${d.error?.message?`: ${d.error.message}`:""}`}:{kind:"failed",error:"parallelize subagent returned no message"}}finally{await c.teardownAll()}}catch(i){return{kind:"failed",error:`parallelize dispatch threw: ${i instanceof Error?i.message:String(i)}`}}}var Ah=y(()=>{"use strict";be();yn();ie();je()});function En(t){let e=ve();e&&e({type:"panel",spec:t},{subagentId:"__main__"})}var Ms=y(()=>{"use strict";Ct()});import{z as ot}from"zod";async function Th(t,e,n,r,o,s="sonnet"){let a=Q("mint")["build.md"];if(!a)throw new Error("mint skill missing build.md prompt");let l=await new G(r!==void 0?{cwd:r}:{}).forkSubagent({parent:{sessionId:n},config:{model:s,systemPrompt:a,apiKey:ae()},idPrefix:"mint-build",outputSchema:PR,...o?{parentId:o}:{}}),d=`Implementation plan:
1404
+ Create a detailed implementation plan based on the spec and research.`,u=await l.runToResult(d);if(u.status!=="succeeded"||!u.message)throw new Error(`plan phase failed: ${se(u)}`);return u.message.content}var _h=y(()=>{"use strict";ie();ke();je();Te()});function RR(t){let e=/[\w./@-]*\.(?:ts|tsx|js|jsx|mjs|cjs|py|md|json|yaml|yml|toml|sh)\b/gi,n=new Set;for(let r of t.matchAll(e))n.add(r[0].toLowerCase());return n.size}async function Eh(t,e,n,r="sonnet"){if(RR(t)<3)return{kind:"skipped",reason:"too-few-files"};let s=!1;try{let i=Le("parallelize");return s=!0,{kind:"plan",plan:await i.handler({plan:t})}}catch(i){if(s)return{kind:"failed",error:`parallelize skill handler threw: ${i instanceof Error?i.message:String(i)}`}}try{let a=vs().get("parallelize");if(!a)return{kind:"skipped",reason:"skill-body-missing"};let c=new G({parentAbortSignal:e.abortSignal,apiKey:ae(),...e.cwd!==void 0?{cwd:e.cwd}:{}});try{let d=await(await c.forkSubagent({parent:{sessionId:e.sessionId},config:{model:r,systemPrompt:a.body,env:{PLUGIN_ROOT:a.pluginPath}},idPrefix:"mint-parallelize",...n?{parentId:n}:{}})).runToResult(JSON.stringify({plan:t}));return d.status==="succeeded"&&d.message?{kind:"plan",plan:d.message.content}:d.status!=="succeeded"?{kind:"failed",error:`parallelize subagent status=${d.status}${d.error?.message?`: ${d.error.message}`:""}`}:{kind:"failed",error:"parallelize subagent returned no message"}}finally{await c.teardownAll()}}catch(i){return{kind:"failed",error:`parallelize dispatch threw: ${i instanceof Error?i.message:String(i)}`}}}var Ah=y(()=>{"use strict";be();yn();ie();je()});function En(t){let e=ve();e&&e({type:"panel",spec:t},{subagentId:"__main__"})}var Ms=y(()=>{"use strict";Ct()});import{z as ot}from"zod";async function Th(t,e,n,r,o,s="sonnet"){let a=Q("mint")["build.md"];if(!a)throw new Error("mint skill missing build.md prompt");let l=await new G(r!==void 0?{cwd:r}:{}).forkSubagent({parent:{sessionId:n},config:{model:s,systemPrompt:a,apiKey:ae()},idPrefix:"mint-build",outputSchema:PR,...o?{parentId:o}:{}}),d=`Implementation plan:
1405
1405
  ${t}
1406
1406
 
1407
1407
  `+(e?`Wave orchestration plan:
1408
1408
  ${JSON.stringify(e,null,2)}
1409
1409
 
1410
- `:"")+"Execute the implementation plan following TDD (test-first) principles.",u=await l.runToResult(d);if(u.status!=="succeeded"||!u.output)throw new Error(`build phase failed: ${oe(u)}`);let p=u.output,f={filesChanged:p.files_changed,testsPassed:p.tests_passed,notes:p.notes};return En({kind:"checkpoint",title:"build",body:[`Files changed: ${f.filesChanged.length}`,`Tests: ${f.testsPassed?"passed":"failed"}`,"Next: verify"]}),f}var PR,xh=y(()=>{"use strict";ie();ke();je();Te();Ms();PR=ot.object({status:ot.enum(["PASS","FAIL"]),status_reason:ot.string().optional(),files_changed:ot.array(ot.string()),tests_passed:ot.boolean(),build_passed:ot.boolean().optional(),verification_passed:ot.boolean().optional(),notes:ot.string()})});import{z as An}from"zod";async function Dc(t,e,n,r,o,s,i,a="sonnet"){let l=await new G(s!==void 0?{cwd:s}:{}).forkSubagent({parent:{sessionId:r},config:{model:a,systemPrompt:o,apiKey:ae()},idPrefix:`mint-verify-${t}`,outputSchema:IR,...i?{parentId:i}:{}}),d=`Plan:
1410
+ `:"")+"Execute the implementation plan following TDD (test-first) principles.",u=await l.runToResult(d);if(u.status!=="succeeded"||!u.output)throw new Error(`build phase failed: ${se(u)}`);let p=u.output,f={filesChanged:p.files_changed,testsPassed:p.tests_passed,notes:p.notes};return En({kind:"checkpoint",title:"build",body:[`Files changed: ${f.filesChanged.length}`,`Tests: ${f.testsPassed?"passed":"failed"}`,"Next: verify"]}),f}var PR,xh=y(()=>{"use strict";ie();ke();je();Te();Ms();PR=ot.object({status:ot.enum(["PASS","FAIL"]),status_reason:ot.string().optional(),files_changed:ot.array(ot.string()),tests_passed:ot.boolean(),build_passed:ot.boolean().optional(),verification_passed:ot.boolean().optional(),notes:ot.string()})});import{z as An}from"zod";async function Dc(t,e,n,r,o,s,i,a="sonnet"){let l=await new G(s!==void 0?{cwd:s}:{}).forkSubagent({parent:{sessionId:r},config:{model:a,systemPrompt:o,apiKey:ae()},idPrefix:`mint-verify-${t}`,outputSchema:IR,...i?{parentId:i}:{}}),d=`Plan:
1411
1411
  ${e}
1412
1412
 
1413
1413
  Build results:
@@ -1415,7 +1415,7 @@ ${JSON.stringify(n,null,2)}
1415
1415
 
1416
1416
  Mode: ${t}
1417
1417
 
1418
- Run ${t} verification on the implementation.`,u;try{u=await l.runToResult(d)}finally{await l.teardown().catch(()=>{})}if(u.status!=="succeeded"||!u.output)return{passed:!1,issues:[`${t} verification failed: ${oe(u)}`]};let p=u.output,f=p.status==="PASS";return{passed:f,issues:f?void 0:p.issues}}async function Os(t,e,n,r,o,s="sonnet"){let a=Q("mint")["verify.md"];if(!a)throw new Error("mint skill missing verify.md prompt");let[c,l,d]=await Promise.all([Dc("test",t,e,n,a,r,o,s),Dc("lint",t,e,n,a,r,o,s),Dc("design-review",t,e,n,a,r,o,s)]),u=[];c.issues&&u.push(...c.issues),l.issues&&u.push(...l.issues),d.issues&&u.push(...d.issues);let p={testsPassed:c.passed,lintPassed:l.passed,designReviewPassed:d.passed,...u.length>0?{issues:u}:{}},f=p.testsPassed&&p.lintPassed&&p.designReviewPassed,h=g=>g?"passed":"failed";return En({kind:f?"checkpoint":"diagnosis",title:"verify",body:[`Tests: ${h(p.testsPassed)} \xB7 Lint: ${h(p.lintPassed)}`,`Design review: ${h(p.designReviewPassed)}`,...f?["Next: ship"]:[`Issues: ${u.length} (heal loop will retry)`]]}),p}var IR,Fc=y(()=>{"use strict";ie();ke();je();Te();Ms();IR=An.object({status:An.enum(["PASS","FAIL"]),status_reason:An.string().optional(),issues:An.array(An.string()).default([]),summary:An.string().optional()})});async function Rh(t,e,n,r,o,s,i="sonnet"){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 a=Le("diagnose"),c=`Verification failures:
1418
+ Run ${t} verification on the implementation.`,u;try{u=await l.runToResult(d)}finally{await l.teardown().catch(()=>{})}if(u.status!=="succeeded"||!u.output)return{passed:!1,issues:[`${t} verification failed: ${se(u)}`]};let p=u.output,f=p.status==="PASS";return{passed:f,issues:f?void 0:p.issues}}async function Os(t,e,n,r,o,s="sonnet"){let a=Q("mint")["verify.md"];if(!a)throw new Error("mint skill missing verify.md prompt");let[c,l,d]=await Promise.all([Dc("test",t,e,n,a,r,o,s),Dc("lint",t,e,n,a,r,o,s),Dc("design-review",t,e,n,a,r,o,s)]),u=[];c.issues&&u.push(...c.issues),l.issues&&u.push(...l.issues),d.issues&&u.push(...d.issues);let p={testsPassed:c.passed,lintPassed:l.passed,designReviewPassed:d.passed,...u.length>0?{issues:u}:{}},f=p.testsPassed&&p.lintPassed&&p.designReviewPassed,h=g=>g?"passed":"failed";return En({kind:f?"checkpoint":"diagnosis",title:"verify",body:[`Tests: ${h(p.testsPassed)} \xB7 Lint: ${h(p.lintPassed)}`,`Design review: ${h(p.designReviewPassed)}`,...f?["Next: ship"]:[`Issues: ${u.length} (heal loop will retry)`]]}),p}var IR,Fc=y(()=>{"use strict";ie();ke();je();Te();Ms();IR=An.object({status:An.enum(["PASS","FAIL"]),status_reason:An.string().optional(),issues:An.array(An.string()).default([]),summary:An.string().optional()})});async function Rh(t,e,n,r,o,s,i="sonnet"){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 a=Le("diagnose"),c=`Verification failures:
1419
1419
  Tests: ${n.testsPassed?"PASS":"FAIL"}
1420
1420
  Lint: ${n.lintPassed?"PASS":"FAIL"}
1421
1421
  Design: ${n.designReviewPassed?"PASS":"FAIL"}
@@ -1430,7 +1430,7 @@ ${d}
1430
1430
  Verification issues:
1431
1431
  ${g}
1432
1432
 
1433
- Apply the fix and update the implementation.`,b=await h.runToResult(v);if(b.status!=="succeeded"||!b.message)throw new Error(`heal phase failed: ${oe(b)}`);let E=/^\s*FIX_APPLIED:\s*(true|false)/im.exec(b.message.content)?.[1]?.toLowerCase()==="true",w=r+1;if(!E)return{healed:!1,newHealIterations:w,newVerifyResults:n};if(!o.sessionId)throw new Error("Parent session ID required for verification");let k=await Os(t,e,o.sessionId,o.cwd,s,i);return{healed:k.testsPassed&&k.lintPassed&&k.designReviewPassed,newHealIterations:w,newVerifyResults:k}}catch{return{healed:!1,newHealIterations:r+1,newVerifyResults:n}}}var Ph=y(()=>{"use strict";be();ie();ke();je();Te();Fc()});async function Ih(t,e,n,r,o="sonnet"){let i=Q("mint")["ship.md"];if(!i)throw new Error("mint skill missing ship.md prompt");let c=await new G(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:e},config:{model:o,systemPrompt:i,apiKey:ae()},idPrefix:"mint-ship",...r?{parentId:r}:{}}),l=`Idea: ${t.idea}
1433
+ Apply the fix and update the implementation.`,b=await h.runToResult(v);if(b.status!=="succeeded"||!b.message)throw new Error(`heal phase failed: ${se(b)}`);let E=/^\s*FIX_APPLIED:\s*(true|false)/im.exec(b.message.content)?.[1]?.toLowerCase()==="true",w=r+1;if(!E)return{healed:!1,newHealIterations:w,newVerifyResults:n};if(!o.sessionId)throw new Error("Parent session ID required for verification");let k=await Os(t,e,o.sessionId,o.cwd,s,i);return{healed:k.testsPassed&&k.lintPassed&&k.designReviewPassed,newHealIterations:w,newVerifyResults:k}}catch{return{healed:!1,newHealIterations:r+1,newVerifyResults:n}}}var Ph=y(()=>{"use strict";be();ie();ke();je();Te();Fc()});async function Ih(t,e,n,r,o="sonnet"){let i=Q("mint")["ship.md"];if(!i)throw new Error("mint skill missing ship.md prompt");let c=await new G(n!==void 0?{cwd:n}:{}).forkSubagent({parent:{sessionId:e},config:{model:o,systemPrompt:i,apiKey:ae()},idPrefix:"mint-ship",...r?{parentId:r}:{}}),l=`Idea: ${t.idea}
1434
1434
 
1435
1435
  Specification:
1436
1436
  ${t.spec}
@@ -1446,7 +1446,7 @@ ${JSON.stringify(t.verifyResults,null,2)}
1446
1446
 
1447
1447
  Heal iterations used: ${t.healIterations}
1448
1448
 
1449
- Create a ship-ready summary with next steps.`,d=await c.runToResult(l);if(d.status!=="succeeded"||!d.message)throw new Error(`ship phase failed: ${oe(d)}`);let u=t.buildResults?.filesChanged.length??0,p=t.healIterations;return En({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${u}`,`Heal iterations: ${p}`,`Idea: ${t.idea}`]}),d.message.content}var Ch=y(()=>{"use strict";ie();ke();je();Te();Ms()});import{existsSync as Mh,mkdirSync as CR,readFileSync as MR,unlinkSync as OR,writeFileSync as DR}from"fs";import{dirname as FR,join as LR}from"path";function Lc(t){return LR(qe(),t,"mint-state.json")}function Oh(t,e){let n=Lc(t);CR(FR(n),{recursive:!0}),DR(n,JSON.stringify(e,null,2),"utf-8")}function NR(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 Dh(t){let e=Lc(t);if(!Mh(e))return null;try{let n=JSON.parse(MR(e,"utf-8"));return NR(n)?n:null}catch{return null}}function Nc(t){let e=Lc(t);if(Mh(e))try{OR(e)}catch{}}var Fh=y(()=>{"use strict";K()});function Ke(t,e,n){t.history.push({phase:e,output:n,timestamp:Date.now()})}function Bh(t){if("completed"in t&&"paused"in t)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}function BR(t){return t.length<=Nh?t:t.slice(0,Nh)+"\u2026"}function Hh(t){if(typeof t=="string"){if(Lh.test(t))return{userApproved:!0};if(t.length>1&&t.trimStart().startsWith("{"))try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null)return Hh(e)}catch{}return{idea:t}}if(typeof t=="object"&&t!==null){let e=t,n=typeof e.idea=="string"?e.idea:void 0;if(n!==void 0&&Lh.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 $h(t,e,n,r="sonnet"){if(!e.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let o=e.sessionId,s=e.cwd;try{t.currentPhase="research",t.research=await vh(t.spec,o,s,n,r),Ke(t,"research",t.research),t.currentPhase="plan",t.plan=await kh(t.spec,t.research,o,s,n,r),Ke(t,"plan",t.plan),t.currentPhase="parallelize";let i=await Eh(t.plan,e,n,r);if(i.kind==="plan")t.waveOrchestrationPlan=i.plan,Ke(t,"parallelize",JSON.stringify(i.plan));else if(i.kind==="skipped")t.waveOrchestrationPlan=void 0,Ke(t,"parallelize",`skipped: ${i.reason}`);else if(i.kind==="failed"){t.waveOrchestrationPlan=void 0;let l=BR(i.error);Ke(t,"parallelize",`failed: ${l}`),Z({event:"fallback.inline",parent_session_id:o,reason:"parallelize-dispatch-failed",error_message:l}),console.warn(`[mint] parallelize dispatch failed (single-lane fallback): ${l}`)}else{let l=i}t.currentPhase="build",t.buildResults=await Th(t.plan,t.waveOrchestrationPlan,o,s,n,r),Ke(t,"build",JSON.stringify(t.buildResults)),t.currentPhase="verify",t.verifyResults=await Os(t.plan,t.buildResults,o,s,n,r),Ke(t,"verify",JSON.stringify(t.verifyResults)),t.currentPhase="heal";let a=t.verifyResults.testsPassed&&t.verifyResults.lintPassed&&t.verifyResults.designReviewPassed;for(;!a&&t.healIterations<$R;){let l=await Rh(t.plan,t.buildResults,t.verifyResults,t.healIterations,e,n,r);t.healIterations=l.newHealIterations,t.verifyResults=l.newVerifyResults,a=l.healed,Ke(t,"heal",`Iterations: ${t.healIterations}, Success: ${a}`)}if(!a)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 c=await Ih(t,o,s,n,r);return Ke(t,"ship",c),{completed:!0,artifact:c,state:t}}catch(i){throw new Error(`mint failed at ${t.currentPhase}: ${i}`)}}function Uh(t,e){return Bh(e),("completed"in e||e.phase==="heal-failed")&&Nc(t),e}async function HR(t,e,n){let r=Hh(t);if(!e?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let o=e.sessionId,s=n?.callId,i=n?.defaultSubagentModel??n?.defaultModel??"sonnet";if(r.userApproved){let l=r.resumeFrom??Dh(o);if(!l)throw new Error("mint: no paused spec found for this session to continue. Run /mint <idea> first, then /mint --continue approved.");let d=await $h(l,e,s,i);return Uh(o,d)}if(!r.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");Nc(o);let a={currentPhase:"spec",idea:r.idea,healIterations:0,history:[]};try{a.spec=await bh(r.idea,o,e.cwd,s,i),Ke(a,"spec",a.spec)}catch(l){throw new Error(`mint failed at spec: ${l}`)}if(!r.autoApprove){Oh(o,a);let l={paused:!0,phase:"spec",spec:a.spec,state:a,nextStep:UR};return Bh(l),l}let c=await $h(a,e,s,i);return Uh(o,c)}var $R,Lh,UR,Nh,jR,jh=y(()=>{"use strict";be();wh();Sh();_h();Ah();Qe();xh();Fc();Ph();Ch();Fh();$R=2,Lh=/^\s*(?:--continue(?:\s+(?:approved|yes|y))?|approved?|yes|y|lgtm|sure)\s*$/i,UR='To approve and run the rest of the pipeline, say "approve", "yes", "sure", or "lgtm" \u2014 or invoke /mint --continue approved. The handler will reload the spec state from disk.';Nh=240;jR={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:HR,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, resume by invoking mint again with the literal string `"approved"` (or `"yes"`, `"lgtm"`, `"--continue approved"`) as the arguments. Equivalent JSON forms `{"userApproved": true}` and `{"idea": "approved"}` are also accepted. The handler reloads the spec state from disk and runs phases 2\u20138.',flags:["--continue"]};de(jR)});async function KR(){throw new Error("service-setup is a fork skill; its handler should never be called directly. Invoke via the `skill` tool or `/service-setup` slash command.")}var WR,Kh=y(()=>{"use strict";be();WR={name:"service-setup",description:"Install an AFK background process (telegram bot or daemon) as a macOS LaunchAgent so it auto-starts on login and relaunches on crash. Runs pre-flight checks (e.g., refuses to install the telegram service with an invalid token, which would otherwise crash-loop under KeepAlive), invokes `afk service install`, verifies with `afk service status`, and surfaces the management cheatsheet. macOS-only \u2014 gracefully refuses on other platforms.",handler:KR,context:"fork",whenToUse:"When the user wants to make `afk telegram start` or `afk daemon` always-on \u2014 i.e., survive reboot, crash, OOM. Triggers on phrasings like 'install as a service', 'auto-start on login', 'keep the bot running', 'launchd', 'always-on telegram', or right after a successful `/telegram-setup` when the user asks how to make it persistent."};de(WR)});async function GR(){throw new Error("telegram-setup is a fork skill; its handler should never be called directly. Invoke via the `skill` tool or `/telegram-setup` slash command.")}var qR,Wh=y(()=>{"use strict";be();qR={name:"telegram-setup",description:"Guide the user through first-time Telegram bot onboarding without leaking the bearer token. Walks the user to run `afk telegram setup` in a terminal for token entry, then uses the sanctioned `afk telegram check-token`/`discover-chat`/`set-allowed-chat` subcommands to validate and finish allowlist setup \u2014 the token never enters the model context. Works in REPL or Telegram. Use when the user wants to set up Telegram push notifications for the first time, or to debug a partially-configured install.",handler:GR,context:"fork",whenToUse:`When the user wants to set up Telegram bot notifications for the first time, or when they say something like "set up telegram", "connect telegram", "enable push", or you detect that TELEGRAM_BOT_TOKEN is unset and they're asking for notifications.`};de(qR)});function Gh(t){return t.startsWith("--")?t:`--${t}`}function zR(t){let e=new Set;for(let n of t.matchAll(VR))n[1]&&e.add(`--${n[1]}`);return Array.from(e).sort()}function $c(t){if(!t.startsWith(`---
1449
+ Create a ship-ready summary with next steps.`,d=await c.runToResult(l);if(d.status!=="succeeded"||!d.message)throw new Error(`ship phase failed: ${se(d)}`);let u=t.buildResults?.filesChanged.length??0,p=t.healIterations;return En({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${u}`,`Heal iterations: ${p}`,`Idea: ${t.idea}`]}),d.message.content}var Ch=y(()=>{"use strict";ie();ke();je();Te();Ms()});import{existsSync as Mh,mkdirSync as CR,readFileSync as MR,unlinkSync as OR,writeFileSync as DR}from"fs";import{dirname as FR,join as LR}from"path";function Lc(t){return LR(qe(),t,"mint-state.json")}function Oh(t,e){let n=Lc(t);CR(FR(n),{recursive:!0}),DR(n,JSON.stringify(e,null,2),"utf-8")}function NR(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 Dh(t){let e=Lc(t);if(!Mh(e))return null;try{let n=JSON.parse(MR(e,"utf-8"));return NR(n)?n:null}catch{return null}}function Nc(t){let e=Lc(t);if(Mh(e))try{OR(e)}catch{}}var Fh=y(()=>{"use strict";K()});function Ke(t,e,n){t.history.push({phase:e,output:n,timestamp:Date.now()})}function Bh(t){if("completed"in t&&"paused"in t)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}function BR(t){return t.length<=Nh?t:t.slice(0,Nh)+"\u2026"}function Hh(t){if(typeof t=="string"){if(Lh.test(t))return{userApproved:!0};if(t.length>1&&t.trimStart().startsWith("{"))try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null)return Hh(e)}catch{}return{idea:t}}if(typeof t=="object"&&t!==null){let e=t,n=typeof e.idea=="string"?e.idea:void 0;if(n!==void 0&&Lh.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 $h(t,e,n,r="sonnet"){if(!e.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let o=e.sessionId,s=e.cwd;try{t.currentPhase="research",t.research=await vh(t.spec,o,s,n,r),Ke(t,"research",t.research),t.currentPhase="plan",t.plan=await kh(t.spec,t.research,o,s,n,r),Ke(t,"plan",t.plan),t.currentPhase="parallelize";let i=await Eh(t.plan,e,n,r);if(i.kind==="plan")t.waveOrchestrationPlan=i.plan,Ke(t,"parallelize",JSON.stringify(i.plan));else if(i.kind==="skipped")t.waveOrchestrationPlan=void 0,Ke(t,"parallelize",`skipped: ${i.reason}`);else if(i.kind==="failed"){t.waveOrchestrationPlan=void 0;let l=BR(i.error);Ke(t,"parallelize",`failed: ${l}`),Z({event:"fallback.inline",parent_session_id:o,reason:"parallelize-dispatch-failed",error_message:l}),console.warn(`[mint] parallelize dispatch failed (single-lane fallback): ${l}`)}else{let l=i}t.currentPhase="build",t.buildResults=await Th(t.plan,t.waveOrchestrationPlan,o,s,n,r),Ke(t,"build",JSON.stringify(t.buildResults)),t.currentPhase="verify",t.verifyResults=await Os(t.plan,t.buildResults,o,s,n,r),Ke(t,"verify",JSON.stringify(t.verifyResults)),t.currentPhase="heal";let a=t.verifyResults.testsPassed&&t.verifyResults.lintPassed&&t.verifyResults.designReviewPassed;for(;!a&&t.healIterations<$R;){let l=await Rh(t.plan,t.buildResults,t.verifyResults,t.healIterations,e,n,r);t.healIterations=l.newHealIterations,t.verifyResults=l.newVerifyResults,a=l.healed,Ke(t,"heal",`Iterations: ${t.healIterations}, Success: ${a}`)}if(!a)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 c=await Ih(t,o,s,n,r);return Ke(t,"ship",c),{completed:!0,artifact:c,state:t}}catch(i){throw new Error(`mint failed at ${t.currentPhase}: ${i}`)}}function Uh(t,e){return Bh(e),("completed"in e||e.phase==="heal-failed")&&Nc(t),e}async function HR(t,e,n){let r=Hh(t);if(!e?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let o=e.sessionId,s=n?.callId,i=n?.defaultSubagentModel??n?.defaultModel??"sonnet";if(r.userApproved){let l=r.resumeFrom??Dh(o);if(!l)throw new Error("mint: no paused spec found for this session to continue. Run /mint <idea> first, then /mint --continue approved.");let d=await $h(l,e,s,i);return Uh(o,d)}if(!r.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");Nc(o);let a={currentPhase:"spec",idea:r.idea,healIterations:0,history:[]};try{a.spec=await bh(r.idea,o,e.cwd,s,i),Ke(a,"spec",a.spec)}catch(l){throw new Error(`mint failed at spec: ${l}`)}if(!r.autoApprove){Oh(o,a);let l={paused:!0,phase:"spec",spec:a.spec,state:a,nextStep:UR};return Bh(l),l}let c=await $h(a,e,s,i);return Uh(o,c)}var $R,Lh,UR,Nh,jR,jh=y(()=>{"use strict";be();wh();Sh();_h();Ah();Qe();xh();Fc();Ph();Ch();Fh();$R=2,Lh=/^\s*(?:--continue(?:\s+(?:approved|yes|y))?|approved?|yes|y|lgtm|sure)\s*$/i,UR='To approve and run the rest of the pipeline, say "approve", "yes", "sure", or "lgtm" \u2014 or invoke /mint --continue approved. The handler will reload the spec state from disk.';Nh=240;jR={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:HR,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, resume by invoking mint again with the literal string `"approved"` (or `"yes"`, `"lgtm"`, `"--continue approved"`) as the arguments. Equivalent JSON forms `{"userApproved": true}` and `{"idea": "approved"}` are also accepted. The handler reloads the spec state from disk and runs phases 2\u20138.',flags:["--continue"]};de(jR)});async function KR(){throw new Error("service-setup is a fork skill; its handler should never be called directly. Invoke via the `skill` tool or `/service-setup` slash command.")}var WR,Kh=y(()=>{"use strict";be();WR={name:"service-setup",description:"Install an AFK background process (telegram bot or daemon) as a macOS LaunchAgent so it auto-starts on login and relaunches on crash. Runs pre-flight checks (e.g., refuses to install the telegram service with an invalid token, which would otherwise crash-loop under KeepAlive), invokes `afk service install`, verifies with `afk service status`, and surfaces the management cheatsheet. macOS-only \u2014 gracefully refuses on other platforms.",handler:KR,context:"fork",whenToUse:"When the user wants to make `afk telegram start` or `afk daemon` always-on \u2014 i.e., survive reboot, crash, OOM. Triggers on phrasings like 'install as a service', 'auto-start on login', 'keep the bot running', 'launchd', 'always-on telegram', or right after a successful `/telegram-setup` when the user asks how to make it persistent."};de(WR)});async function GR(){throw new Error("telegram-setup is a fork skill; its handler should never be called directly. Invoke via the `skill` tool or `/telegram-setup` slash command.")}var qR,Wh=y(()=>{"use strict";be();qR={name:"telegram-setup",description:"Guide the user through first-time Telegram bot onboarding without leaking the bearer token. Walks the user to run `afk telegram setup` in a terminal for token entry, then uses the sanctioned `afk telegram check-token`/`discover-chat`/`set-allowed-chat` subcommands to validate and finish allowlist setup \u2014 the token never enters the model context. Works in REPL or Telegram. Use when the user wants to set up Telegram push notifications for the first time, or to debug a partially-configured install.",handler:GR,context:"fork",whenToUse:`When the user wants to set up Telegram bot notifications for the first time, or when they say something like "set up telegram", "connect telegram", "enable push", or you detect that TELEGRAM_BOT_TOKEN is unset and they're asking for notifications.`};de(qR)});function Gh(t){return t.startsWith("--")?t:`--${t}`}function zR(t){let e=new Set;for(let n of t.matchAll(VR))n[1]&&e.add(`--${n[1]}`);return Array.from(e).sort()}function $c(t){if(!t.startsWith(`---
1450
1450
  `))return{frontmatter:null,frontmatterFlags:null,body:t};let e=t.indexOf(`
1451
1451
  ---
1452
1452
  `,4);if(e===-1)return{frontmatter:null,frontmatterFlags:null,body:t};let n=t.slice(4,e),r=t.slice(e+5),o={},s=null,i=n.split(`
@@ -1470,7 +1470,7 @@ ${e.body}`)}var VR,Vh=y(()=>{"use strict";VR=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
1470
1470
 
1471
1471
  `+n},{role:"assistant",content:by},...t.slice(e)]}function ky(t,e,n){let r=xP(t.slice(0,e)),o=yy.length+2+n.length+by.length,s=Math.max(0,r-o);return Math.round(s/4)}function TP(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=_y(o.input);e.push(`[tool call: ${i} ${a}]`)}else if(s==="tool_result"){let i=o.content;e.push(`[tool result: ${Ey(i)}]`)}else s==="image"?e.push("[image]"):s==="document"&&e.push("[document]")}e.push("")}return e.join(`
1472
1472
  `).trim()}function _y(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function Ey(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 xP(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+=_y(r.input).length:o==="tool_result"&&(e+=Ey(r.content).length)}return e}var EP,yy,by,Ay=y(()=>{"use strict";EP=["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(`
1473
- `),yy="[Compacted summary of earlier conversation]",by="Acknowledged. Continuing from the summary above."});import{randomUUID as RP}from"node:crypto";async function Ty(t){let{state:e,abort:n,retry:r,initSessionId:o,traceWriter:s}=t,i=e.messages.length;if(e.closed)return{compacted:!1,reason:"session-closed",messagesBefore:i,messagesAfter:i};if(!n.isIdle())return{compacted:!1,reason:"turn-in-flight",messagesBefore:i,messagesAfter:i};let a=MP(),c=wy(e.messages,a);if(c<0)return{compacted:!1,reason:"history-too-short",messagesBefore:i,messagesAfter:i};if(c===0)return{compacted:!1,reason:"nothing-to-summarize",messagesBefore:i,messagesAfter:i};let l=e.messages.slice(0,c),d=OP(),u=vy(l,d,CP),p=n.begin(),f;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let b=Oe(r.authMode,o,RP()),E=r.client,w=await Promise.resolve(E.messages.create(u,{headers:b,signal:p.signal}));f=await DP(w)}catch(b){return p.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(b instanceof Error?b.message:String(b)),messagesBefore:i,messagesAfter:i}}finally{n.clear(p)}if(f.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let h=ky(e.messages,c,f),g=Sy(e.messages,c,f);e.messages.splice(0,e.messages.length,...g);let v=e.messages.length;return Zd(s,{trigger:"manual",preCompactionMessages:l,summary:f,keptTailCount:i-c,keepLastNConfig:a,messagesBefore:i,messagesAfter:v,tokensSavedEstimate:h}),{compacted:!0,messagesBefore:i,messagesAfter:v,tokensSavedEstimate:h}}function MP(){let t=S.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 PP}function OP(){let t=S.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?se(t)??t:IP}async function DP(t){let e="";for await(let n of t)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(e+=r.text)}return e}var PP,IP,CP,xy=y(()=>{"use strict";Et();Ay();ee();De();U();PP=2,IP="claude-haiku-4-5-20251001",CP=1024});import{randomUUID as Ry}from"node:crypto";var FP,$s,Py=y(()=>{"use strict";Bn();Et();Ui();Hi();Ki();yn();as();De();ey();ny();ry();hy();xy();lc();FP=[{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"}],$s=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;traceWriter;state;abort;retry;cwdDependentsFactory;onPermissionMode;mcpManager;constructor(e){this.initSessionId=e.sessionId??Ry(),this.promptStream=e.promptStream,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.thinking=e.thinking,e.effort!==void 0&&(this.effort=e.effort),e.baseUrl!==void 0&&(this.baseUrl=e.baseUrl),this.traceWriter=e.traceWriter,this.cwdDependentsFactory=e.cwdDependentsFactory,this.onPermissionMode=e.onPermissionMode,this.mcpManager=e.mcpManager,this.retry=new Ns({client:e.client,authMode:e.authMode,initSessionId:this.initSessionId,...e.tokenRefresher?{tokenRefresher:e.tokenRefresher}:{},autoResumeOnUsageLimit:e.autoResumeOnUsageLimit??!0}),this.state=ty({model:e.model,...e.requestedModel!==void 0?{requestedModel:e.requestedModel}:{},permissionMode:e.permissionMode??"default",userSystem:e.userSystem,toolDispatcher:e.toolDispatcher,...e.initialMessages?{initialMessages:e.initialMessages}:{},...e.autoCompactThreshold!==void 0?{autoCompactThreshold:e.autoCompactThreshold}:{}}),this.abort=new Fs}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.state.currentModel,permissionMode:this.state.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:this.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.retry.authMode,version:"anthropic-direct-v1"}};let n=this.promptStream[Symbol.asyncIterator]();try{for(;!this.state.closed;){let r=await Promise.race([n.next(),this.abort.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=this.abort.begin();if(i.signal.aborted){this.abort.clear(i);return}Zh(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),c=Oe(this.retry.authMode,this.initSessionId,Ry(),this.effort!==void 0),l={client:this.retry.client,messages:this.state.messages,system:a,tools:this.tools,toolDispatcher:this.state.toolDispatcher,model:this.state.currentModel,maxTokens:this.maxTokens,headers:c,signal:i.signal,ctx:{sessionId:this.initSessionId},...this.thinking!==void 0?{thinking:this.thinking}:{},...this.effort!==void 0?{effort:this.effort}:{},...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{},...this.traceWriter?{traceWriter:this.traceWriter}:{},onUsageProgress:u=>{this.state.lastUsage=u}},d=!1;try{for await(let u of this.retry.turnWithRetries(l,()=>this.state.closed)){if(this.state.closed)return;u.type==="turn.completed"&&(this.state.lastUsage=u.usage,this.abort.clear(i)),(u.type==="turn.completed"||u.type==="error")&&(d=!0),yield u}}catch(u){if(this.state.closed)return;if(i.signal.aborted){this.abort.clear(i),d||(yield this.makeInterruptedTurnEvent());continue}yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}finally{this.abort.clear(i)}if(this.state.closed)return;if(i.signal.aborted){d||(yield this.makeInterruptedTurnEvent());continue}if(this.state.autoCompactThreshold!==void 0&&!this.state.closed){let u=this.state.lastUsage,p=nr(this.state.requestedModel);if(u!==null&&p>0){let f=hn(u);jm(f,p,this.state.autoCompactThreshold)&&await this.compact()}}}}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.state.userSystem,r=[];e&&e.length>0&&r.push(...e),n&&n.length>0&&r.push({type:"text",text:n});let o=Vd(this.state.currentPermissionMode);o!==null&&r.push(o);let s=zd(this.state.currentPermissionMode);return s!==null&&r.push(s),r.length===0?null:co({baseUrl:this.baseUrl})?Wd(r,lo()):r}async interrupt(){this.abort.requestAbort("interrupted")}makeInterruptedTurnEvent(){return{type:"turn.completed",usage:{stopReason:"interrupted",resultSubtype:"interrupted",isError:!1},sessionId:this.initSessionId}}async setModel(e){e!==void 0&&e.length>0&&(this.state.requestedModel=e,this.state.currentModel=se(e)??e)}async setPermissionMode(e){this.state.currentPermissionMode=e;let n=Fe(e);this.state.toolDispatcher.setAllowAll?.(n),this.onPermissionMode?.(e)}setCwd(e){if(this.state.toolDispatcher.setResolveBase?.(e),!this.cwdDependentsFactory)return;let{userSystem:n,dispatcher:r}=this.cwdDependentsFactory(e);this.state.userSystem=n,this.state.toolDispatcher=r}async supportedCommands(){try{return Bt().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return FP.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){let e=this.state.lastUsage,n=nr(this.state.requestedModel),r;if(e&&n>0){let i=hn(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=ds(e);return{tools:[],agents:[],isAutoCompactEnabled:this.state.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.mcpManager?this.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{subscriptionType:this.retry.authMode==="oauth"?"claude-subscription":"api-key"}}async reauth(){return this.retry.forceClientRefresh()}async rewindFiles(e,n){return{canRewind:!1,error:"anthropic-direct provider does not support file checkpoint rewind"}}async compact(){return Ty({state:this.state,abort:this.abort,retry:this.retry,initSessionId:this.initSessionId,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}close(){this.state.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed()}}});function Gc(t){if(t===void 0||t===!1)return;if(t===!0)return NP;let e=t.threshold;if(!(typeof e!="number"||!Number.isFinite(e)||e<=0||e>=1))return e}function qc(t,e){let n=is(e),r=t.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let s=`max:${e}:${o}`;return Us.has(s)||(Us.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function Iy(t){if(!t||t.length===0)return;let e=[];for(let n of t)n.user.length>0&&e.push({role:"user",content:n.user}),n.assistant.length>0&&e.push({role:"assistant",content:n.assistant});return e.length>0?e:void 0}function Vc(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&LP(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(e*$P),o=Math.max(1024,e-1-r),s=t.budgetTokens!==void 0&&Number.isFinite(t.budgetTokens)?Math.floor(t.budgetTokens):void 0,i=Math.min(Math.max(s??o,1024),o);if(s!==void 0&&s>o){let a=`think:${n??"default"}:${s}:${e}`;Us.has(a)||(Us.add(a),console.warn(`[afk] thinking budgetTokens ${s} leaves too little of max_tokens ${e} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:i,display:"summarized"}}}}function zc(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-4-[678]/.test(n))return"max"}var LP,NP,Us,$P,Jc=y(()=>{"use strict";as();LP=t=>/opus-4-(7|[89])/.test(t),NP=.9;Us=new Set,$P=.25});var Bs,Yc,Xc,aq,Cy,My,Oy=y(()=>{"use strict";Bs=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
1473
+ `),yy="[Compacted summary of earlier conversation]",by="Acknowledged. Continuing from the summary above."});import{randomUUID as RP}from"node:crypto";async function Ty(t){let{state:e,abort:n,retry:r,initSessionId:o,traceWriter:s}=t,i=e.messages.length;if(e.closed)return{compacted:!1,reason:"session-closed",messagesBefore:i,messagesAfter:i};if(!n.isIdle())return{compacted:!1,reason:"turn-in-flight",messagesBefore:i,messagesAfter:i};let a=MP(),c=wy(e.messages,a);if(c<0)return{compacted:!1,reason:"history-too-short",messagesBefore:i,messagesAfter:i};if(c===0)return{compacted:!1,reason:"nothing-to-summarize",messagesBefore:i,messagesAfter:i};let l=e.messages.slice(0,c),d=OP(),u=vy(l,d,CP),p=n.begin(),f;try{if(p.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let b=Oe(r.authMode,o,RP()),E=r.client,w=await Promise.resolve(E.messages.create(u,{headers:b,signal:p.signal}));f=await DP(w)}catch(b){return p.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(b instanceof Error?b.message:String(b)),messagesBefore:i,messagesAfter:i}}finally{n.clear(p)}if(f.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let h=ky(e.messages,c,f),g=Sy(e.messages,c,f);e.messages.splice(0,e.messages.length,...g);let v=e.messages.length;return Zd(s,{trigger:"manual",preCompactionMessages:l,summary:f,keptTailCount:i-c,keepLastNConfig:a,messagesBefore:i,messagesAfter:v,tokensSavedEstimate:h}),{compacted:!0,messagesBefore:i,messagesAfter:v,tokensSavedEstimate:h}}function MP(){let t=S.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 PP}function OP(){let t=S.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?oe(t)??t:IP}async function DP(t){let e="";for await(let n of t)if(n.type==="content_block_delta"){let r=n.delta;r.type==="text_delta"&&typeof r.text=="string"&&(e+=r.text)}return e}var PP,IP,CP,xy=y(()=>{"use strict";Et();Ay();ee();De();U();PP=2,IP="claude-haiku-4-5-20251001",CP=1024});import{randomUUID as Ry}from"node:crypto";var FP,$s,Py=y(()=>{"use strict";Bn();Et();Ui();Hi();Ki();yn();as();De();ey();ny();ry();hy();xy();lc();FP=[{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"}],$s=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;baseUrl;traceWriter;state;abort;retry;cwdDependentsFactory;onPermissionMode;mcpManager;constructor(e){this.initSessionId=e.sessionId??Ry(),this.promptStream=e.promptStream,this.maxTokens=e.maxTokens,this.tools=e.tools,this.systemPrefix=e.systemPrefix,this.thinking=e.thinking,e.effort!==void 0&&(this.effort=e.effort),e.baseUrl!==void 0&&(this.baseUrl=e.baseUrl),this.traceWriter=e.traceWriter,this.cwdDependentsFactory=e.cwdDependentsFactory,this.onPermissionMode=e.onPermissionMode,this.mcpManager=e.mcpManager,this.retry=new Ns({client:e.client,authMode:e.authMode,initSessionId:this.initSessionId,...e.tokenRefresher?{tokenRefresher:e.tokenRefresher}:{},autoResumeOnUsageLimit:e.autoResumeOnUsageLimit??!0}),this.state=ty({model:e.model,...e.requestedModel!==void 0?{requestedModel:e.requestedModel}:{},permissionMode:e.permissionMode??"default",userSystem:e.userSystem,toolDispatcher:e.toolDispatcher,...e.initialMessages?{initialMessages:e.initialMessages}:{},...e.autoCompactThreshold!==void 0?{autoCompactThreshold:e.autoCompactThreshold}:{}}),this.abort=new Fs}async*[Symbol.asyncIterator](){yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.state.currentModel,permissionMode:this.state.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:this.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.retry.authMode,version:"anthropic-direct-v1"}};let n=this.promptStream[Symbol.asyncIterator]();try{for(;!this.state.closed;){let r=await Promise.race([n.next(),this.abort.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=this.abort.begin();if(i.signal.aborted){this.abort.clear(i);return}Zh(this.state.messages),this.state.messages.push({role:"user",content:s.content});let a=this.composeSystem(),c=Oe(this.retry.authMode,this.initSessionId,Ry(),this.effort!==void 0),l={client:this.retry.client,messages:this.state.messages,system:a,tools:this.tools,toolDispatcher:this.state.toolDispatcher,model:this.state.currentModel,maxTokens:this.maxTokens,headers:c,signal:i.signal,ctx:{sessionId:this.initSessionId},...this.thinking!==void 0?{thinking:this.thinking}:{},...this.effort!==void 0?{effort:this.effort}:{},...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{},...this.traceWriter?{traceWriter:this.traceWriter}:{},onUsageProgress:u=>{this.state.lastUsage=u}},d=!1;try{for await(let u of this.retry.turnWithRetries(l,()=>this.state.closed)){if(this.state.closed)return;u.type==="turn.completed"&&(this.state.lastUsage=u.usage,this.abort.clear(i)),(u.type==="turn.completed"||u.type==="error")&&(d=!0),yield u}}catch(u){if(this.state.closed)return;if(i.signal.aborted){this.abort.clear(i),d||(yield this.makeInterruptedTurnEvent());continue}yield{type:"error",error:u instanceof Error?u:new Error(String(u))};return}finally{this.abort.clear(i)}if(this.state.closed)return;if(i.signal.aborted){d||(yield this.makeInterruptedTurnEvent());continue}if(this.state.autoCompactThreshold!==void 0&&!this.state.closed){let u=this.state.lastUsage,p=nr(this.state.requestedModel);if(u!==null&&p>0){let f=hn(u);jm(f,p,this.state.autoCompactThreshold)&&await this.compact()}}}}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.state.userSystem,r=[];e&&e.length>0&&r.push(...e),n&&n.length>0&&r.push({type:"text",text:n});let o=Vd(this.state.currentPermissionMode);o!==null&&r.push(o);let s=zd(this.state.currentPermissionMode);return s!==null&&r.push(s),r.length===0?null:co({baseUrl:this.baseUrl})?Wd(r,lo()):r}async interrupt(){this.abort.requestAbort("interrupted")}makeInterruptedTurnEvent(){return{type:"turn.completed",usage:{stopReason:"interrupted",resultSubtype:"interrupted",isError:!1},sessionId:this.initSessionId}}async setModel(e){e!==void 0&&e.length>0&&(this.state.requestedModel=e,this.state.currentModel=oe(e)??e)}async setPermissionMode(e){this.state.currentPermissionMode=e;let n=Fe(e);this.state.toolDispatcher.setAllowAll?.(n),this.onPermissionMode?.(e)}setCwd(e){if(this.state.toolDispatcher.setResolveBase?.(e),!this.cwdDependentsFactory)return;let{userSystem:n,dispatcher:r}=this.cwdDependentsFactory(e);this.state.userSystem=n,this.state.toolDispatcher=r}async supportedCommands(){try{return Bt().map(n=>{let r={name:n.name,description:n.description};return n.argumentHint&&(r.argumentHint=n.argumentHint),r})}catch{return[]}}async supportedModels(){return FP.map(e=>({...e}))}async supportedAgents(){return[]}async getContextUsage(){let e=this.state.lastUsage,n=nr(this.state.requestedModel),r;if(e&&n>0){let i=hn(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=ds(e);return{tools:[],agents:[],isAutoCompactEnabled:this.state.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.mcpManager?this.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{subscriptionType:this.retry.authMode==="oauth"?"claude-subscription":"api-key"}}async reauth(){return this.retry.forceClientRefresh()}async rewindFiles(e,n){return{canRewind:!1,error:"anthropic-direct provider does not support file checkpoint rewind"}}async compact(){return Ty({state:this.state,abort:this.abort,retry:this.retry,initSessionId:this.initSessionId,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}close(){this.state.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed()}}});function Gc(t){if(t===void 0||t===!1)return;if(t===!0)return NP;let e=t.threshold;if(!(typeof e!="number"||!Number.isFinite(e)||e<=0||e>=1))return e}function qc(t,e){let n=is(e),r=t.maxOutputTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let o=Math.floor(r);if(o>n){let s=`max:${e}:${o}`;return Us.has(s)||(Us.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function Iy(t){if(!t||t.length===0)return;let e=[];for(let n of t)n.user.length>0&&e.push({role:"user",content:n.user}),n.assistant.length>0&&e.push({role:"assistant",content:n.assistant});return e.length>0?e:void 0}function Vc(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&LP(n))return{type:"adaptive",display:"summarized"};let r=Math.floor(e*$P),o=Math.max(1024,e-1-r),s=t.budgetTokens!==void 0&&Number.isFinite(t.budgetTokens)?Math.floor(t.budgetTokens):void 0,i=Math.min(Math.max(s??o,1024),o);if(s!==void 0&&s>o){let a=`think:${n??"default"}:${s}:${e}`;Us.has(a)||(Us.add(a),console.warn(`[afk] thinking budgetTokens ${s} leaves too little of max_tokens ${e} for the reply; clamping to ${o}.`))}return{type:"enabled",budget_tokens:i,display:"summarized"}}}}function zc(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-4-[678]/.test(n))return"max"}var LP,NP,Us,$P,Jc=y(()=>{"use strict";as();LP=t=>/opus-4-(7|[89])/.test(t),NP=.9;Us=new Set,$P=.25});var Bs,Yc,Xc,aq,Cy,My,Oy=y(()=>{"use strict";Bs=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
1474
1474
 
1475
1475
  - Use read_file before editing to verify the exact content you want to change.
1476
1476
  - Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
@@ -1528,7 +1528,7 @@ Use FTS5 syntax: "exact phrase", term1 AND term2, prefix*.`});import{mkdirSync a
1528
1528
  `;BP(i,l)}catch(c){let l=`[prompt-dump] Failed to write to ${i}: ${String(c)}
1529
1529
  `;process.stderr.write(l)}}var WP,GP,qP,Fy=y(()=>{"use strict";U();WP=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
1530
1530
  `,GP=/key|token|secret|password|credential|auth/i,qP=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,t=>`<REDACTED sk-ant length=${t[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,t=>`<REDACTED sk- length=${t[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,t=>`<REDACTED Bearer length=${t[0].length}>`],[/AKIA[A-Z0-9]{16}/g,t=>`<REDACTED AKIA length=${t[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,t=>`<REDACTED xox token length=${t[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,t=>`<REDACTED Telegram token length=${t[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,t=>`${t[1]}=<REDACTED length=${t[2].length}>`],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,t=>`${t[1]}=<REDACTED length=${t[2].length}>`]]});import Zc from"path";import{appendFileSync as YP,mkdirSync as XP}from"fs";import{dirname as QP}from"path";import Ly from"@anthropic-ai/sdk";function ZP(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}var ur,Ny,el,pe,eI,Ss=y(()=>{"use strict";Et();Nd();Un();Py();Bn();Jc();Jc();ua();Za();pt();Oy();Po();xo();De();yn();dt();Fy();K();U();ft();ct();ur="anthropic-direct",Ny="claude-sonnet-4-5-20250929",el=null,pe=class{name=ur;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;subagentExecutor;composeExecutor;surface;readOnlyMemory;readOnlyBash;mcpManager;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;constructor(e={}){let n=[...Ze];if(e.subagentExecutor&&n.push(Mt),e.skillExecutor&&n.push(Ot),e.composeExecutor&&n.push(Dt),e.readOnlyMemory===!0?n.push(qt):n.push(...lt),n.push($e),this.memoryStore=e.memoryStore??new fe,this.externalTools=e.tools,this.skillExecutor=e.skillExecutor,this.schemas=n,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.subagentExecutor=e.subagentExecutor,this.composeExecutor=e.composeExecutor,this.surface=e.surface??"cli",this.readOnlyMemory=e.readOnlyMemory===!0,this.readOnlyBash=e.readOnlyBash===!0,this.mcpManager=e.mcpManager,e.mcpManager){let r=e.mcpManager.onToolsRefreshed;e.mcpManager.onToolsRefreshed=o=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,r?.(o)}}e.clientFactory&&(this.providerFactory=e.clientFactory)}buildDispatcher(e,n){let r=ss(e,n?.cwd),o=Dn(this.memoryStore,void 0,this.surface);for(let[i,a]of o)this.readOnlyMemory&&i!=="memory_search"||r.set(i,a);if(n?.runtimeStateSource&&r.set("get_runtime_state",an(n.runtimeStateSource)),this.mcpManager){this._mcpToolsCache||(this._mcpToolsCache=this.mcpManager.getMcpTools()),this._mcpHandlersCache||(this._mcpHandlersCache=this.mcpManager.getMcpHandlers());for(let[i,a]of this._mcpHandlersCache)r.set(i,a)}let s=this._mcpToolsCache??[];return new et({handlers:r,allowAll:Fe(e),schemas:[...this.schemas,...s],hookRegistry:To(n?.hookRegistry,this.hookRegistry),permissions:this.mcpManager?Ro(this.permissions,this.mcpManager.getMcpToolWireNames()):this.permissions,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,cwd:n?.cwd,readRoots:n?.readRoots,writeRoots:n?.writeRoots,...n?.env!==void 0?{env:n.env}:{},sessionId:n?.sessionId,parentSessionId:n?.parentSessionId,...n?.traceWriter?{traceWriter:n.traceWriter}:{},readOnlyBash:this.readOnlyBash})}close(){this.memoryStore.close()}async complete(e){let n=e.apiKey&&e.apiKey.length>0?e.apiKey:S.ANTHROPIC_API_KEY||S.CLAUDE_CODE_OAUTH_TOKEN||"";if(!n)throw new Error(`${ur} complete() requires an API key or OAuth token (config apiKey, ANTHROPIC_API_KEY, or CLAUDE_CODE_OAUTH_TOKEN)`);let r={token:n,model:e.model??Ny,system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.signal&&(r.signal=e.signal);let o=this.providerFactory??el;return o&&(r.clientFactory=o),Ld(r)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e),e&&!this._currentCwd&&(this._currentCwd=e)}}addReadRoot(e,n="slash",r){this.ensureSharedRoots();let o=Zc.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this.appendProviderAuditLog({action:"grant-read",path:o,source:n,sessionId:r})}addWriteRoot(e,n="slash",r){this.ensureSharedRoots();let o=Zc.resolve(e);this._sharedReadRoots.includes(o)||this._sharedReadRoots.push(o),this._sharedWriteRoots.includes(o)||this._sharedWriteRoots.push(o),this.appendProviderAuditLog({action:"grant-write",path:o,source:n,sessionId:r})}revokeRoot(e,n="slash",r){if(!this._sharedReadRoots)return;let o=Zc.resolve(e);if(this._initialResolveBase&&o===this._initialResolveBase)return;let s=this._sharedReadRoots.indexOf(o);if(s!==-1&&this._sharedReadRoots.splice(s,1),this._sharedWriteRoots){let i=this._sharedWriteRoots.indexOf(o);i!==-1&&this._sharedWriteRoots.splice(i,1)}this.appendProviderAuditLog({action:"revoke",path:o,source:n,sessionId:r})}getGrants(){return{resolveBase:this._initialResolveBase,readRoots:this._sharedReadRoots?.slice()??[],writeRoots:this._sharedWriteRoots?.slice()??[],allowAll:Fe(this._currentPermissionMode)}}appendProviderAuditLog(e){try{let n=Gt();XP(QP(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??null,action:e.action,path:e.path,source:e.source});YP(n,r+`
1531
- `)}catch{}}query(e){let n=e.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:S.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:S.ANTHROPIC_API_KEY||S.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${ur} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Jt(o),i=Nn(o,s,n.baseUrl),a=this.providerFactory??el,c=a?a(i):new Ly(i),l=r?null:Md(s),d=ZP(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?se(n.model)??n.model:Ny,p=qc(n,u),f=n.permissionMode??"default";this._currentPermissionMode=f,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let h,g=Wn({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:u,providerName:ur,permissionMode:f,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>h instanceof et?h.toolDefs.map(M=>M.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});if((n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let M=n.sessionId,C=g.getWorkspace();Hn({sessionId:M,surface:this.surface,actor:Pe(n.depth),cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:ur,name:u},workspace:C,pid:process.pid}),process.once("exit",()=>{Ye(M)}),process.once("SIGINT",()=>{Ye(M),process.exit(130)}),process.once("SIGTERM",()=>{Ye(M),process.exit(143)})}h=this.externalTools?Gn(this.externalTools,g):this.buildDispatcher(f,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:g,hookRegistry:n.hookRegistry});let b=h instanceof et?[...h.toolDefs]:[...Ze,$e],E=n.isSkillDispatch?b.filter(M=>M.name!=="ask_question"&&M.name!=="terminal_font_size"):n.isNonInteractive?b.filter(M=>M.name!=="ask_question"):b,w=this.skillExecutor?Qh():"",k=n.cwd||process.cwd(),A=n.isSkillDispatch?Bs:`${Bs}
1531
+ `)}catch{}}query(e){let n=e.config,r=typeof n.baseUrl=="string"&&n.baseUrl.length>0,o=r?n.apiKey&&n.apiKey.length>0?n.apiKey:S.AFK_LOCAL_API_KEY||"local":n.apiKey&&n.apiKey.length>0?n.apiKey:S.ANTHROPIC_API_KEY||S.CLAUDE_CODE_OAUTH_TOKEN||"";if(!o||o.length===0)throw new Error(`${ur} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let s=Jt(o),i=Nn(o,s,n.baseUrl),a=this.providerFactory??el,c=a?a(i):new Ly(i),l=r?null:Md(s),d=ZP(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?oe(n.model)??n.model:Ny,p=qc(n,u),f=n.permissionMode??"default";this._currentPermissionMode=f,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let h,g=Wn({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:u,providerName:ur,permissionMode:f,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>h instanceof et?h.toolDefs.map(M=>M.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});if((n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let M=n.sessionId,C=g.getWorkspace();Hn({sessionId:M,surface:this.surface,actor:Pe(n.depth),cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:ur,name:u},workspace:C,pid:process.pid}),process.once("exit",()=>{Ye(M)}),process.once("SIGINT",()=>{Ye(M),process.exit(130)}),process.once("SIGTERM",()=>{Ye(M),process.exit(143)})}h=this.externalTools?Gn(this.externalTools,g):this.buildDispatcher(f,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:g,hookRegistry:n.hookRegistry});let b=h instanceof et?[...h.toolDefs]:[...Ze,$e],E=n.isSkillDispatch?b.filter(M=>M.name!=="ask_question"&&M.name!=="terminal_font_size"):n.isNonInteractive?b.filter(M=>M.name!=="ask_question"):b,w=this.skillExecutor?Qh():"",k=n.cwd||process.cwd(),A=n.isSkillDispatch?Bs:`${Bs}
1532
1532
 
1533
1533
  ${Yc}
1534
1534
 
@@ -1700,7 +1700,7 @@ Status written to: ${Ur()}
1700
1700
  ${o.join(`
1701
1701
  `)}`)}this.nameRegistry=r.tools}static async fromConfig(e,n={}){if(n.warnings&&n.warnings.length>0)for(let l of n.warnings)console.warn(`[mcp] ${l}`);let r=new Map,o=[],s={manager:void 0};for(let[l,d]of Object.entries(e)){let u=Ar(l);if(u!==l&&console.warn(`[mcp] server name "${l}" sanitized to "${u}" for wire encoding`),d.disabled){r.set(l,{client:void 0,tools:[],state:{serverName:l,config:d,status:"disabled",toolCount:0}});continue}let f={client:void 0,tools:[],state:{serverName:l,config:d,status:"connecting",toolCount:0}};r.set(l,f);let h=new Rn(l,d);f.client=h,h.onTransportError=v=>{f.state.status="error",f.state.error=ci(v.message,200),console.warn(`[mcp:${l}] transport error: ${v.message}`)},h.onToolListChanged=()=>{s.manager?.refreshServer(l).catch(v=>{let b=v instanceof Error?v.message:String(v);console.warn(`[mcp:${l}] refreshServer failed: ${b}`)})};let g=(async()=>{let v=Date.now();re(n.traceWriter,{phase:"mcp_server_start",metadata:{server:l}});let b="error",E=0;try{let{tools:w,serverInfo:k}=await h.connect();f.tools=w,f.state.status="connected",f.state.toolCount=w.length,f.state.lastListedAt=Date.now(),b="connected",E=w.length;let A=k?`${k.name}@${k.version}`:"unknown";console.log(`[mcp:${l}] connected (${A}) \u2014 ${w.length} tool(s)`)}catch(w){if(w instanceof Al){f.state.status="oauth_pending",b="oauth_pending",console.log(`[mcp:${l}] OAuth authorization required \u2014 check Telegram or stderr for the auth URL`);return}let k=w instanceof Error?w.message:String(w);if(f.state.status="error",f.state.error=ci(k,200),d.alwaysLoad===!0)throw new Error(`MCP server "${l}" is marked alwaysLoad but failed to connect: ${k}`);console.warn(`[mcp:${l}] connect failed: ${k}`)}finally{re(n.traceWriter,{phase:"mcp_server_done",durationMs:Date.now()-v,metadata:{server:l,status:b,toolCount:E}})}})();o.push(g)}let a=(await Promise.allSettled(o)).find(l=>l.status==="rejected");if(a){for(let l of r.values())l.client&&await l.client.disconnect().catch(()=>{});throw a.reason}let c=new t(r);return s.manager=c,c}getMcpTools(){let e=[];for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);if(!s||s.state.status!=="connected")continue;let i=s.tools.find(a=>a.name===o);i&&e.push(yO(n,i))}return e}getMcpHandlers(){let e=new Map;for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);!s||s.state.status!=="connected"||e.set(n,async(i,a)=>s.client?s.client.callTool(o,i,a):{content:`MCP server "${r}" is not connected`,isError:!0})}return e}async refreshServer(e){let n=this.records.get(e);if(!n||!n.client||n.state.status!=="connected")throw new Error(`McpManager.refreshServer("${e}"): server is not connected`);let r=await n.client.refreshTools();for(let[s,i]of this.nameRegistry)i.serverName===e&&this.nameRegistry.delete(s);let o=Tr([{serverName:e,toolNames:r.map(s=>s.name)}]);if(o.conflicts.length>0)for(let s of o.conflicts){let i=s.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");console.warn(`[mcp:${e}] wire-name conflict after refresh \u2014 skipping: ${s.wireName} \u2190 ${i}`)}for(let[s,i]of o.tools)this.nameRegistry.set(s,i);n.tools=r,n.state.toolCount=r.length,n.state.lastListedAt=Date.now(),console.log(`[mcp:${e}] tool list refreshed \u2014 ${r.length} tool(s)`),this.onToolsRefreshed?.(e)}getServerStates(){return[...this.records.values()].map(e=>({...e.state}))}getMcpToolWireNames(){return[...this.nameRegistry.keys()]}async completeAuth(e,n){let r=this.records.get(e);if(!r)throw new Error(`McpManager.completeAuth("${e}"): server not found`);if(r.state.status!=="oauth_pending")throw new Error(`McpManager.completeAuth("${e}"): server is not in oauth_pending state (current status: ${r.state.status})`);if(!r.client)throw new Error(`McpManager.completeAuth("${e}"): no client record \u2014 server was never connected`);await r.client.finishAuth(n),await r.client.disconnect().catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${e}] completeAuth disconnect warning: ${a}`)});let o=new Rn(e,r.state.config);o.onTransportError=i=>{r.state.status="error",r.state.error=ci(i.message,200),console.warn(`[mcp:${e}] transport error: ${i.message}`)},o.onToolListChanged=()=>{this.refreshServer(e).catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${e}] refreshServer failed: ${a}`)})},r.state.status="connecting",r.state.error=void 0,r.client=o;try{let{tools:i,serverInfo:a}=await o.connect();r.tools=i,r.state.status="connected",r.state.toolCount=i.length,r.state.lastListedAt=Date.now();let c=a?`${a.name}@${a.version}`:"unknown";console.log(`[mcp:${e}] OAuth complete \u2014 connected (${c}) \u2014 ${i.length} tool(s)`)}catch(i){let a=i instanceof Error?i.message:String(i);throw r.state.status="error",r.state.error=ci(a,200),new Error(`McpManager.completeAuth("${e}"): reconnect failed: ${a}`)}for(let[i,a]of this.nameRegistry)a.serverName===e&&this.nameRegistry.delete(i);let s=Tr([{serverName:e,toolNames:r.tools.map(i=>i.name)}]);for(let[i,a]of s.tools)this.nameRegistry.set(i,a);this.onToolsRefreshed?.(e)}hasAnyConnected(){for(let e of this.records.values())if(e.state.status==="connected")return!0;return!1}size(){return this.records.size}async disconnectAll(){let e=[];for(let[n,r]of this.records)r.client&&e.push(r.client.disconnect().catch(o=>{let s=o instanceof Error?o.message:String(o);console.warn(`[mcp:${n}] disconnect error: ${s}`)}));await Promise.all(e)}};function yO(t,e){let n=e.description??`MCP tool ${e.name}`;return{name:t,description:n,input_schema:e.inputSchema}}function ci(t,e){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}U();K();import{existsSync as Pr,lstatSync as bO,readFileSync as wO,readdirSync as vO}from"node:fs";import{join as Rr}from"node:path";function li(){return Rr(We(),"mcp.json")}function Dw(t=process.cwd()){return Rr(t,".mcp.json")}var SO=5;function xl(t=st()){if(!Pr(t))return[];let e=[];return Fw(t,t,0,e,new Set),e}function Fw(t,e,n,r,o){if(n>SO||o.has(e))return;o.add(e);let s=Rr(e,".claude-plugin","plugin.json");if(Pr(s)){let a=Rr(e,".claude-plugin","mcp.json");Pr(a)&&r.push(a);return}let i;try{i=vO(e)}catch{return}for(let a of i){if(a.startsWith("."))continue;let c=Rr(e,a),l;try{l=bO(c)}catch{continue}l.isDirectory()&&Fw(t,c,n+1,r,o)}}function kO(t,e){if(e===null||typeof e!="object"||Array.isArray(e))return{ok:!1,error:`server "${t}" must be an object`};let n=e,r=n.type;if(r===void 0)if(typeof n.command=="string")r="stdio";else if(typeof n.url=="string")r="streamable-http";else return{ok:!1,error:`server "${t}" has no \`command\` or \`url\`; cannot infer transport`};if(r==="stdio"){if(typeof n.command!="string"||n.command.length===0)return{ok:!1,error:`stdio server "${t}" requires non-empty \`command\``}}else if(r==="streamable-http"||r==="sse"){if(typeof n.url!="string"||n.url.length===0)return{ok:!1,error:`${r} server "${t}" requires non-empty \`url\``}}else return{ok:!1,error:`server "${t}" has unsupported \`type\`: ${String(r)}`};let o={type:r};if(typeof n.command=="string"&&(o.command=n.command),Array.isArray(n.args)&&(o.args=n.args.filter(s=>typeof s=="string")),n.env!==void 0&&typeof n.env=="object"&&n.env!==null){let s={};for(let[i,a]of Object.entries(n.env))typeof a=="string"&&(s[i]=a);o.env=s}if(typeof n.url=="string"&&(o.url=n.url),n.headers!==void 0&&typeof n.headers=="object"&&n.headers!==null){let s={};for(let[i,a]of Object.entries(n.headers))typeof a=="string"&&(s[i]=a);o.headers=s}return typeof n.oauth=="boolean"&&(o.oauth=n.oauth),typeof n.disabled=="boolean"&&(o.disabled=n.disabled),typeof n.alwaysLoad=="boolean"&&(o.alwaysLoad=n.alwaysLoad),typeof n.timeout=="number"&&n.timeout>0&&(o.timeout=n.timeout),{ok:!0,config:o}}function Pn(t){if(!Pr(t))return{mcpServers:{},sources:[],warnings:[]};let e=[],n;try{n=JSON.parse(wO(t,"utf-8"))}catch(i){let a=i instanceof Error?i.message:String(i);return e.push(`mcp.json at ${t}: parse error \u2014 ${a}`),{mcpServers:{},sources:[t],warnings:e}}if(n===null||typeof n!="object"||Array.isArray(n))return e.push(`mcp.json at ${t}: top-level must be an object`),{mcpServers:{},sources:[t],warnings:e};let o=n.mcpServers;if(o==null||typeof o!="object")return{mcpServers:{},sources:[t],warnings:e};let s={};for(let[i,a]of Object.entries(o)){let c=kO(i,a);c.ok?s[i]=c.config:e.push(`mcp.json at ${t}: skipping ${c.error}`)}return{mcpServers:s,sources:[t],warnings:e}}function Rl(t={}){let e=[],n=[];if(t.importedMcpConfigs&&t.importedMcpConfigs.length>0)for(let a of t.importedMcpConfigs)e.push({path:a,loaded:Pn(a)});if(t.pluginsRoot!==null){let a=t.pluginsRoot,c=a?xl(a):xl();for(let l of c)e.push({path:l,loaded:Pn(l)})}if(!t.skipUserGlobal){let a=li();e.push({path:a,loaded:Pn(a)})}if(!t.skipProjectLocal&&S.AFK_ALLOW_PROJECT_MCP!=="0"){let a=Dw(t.cwd);Pr(a)&&(e.push({path:a,loaded:Pn(a)}),n.push(`mcp: loaded project-local config from ${a} \u2014 set AFK_ALLOW_PROJECT_MCP=0 to disable auto-load`))}t.cliOverride!==void 0&&e.push({path:t.cliOverride,loaded:Pn(t.cliOverride)});let r=new Map,o=[...n],s=[];for(let a of e){for(let c of a.loaded.warnings)o.push(c);if(a.loaded.sources.length>0)for(let c of a.loaded.sources)s.includes(c)||s.push(c);for(let[c,l]of Object.entries(a.loaded.mcpServers)){let d=r.get(c);d&&o.push(`mcp: server "${c}" defined in ${d.source} is overridden by ${a.path}`),r.set(c,{config:l,source:a.path})}}let i={};for(let[a,c]of r)i[a]=c.config;return{mcpServers:i,sources:s,warnings:o}}Ho();ee();async function Lw(t,e={}){let n=Vn(qn()).mcpConfigs.filter(a=>a.format==="json").map(a=>a.source),r=Rl({cwd:t??process.cwd(),...n.length>0?{importedMcpConfigs:n}:{}}),o=Object.values(r.mcpServers).filter(a=>!a.disabled).length;if(o===0){for(let a of r.warnings)console.warn(`[mcp] ${a}`);return}let s=r.sources.length===1?r.sources[0]:`${r.sources.length} source(s)`;console.log(` mcp: ${o} server(s) from ${s??li()}`);let i=Date.now();re(e.traceWriter,{phase:"mcp_connect_start",metadata:{serverCount:o}});try{return await xr.fromConfig(r.mcpServers,{warnings:r.warnings,...e.traceWriter!==void 0?{traceWriter:e.traceWriter}:{}})}finally{re(e.traceWriter,{phase:"mcp_connect_done",durationMs:Date.now()-i,metadata:{serverCount:o}})}}function Pl(t,e){if(e===void 0)return t;let n=t.close.bind(t),r=!1;return t.close=(async()=>{try{await n()}finally{r||(r=!0,await e.disconnectAll())}}),t}var Bw="unknown";try{let t=Uw($w(Nw(import.meta.url)),"..","package.json"),e=JSON.parse(Il(t,"utf8"));e.version&&(Bw=e.version)}catch{console.warn("\u26A0\uFE0F [daemon] Could not read package.json at startup \u2014 version drift check disabled.")}async function EO(){let t;try{t=Ea()}catch(d){console.error("\u274C Configuration error:",d.message),process.exit(1)}let e=gh(),n=z(t.model);if(n==="openai-compatible"||n==="openai-codex"){let d=S.OPENAI_API_KEY||S.CODEX_API_KEY;console.log(d?"\u{1F4DD} Using OPENAI_API_KEY / CODEX_API_KEY for OpenAI auth":"\u{1F4DD} Will attempt API key from ~/.codex/auth.json (run `afk provider auth diagnose` for details)")}else{let d=_a();(!d||d.length===0)&&(console.error("\u274C Claude models require ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN."),console.error(" Set one in your environment, run `afk login`, or sign in to Claude Code."),process.exit(1)),Jt(d)==="oauth"?(process.env.CLAUDE_CODE_OAUTH_TOKEN=d,console.log("\u{1F4DD} Using CLAUDE_CODE_OAUTH_TOKEN for Anthropic auth (OAuth, auto-refresh on 401)")):(process.env.ANTHROPIC_API_KEY=d,console.log("\u{1F4DD} Using ANTHROPIC_API_KEY for Anthropic auth")),t.apiKey=d}xO(kt());let r=S.TELEGRAM_BOT_TOKEN;r||(console.error("\u274C Error: TELEGRAM_BOT_TOKEN environment variable is required"),console.error(`
1702
1702
  How to get a bot token:`),console.error(" 1. Open Telegram and search for @BotFather"),console.error(" 2. Send /newbot and follow the instructions"),console.error(" 3. Run: afk telegram setup"),process.exit(1));let o=$o(S.AFK_TELEGRAM_ALLOWED_CHAT_IDS,console.warn);o.size===0&&(console.error("\u274C Error: AFK_TELEGRAM_ALLOWED_CHAT_IDS must list at least one chat ID"),console.error(`
1703
- This is an allowlist that gates who can message the bot.`),console.error("Run `afk telegram setup` to set it interactively, or set it manually:"),console.error(" AFK_TELEGRAM_ALLOWED_CHAT_IDS=123456789,-100987654321"),process.exit(1)),console.log("\u{1F50E} Validating bot token...");let s=await xb(r);s||(console.error("\u274C Error: TELEGRAM_BOT_TOKEN was rejected by Telegram (getMe failed)"),console.error(" The token may be revoked, malformed, or your network may be unreachable."),console.error(" Re-run `afk telegram setup` to refresh it."),process.exit(1));let i=s.username?`@${s.username}`:s.firstName;console.log(""),console.log(`\u{1F916} Starting Agent AFK Telegram Bot as ${i} (id ${s.id})`),console.log(`\u{1F4E1} Model: ${t.model} \xB7 Provider: ${n}`),console.log(`\u{1F512} Allowlist: ${o.size} chat ID(s)`);let a=new fe,c=S.AFK_TELEGRAM_CWD,l=new ei({botToken:r,apiKey:t.apiKey??"",dataDir:S.TELEGRAM_DATA_DIR||"./data/telegram-sessions",defaultModel:t.model,verbose:S.TELEGRAM_VERBOSE==="true",allowedChatIds:o,settingSources:["user","project"],...c!==void 0&&c.length>0?{botCwd:c}:{},createSession:async d=>{let u=se(d.model)??d.model;console.log(`Creating session with model: ${d.model} -> ${u}`);let p=z(u),f=p==="openai-compatible"||p==="openai-codex",h=f?void 0:yh(),g=d.systemPrompt??t.systemPrompt,v=hh(e,typeof g=="string"?g:void 0),b=d.cwd??c,E=Kb(),w=await Lw(b,{...E!==null?{traceWriter:E}:{}}),k;try{let A;if(!f){let O,L=d.apiKey??t.apiKey??"",M=t.baseUrl,C=new G({apiKey:L,...M!==void 0?{baseUrl:M}:{},...b!==void 0&&b.length>0?{cwd:b}:{}}),R={get sessionId(){return O?.sessionId},getInputStreamRef(){return O?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return O?.abortSignal??new AbortController().signal},get hookRegistry(){return O?.hookRegistry}},N=Ig(),H=Cg(d.model,L,N,M,void 0,void 0,b!==void 0&&b.length>0?b:void 0,_n,"telegram"),j=new wn({subagentManager:C,parentSession:R,surface:"telegram",defaultConfig:{apiKey:L,systemPrompt:v,...M!==void 0?{baseUrl:M}:{}},defaultSubagentModel:Cs(d.model),childProviderFactory:N,childSkillExecutorFactory:H,resolveApiKeyForModel:_n,depth:0}),Y=new kn({parentSession:R,surface:"telegram",defaultModel:d.model,defaultSubagentModel:Cs(d.model),apiKey:L,childProviderFactory:N,childSkillExecutorFactory:H,resolveApiKeyForModel:_n,...M!==void 0?{baseUrl:M}:{}}),Ee=new oi({parentSession:R,defaultModel:d.model,defaultSubagentModel:Cs(d.model),apiKey:L,resolveApiKeyForModel:_n,...M!==void 0?{baseUrl:M}:{},...b!==void 0&&b.length>0?{cwd:b}:{},systemPrompt:v??"",surface:"telegram",depth:0}),Ht=[...Ft,...Jr,...xe,"agent","skill","compose",...w?.getMcpToolWireNames()??[]];A=new pe({permissions:{allowedTools:Ht},subagentExecutor:j,skillExecutor:Y,composeExecutor:Ee,...w!==void 0?{mcpManager:w}:{},surface:"telegram"});let q=v,jt=t.autoRouting?.telegram??!1,Kt=typeof q=="string"?wl(q,jt,"telegram",bl()):q,Cl=yl(void 0,"telegram",a,void 0,hl(b!==void 0&&b.length>0?{cwd:b}:{}),{cwd:b!==void 0&&b.length>0?b:void 0},()=>b),di=Pl(fl({...d.apiKey!==void 0?{apiKey:d.apiKey}:{},model:d.model,...Kt!==void 0?{systemPrompt:Kt}:{},maxTurns:100,...h!==void 0?{maxOutputTokens:h}:{},...M!==void 0?{baseUrl:M}:{},...b!==void 0&&b.length>0?{cwd:b}:{},provider:A,hookRegistry:Cl.registry},{traceWriter:E}),w);return k=di,Cl.pathApprovalGrantRef.current=A,ll(A),O=di,di}let _=v,T=t.autoRouting?.telegram??!1,P=typeof _=="string"?wl(_,T,"telegram",bl()):_,I=b,D=new ue({surface:"telegram",...w!==void 0?{mcpManager:w}:{}}),x=yl(void 0,"telegram",a,void 0,hl(I!==void 0&&I.length>0?{cwd:I}:{}),{cwd:I!==void 0&&I.length>0?I:void 0},()=>I),F=Pl(fl({...d.apiKey!==void 0?{apiKey:d.apiKey}:{},model:d.model,...P!==void 0?{systemPrompt:P}:{},maxTurns:100,...h!==void 0?{maxOutputTokens:h}:{},...I!==void 0&&I.length>0?{cwd:I}:{},provider:D,hookRegistry:x.registry},{traceWriter:E}),w);return k=F,x.pathApprovalGrantRef.current=D,ll(D),F}catch(A){throw k!==void 0?await k.close().catch(()=>{}):w!==void 0&&await w.disconnectAll(),A}}});try{l.start(),console.log("\u2705 Bot started successfully!"),console.log(`
1703
+ This is an allowlist that gates who can message the bot.`),console.error("Run `afk telegram setup` to set it interactively, or set it manually:"),console.error(" AFK_TELEGRAM_ALLOWED_CHAT_IDS=123456789,-100987654321"),process.exit(1)),console.log("\u{1F50E} Validating bot token...");let s=await xb(r);s||(console.error("\u274C Error: TELEGRAM_BOT_TOKEN was rejected by Telegram (getMe failed)"),console.error(" The token may be revoked, malformed, or your network may be unreachable."),console.error(" Re-run `afk telegram setup` to refresh it."),process.exit(1));let i=s.username?`@${s.username}`:s.firstName;console.log(""),console.log(`\u{1F916} Starting Agent AFK Telegram Bot as ${i} (id ${s.id})`),console.log(`\u{1F4E1} Model: ${t.model} \xB7 Provider: ${n}`),console.log(`\u{1F512} Allowlist: ${o.size} chat ID(s)`);let a=new fe,c=S.AFK_TELEGRAM_CWD,l=new ei({botToken:r,apiKey:t.apiKey??"",dataDir:S.TELEGRAM_DATA_DIR||"./data/telegram-sessions",defaultModel:t.model,verbose:S.TELEGRAM_VERBOSE==="true",allowedChatIds:o,settingSources:["user","project"],...c!==void 0&&c.length>0?{botCwd:c}:{},createSession:async d=>{let u=oe(d.model)??d.model;console.log(`Creating session with model: ${d.model} -> ${u}`);let p=z(u),f=p==="openai-compatible"||p==="openai-codex",h=f?void 0:yh(),g=d.systemPrompt??t.systemPrompt,v=hh(e,typeof g=="string"?g:void 0),b=d.cwd??c,E=Kb(),w=await Lw(b,{...E!==null?{traceWriter:E}:{}}),k;try{let A;if(!f){let O,L=d.apiKey??t.apiKey??"",M=t.baseUrl,C=new G({apiKey:L,...M!==void 0?{baseUrl:M}:{},...b!==void 0&&b.length>0?{cwd:b}:{}}),R={get sessionId(){return O?.sessionId},getInputStreamRef(){return O?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return O?.abortSignal??new AbortController().signal},get hookRegistry(){return O?.hookRegistry}},N=Ig(),H=Cg(d.model,L,N,M,void 0,void 0,b!==void 0&&b.length>0?b:void 0,_n,"telegram"),j=new wn({subagentManager:C,parentSession:R,surface:"telegram",defaultConfig:{apiKey:L,systemPrompt:v,...M!==void 0?{baseUrl:M}:{}},defaultSubagentModel:Cs(d.model),childProviderFactory:N,childSkillExecutorFactory:H,resolveApiKeyForModel:_n,depth:0}),Y=new kn({parentSession:R,surface:"telegram",defaultModel:d.model,defaultSubagentModel:Cs(d.model),apiKey:L,childProviderFactory:N,childSkillExecutorFactory:H,resolveApiKeyForModel:_n,...M!==void 0?{baseUrl:M}:{}}),Ee=new oi({parentSession:R,defaultModel:d.model,defaultSubagentModel:Cs(d.model),apiKey:L,resolveApiKeyForModel:_n,...M!==void 0?{baseUrl:M}:{},...b!==void 0&&b.length>0?{cwd:b}:{},systemPrompt:v??"",surface:"telegram",depth:0}),Ht=[...Ft,...Jr,...xe,"agent","skill","compose",...w?.getMcpToolWireNames()??[]];A=new pe({permissions:{allowedTools:Ht},subagentExecutor:j,skillExecutor:Y,composeExecutor:Ee,...w!==void 0?{mcpManager:w}:{},surface:"telegram"});let q=v,jt=t.autoRouting?.telegram??!1,Kt=typeof q=="string"?wl(q,jt,"telegram",bl()):q,Cl=yl(void 0,"telegram",a,void 0,hl(b!==void 0&&b.length>0?{cwd:b}:{}),{cwd:b!==void 0&&b.length>0?b:void 0},()=>b),di=Pl(fl({...d.apiKey!==void 0?{apiKey:d.apiKey}:{},model:d.model,...Kt!==void 0?{systemPrompt:Kt}:{},maxTurns:100,...h!==void 0?{maxOutputTokens:h}:{},...M!==void 0?{baseUrl:M}:{},...b!==void 0&&b.length>0?{cwd:b}:{},provider:A,hookRegistry:Cl.registry},{traceWriter:E}),w);return k=di,Cl.pathApprovalGrantRef.current=A,ll(A),O=di,di}let _=v,T=t.autoRouting?.telegram??!1,P=typeof _=="string"?wl(_,T,"telegram",bl()):_,I=b,D=new ue({surface:"telegram",...w!==void 0?{mcpManager:w}:{}}),x=yl(void 0,"telegram",a,void 0,hl(I!==void 0&&I.length>0?{cwd:I}:{}),{cwd:I!==void 0&&I.length>0?I:void 0},()=>I),F=Pl(fl({...d.apiKey!==void 0?{apiKey:d.apiKey}:{},model:d.model,...P!==void 0?{systemPrompt:P}:{},maxTurns:100,...h!==void 0?{maxOutputTokens:h}:{},...I!==void 0&&I.length>0?{cwd:I}:{},provider:D,hookRegistry:x.registry},{traceWriter:E}),w);return k=F,x.pathApprovalGrantRef.current=D,ll(D),F}catch(A){throw k!==void 0?await k.close().catch(()=>{}):w!==void 0&&await w.disconnectAll(),A}}});try{l.start(),console.log("\u2705 Bot started successfully!"),console.log(`
1704
1704
  \u{1F4DD} Slash commands (Agent SDK):`),console.log(" /start - Welcome and command list"),console.log(" /help - Show command list"),console.log(" /clear - Clear conversation history"),console.log(" /compact - Compact history (summarize older messages)"),console.log(" /model - Switch model (opus/sonnet/haiku/gpt-5.4/...)"),console.log(`
1705
1705
  \u{1F4AC} Send any message to chat with the agent.`),console.log(`
1706
1706
  \u23F9\uFE0F Press Ctrl+C to stop the bot.`);let d=0,u=setInterval(()=>{let f=l.getStats();console.log(`