agent-afk 5.75.0 → 5.75.2

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.
@@ -24,18 +24,19 @@ When a proposal — a plan, fix, decomposition, scoping, or named recommendation
24
24
  4. Flag `dissent = true` when ≥2 critics returned `strong` alternatives disagreeing with the recommendation — signals the synthesizer is overruling well-argued dissent, so confidence is low. Include a `dissent_note` summarizing the strongest counter-argument.
25
25
 
26
26
  **Wave 3.5 — Composition-boundary check (fires on convergence):**
27
- Critics that converge may all have evaluated the proposal in artifact-isolation — none read the boundaries where it composes with siblings. A convergent verdict reached in isolation can be confidently wrong (e.g., critics agree on a UI glyph asserting visual continuity, but none saw that parallel-branch flushes reorder it). When the synthesis recommendation is **convergent** — recommendation ≠ original with `dissent = false`, OR ≥2 critics returned the same alternative — dispatch ONE context-injection verifier (same research-agent base) BEFORE surfacing:
27
+ Critics that converge may all have evaluated the proposal in artifact-isolation — none read the boundaries where it composes with siblings. A convergent verdict reached in isolation can be confidently wrong (e.g., critics agree on a UI glyph asserting visual continuity, but none saw that parallel-branch flushes reorder it). When the synthesis recommendation is **convergent** — recommendation ≠ original with ≥2 critics having returned the same alternative — dispatch ONE context-injection verifier (**`subagent_type: "research-agent"`** — Read/Grep/Glob/WebFetch only, no Edit/commit) BEFORE surfacing:
28
28
  1. Its job is NOT to re-evaluate the proposal in isolation. It reads the 3 nearest composition boundaries — upstream caller, downstream consumer, and the render/event/state pipeline that interleaves the proposal's target with siblings.
29
29
  2. For each boundary: does the recommendation survive when the boundary varies? Check **temporal interleaving** (can flushes / parallel branches / sibling completions reorder it?), **state threading** (does it assume a point-of-use state upstream can break?), **adjacency assumptions** (does it presume render-tree / scrollback / call-graph adjacency that isn't load-bearing under recomposition?).
30
- 3. Returns `CONFIRMED` only if the recommendation survives all three; otherwise `OVERRIDE: <specific boundary condition that breaks it>`.
30
+ 3. Returns `CONFIRMED` only if the recommendation survives all three; otherwise `OVERRIDE: <specific boundary condition that breaks it>`. (These verdicts are internal to Wave 3.5 — distinct from shadow-verify's verifier verdict vocabulary.)
31
31
 
32
- Until the verifier returns `CONFIRMED`, the convergent recommendation is a **candidate**, not a recommendation. On `OVERRIDE`, fold the named condition into the matrix and re-rank.
32
+ Until the verifier returns `CONFIRMED`, the convergent recommendation is a **candidate**, not a recommendation. On `OVERRIDE`, fold the named condition into the matrix and re-rank. **Cap:** if `OVERRIDE` recurs after 2 re-ranks, escalate the full composition failure to the user rather than cycling further — the matrix cannot resolve a boundary violation on its own.
33
33
 
34
- **Scope guard:** skip when the proposal is purely local with no composition surface, or is anchored to an external referent that survives independently of the system. Fires once per convergent verdict, not per critic.
34
+ **Scope guard:** skip when the proposal is purely local with no composition surface, or is anchored to an external referent that survives independently of the system. Does not fire when `dissent = true` — that path surfaces the matrix directly; adding a Wave 3.5 gate on already-uncertain output adds friction without signal. Fires once per convergent verdict, not per critic.
35
35
 
36
36
  **Merge + surface:**
37
- - Recommendation = `original` → the proposal survived critique; proceed with it — **unless ≥2 critics converged on the same alternative** (the second convergence condition above), in which case run Wave 3.5 first and, on `OVERRIDE`, re-rank before acting.
38
- - Recommendation ≠ `original`, `dissent = false` synthesis found a better path; run Wave 3.5, then surface the alternative with rationale (on `OVERRIDE`, re-rank first) before acting.
37
+ - Recommendation = `original` → the proposal survived critique; proceed with it.
38
+ - Recommendation ≠ `original`, `dissent = false`, ≥2 critics returned the same alternative → convergent path: run Wave 3.5, then surface the alternative with rationale (on `OVERRIDE`, re-rank first) before acting.
39
+ - Recommendation ≠ `original`, `dissent = false`, only 1 critic backed the winner → no convergence to guard: surface the alternative with rationale directly (Wave 3.5 does not fire).
39
40
  - `dissent = true` → present the matrix to the user; do not act. Confidence is low.
40
41
 
41
42
  **When to invoke:**
@@ -6,6 +6,6 @@ context: fork
6
6
 
7
7
  Gather context: read the failing test or bug description, relevant error output, and recent git changes. If no failing test exists yet, write a minimal reproducer test (or identify a concrete verification command) before proceeding — hypotheses need a pass/fail signal to validate against. Dispatch two sub-agents in parallel — one to search the codebase for code paths involved in the failure (`subagent_type: research-agent`, read-only), and one to check recent commits and diffs that could have introduced the regression (`subagent_type: general-purpose` — requires Bash for `git log`/`git diff`/`git show`). When both return, synthesize findings into 2–4 ranked hypotheses, each with a specific code location and proposed cause.
8
8
 
9
- For each hypothesis, first create a dedicated git worktree with the `worktree` tool (`action: "create"`, one per hypothesis), then dispatch a sub-agent with its `cwd` set to that worktree's absolute path. This is how afk isolates a sub-agent to its own tree — the `agent` tool has NO `isolation` parameter, so parallel agents that omit `cwd` all inherit the same working tree and would contaminate each other's speculative fixes and test runs, invalidating the pass/fail attribution. Each sub-agent applies a minimal speculative fix, runs the test or verification command, then runs the broader related test suite to check for regressions. Run all hypothesis-testing agents in parallel, each in its own worktree; after collecting a result, remove that worktree with the `worktree` tool (`action: "remove"`). Collect results: which fixes passed, which didn't, and any regressions surfaced by the broader suite.
9
+ For each hypothesis, dispatch a sub-agent with `isolation: "worktree"` to apply a minimal speculative fix, run the test or verification command, and then run the broader related test suite to check for regressions. Run all hypothesis-testing agents in parallel. Collect results: which fixes passed, which didn't, and any regressions surfaced by the broader suite.
10
10
 
11
11
  Report the validated root cause (the hypothesis whose fix passed), the speculative fix diff, and regression status from the broader test run. If no hypothesis passes, synthesize what was learned and form a second round of hypotheses. If the user approves the fix, apply it to the main worktree.
@@ -18,15 +18,18 @@ When a sub-agent (or wave) returns investigation findings, code-review conclusio
18
18
  - `CONFIRMED` → surface the claim as validated.
19
19
  - `REFUTED` → replace the claim with the verifier's corrected finding, annotated `[was: confident, now: refuted]`, and show it alongside the original with evidence. Do not act until the conflict is resolved.
20
20
  - `UNVERIFIABLE` → surface with a `[needs-human-review]` tag rather than passing it through silently.
21
- - `UNVERIFIED-COMPOSITION` / `UNVERIFIED-ECHO-CHAMBER` (from the composition-axis guard below) → surface with a `[needs-human-review]` tag naming the missed boundary; do not pass through as validated.
21
+
22
+ *The two verdicts below are **not** emitted by individual verifiers — they are produced by the Composition-axis guard (defined below) and handled here:*
23
+ - `UNVERIFIED-COMPOSITION` → surface with `[needs-human-review: composition boundary unchecked]`; do not act until a boundary read confirms or refutes the claim.
24
+ - `UNVERIFIED-ECHO-CHAMBER` → surface with `[needs-human-review: echo-chamber suspected]`; require at least one verifier to re-derive from outside the cited artifact before acting.
22
25
 
23
26
  Bound the loop: at most 3 verification rounds per session. Claims still unresolved after 3 rounds are escalated to the user, never silently dropped.
24
27
 
25
28
  **Composition-axis guard (echo-chamber check):**
26
29
  A verifier that re-derives a claim by re-reading the *same* file/region the original sub-agent cited has confirmed the citation, not the claim — it can be blind to composition-boundary failures (temporal interleaving, state threading, render/event-pipeline ordering, scrollback/call-graph adjacency) that only manifest outside the artifact's boundary. Before accepting a `CONFIRMED`:
27
30
  1. Read each verifier's `evidence_base`.
28
- 2. For any **artifact-internal `CONFIRMED`**, require one composition-boundary read (≥1 upstream caller + ≥1 downstream consumer, plus the pipeline that interleaves the artifact with siblings) before merging. If a missed boundary surfaces, downgrade to `UNVERIFIED-COMPOSITION` and tag `[needs-human-review]`.
29
- 3. **Echo-chamber guard:** if ≥2 verifiers cite the *same* in-repo artifact as primary evidence with no external referent, flag `UNVERIFIED-ECHO-CHAMBER` regardless of verdict and require one verifier to read outside that artifact's boundary.
31
+ 2. For any **artifact-internal `CONFIRMED`**, require one composition-boundary read (≥1 upstream caller + ≥1 downstream consumer, plus the pipeline that interleaves the artifact with siblings) before merging. If a missed boundary surfaces, downgrade to `UNVERIFIED-COMPOSITION` and tag `[needs-human-review]`. (An artifact-internal `REFUTED` is intentionally exempt: a refutation already halts action under the Merge rule above, so its boundary-blindness cannot drive a wrong commit — the asymmetry is safe by construction.)
32
+ 3. **Echo-chamber guard:** if ≥2 verifiers cite the *same* in-repo artifact as primary evidence with no external referent, flag `UNVERIFIED-ECHO-CHAMBER` regardless of verdict and require one verifier to read outside that artifact's boundary. If the 3-round loop cap is already exhausted when this fires, escalate to the user as `UNVERIFIED-ECHO-CHAMBER [loop-cap-reached]` — do not dispatch a new round.
30
33
 
31
34
  **Scope guard:** skip the composition check when the claim cites an external referent (RFC, spec, threat model, upstream-API contract) that survives independently of the repo, or when the artifact is purely local with no composition surface. Runs once per artifact, not on every cite.
32
35
 
@@ -88,7 +88,6 @@ export declare class TerminalCompositor {
88
88
  setOnSubmit(handler: ((payload: SubmissionPayload) => void) | null): void;
89
89
  setOnCancel(handler: (() => void) | null): void;
90
90
  getOnCancel(): (() => void) | undefined;
91
- setOnBackground(handler: (() => void) | null): void;
92
91
  setOnRewindRequest(handler: (() => void) | null): void;
93
92
  setOnOpenEditor(handler: (() => void) | null): void;
94
93
  enterPickerMode(controller: PickerController): void;
package/dist/cli.mjs CHANGED
@@ -869,7 +869,7 @@ Remedy: these paths are outside the fork's granted read roots. Re-dispatch with
869
869
  Note: this search ran in basic-regex (BRE) mode, where '|' is a literal pipe \u2014 not alternation. If you intended "A or B", retry with extended: true (extended regex / ERE). If you meant the literal character '|', this empty result stands.`),d({content:D});return}if(k===2){let D=Hs(h.trim());d({content:`grep error: ${D.content}`,isError:!0,...D.truncated?{truncated:!0}:{}});return}let T=zn(g.trimEnd()),C=Hs(T);d({content:C.content,...C.truncated?{truncated:!0}:{}})}),f.on("error",k=>{let T;if(m===void 0&&Rc(k))try{T=Js(k,process.cwd())}catch{T=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${k.message}`}else T=Js(k,m);d({content:`Failed to execute grep: ${T}`,isError:!0})})})}}var r_,o_=x(()=>{"use strict";Gn();Jn();co();qw();Ws();r_=eS()});import{promises as IV}from"fs";function tS(e){return(t,n,r)=>PV(t,n,r,e)}var PV,i_,s_=x(()=>{"use strict";Jn();PV=async(e,t,n,r)=>{if(!e||typeof e!="object")throw new Error("Invalid input: expected an object");let i=e.path;if(typeof i!="string")throw new Error("Invalid input: path must be a string");let s;try{s=ln(i,n,"read",r)}catch(a){return{content:a instanceof Error?a.message:String(a),isError:!0}}try{let a=await IV.readdir(s,{withFileTypes:!0}),l=a.filter(m=>m.isDirectory()).map(m=>`${m.name}/`),c=a.filter(m=>!m.isDirectory()).map(m=>m.name);l.sort(),c.sort();let d=[...l,...c];return d.length===0?{content:"(empty directory)"}:{content:d.join(`
870
870
  `)}}catch(a){if(a instanceof Error){let l=a;return l.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:l.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:l.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${a.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}};i_=tS()});function MV(e=Ls){return async(t,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let r=t,o=r.message,i=r.chat;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(i!==void 0&&typeof i!="number"&&typeof i!="string")return{content:"Invalid input: chat must be a number (chat id) or string (chat id or alias name)",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>a_)return{content:`Invalid input: message exceeds Telegram's ${a_}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=v.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 a;if(i!==void 0){let c=Sp(i,vp());if(!c.ok)return{content:c.message,isError:!0};let d=Ps(v.AFK_TELEGRAM_ALLOWED_CHAT_IDS);if(!dp(c.id,d)){let u=[...d];return{content:`Refusing to send: chat ${c.id} is not in the allowlist (AFK_TELEGRAM_ALLOWED_CHAT_IDS). `+(u.length>0?`Allowed chat id(s): ${u.join(", ")}. `:"The allowlist is empty or unset. ")+"Add the chat id to the allowlist before targeting it.",isError:!0}}a=[c.id]}else a=Fs();if(a.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 l=[];for(let c of a){let d=await e({token:s,chatId:c,text:o});d.ok||l.push(`chat ${c}: ${d.errorMessage??`HTTP ${d.status}`}`)}return l.length===a.length?{content:`Failed to send Telegram message to any chat. ${l.join("; ")}`,isError:!0}:l.length>0?{content:`Sent Telegram message to ${a.length-l.length}/${a.length} chat(s); ${l.length} failed: ${l.join("; ")}`}:{content:a.length===1?`Sent Telegram message to chat ${a[0]}.`:`Sent Telegram message to ${a.length} chats.`}}}var a_,l_,c_=x(()=>{"use strict";K();vr();fc();up();a_=4096;l_=MV()});async function OV(){let[{JSDOM:e},{Readability:t},{default:n}]=await Promise.all([import("jsdom"),import("@mozilla/readability"),import("turndown")]),r=new n({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});return r.remove(["script","style","noscript","iframe"]),{JSDOM:e,Readability:t,turndown:r}}function $V(){return nS===null&&(nS=OV()),nS}function d_(e){return e.replace(/\n{3,}/g,`
871
871
 
872
- `).trim()}function DV(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}async function u_(e,t){let{JSDOM:n,Readability:r,turndown:o}=await $V(),s=new n(e,{url:t}).window.document,a=(s.title??"").trim(),l=(()=>{try{let m=s.cloneNode(!0);return new r(m).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let m=d_(o.turndown(l.content)),f=(l.title??"").trim()||a,g=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:m,textLength:g,usedFallback:!1}}let c=s.body,d=c?.innerHTML??"",u=d_(o.turndown(d));return{title:a,markdown:u,textLength:DV(c),usedFallback:!0}}var nS,p_=x(()=>{"use strict";nS=null});function LV(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(i),r(t?.reason??new Error("aborted"))},i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function m_(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function NV(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function tm(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??LV,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await e(t,n);if(!FV.has(u.status)||d===o)return u;let m=NV(u,s)??m_(d,i,s);W("[web/retryFetch] retrying",{url:t,attempt:d,status:u.status,waitMs:m}),await u.body?.cancel().catch(()=>{}),await a(m,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let m=m_(d,i,s);W("[web/retryFetch] retrying after error",{url:t,attempt:d,waitMs:m}),await a(m,l)}}throw c??new Error("retryFetch: exhausted without a result")}var FV,rS=x(()=>{"use strict";ye();FV=new Set([429,502,503,504])});import{readFileSync as BV}from"node:fs";import{join as UV}from"path";function jV(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function f_(e,t){return jV(t).test(e)}function KV(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(HV.has(t))return!0;if(WV.has(t))return!1}return!1}function g_(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function GV(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function h_(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Vl(t),t}function qV(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function zV(e){try{return BV(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function JV(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=h_(t.defaultProfile)),n}function y_(e){let t=e?.env??v,n=e?.readFileSync??zV,r=e?.surface??t.AGENT_SURFACE,o=KV(t.AFK_BROWSER_HEADLESS,r),i=g_(t.AFK_BROWSER_ALLOWED_DOMAINS),s=g_(t.AFK_BROWSER_BLOCKED_DOMAINS),a=qV(t.AFK_BROWSER_DOM_SNAPSHOTS),l=GV(t.AFK_BROWSER_BACKEND),c=h_(t.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:i,blockedDomains:s,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=t.AFK_BROWSER_CONFIG,m=u!==void 0&&u.trim()!==""?u.trim():UV(bn(),"browser.json"),f=n(m);if(f===void 0)return d;let g;try{g=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${m}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${m} must be a JSON object`);let h=JV(d,g);return h.configPath=m,h}function oS(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(f_(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>f_(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var HV,WV,iS=x(()=>{"use strict";K();q();HV=new Set(["daemon","subagent","telegram","afk"]),WV=new Set(["repl","interactive","cli"])});import mi from"node:fs";import nm from"node:path";import{randomBytes as YV}from"node:crypto";import{chromium as VV}from"playwright";function XV(){try{return"5.75.0"}catch{}try{let e=nm.resolve(import.meta.dirname,"../../../package.json"),t=mi.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var QV,rm,b_=x(()=>{"use strict";q();ye();QV=XV(),rm=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}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=VV.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i=()=>{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",i,{once:!0});try{let s=await o.newPage(),a=await s.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await s.content(),c=s.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);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(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.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/${QV}`}}loadStorageState(t){let n=Xl(t);try{if(!mi.existsSync(n))return;let r=JSON.parse(mi.readFileSync(n,"utf8"));return W("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){W("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Xl(t);if(!mi.existsSync(r))return;let o=await n.storageState(),i=nm.join(nm.dirname(r),`.${nm.basename(r)}.${process.pid}.${YV(4).toString("hex")}.tmp`);mi.writeFileSync(i,JSON.stringify(o),{mode:384}),mi.chmodSync(i,384),mi.renameSync(i,r),W("[browser/vault] saved session",{profile:t,file:r})}catch(r){W("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as ZV}from"crypto";function sS(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of e4)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function w_(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&t4.test(e.label))}function S_(e){return ZV("sha256").update(e,"utf8").digest("hex").slice(0,8)}function v_(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var e4,t4,_c=x(()=>{"use strict";e4=[{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}];t4=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as n4}from"node:crypto";function r4(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function o4(e,t,n){return`el_${n4("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function i4(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function k_(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function E_(e,t){let n=e.role??"",r=e.name??"";T_.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])E_(i,t)}async function s4(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let d=window.getComputedStyle(s);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},x_).catch(()=>[])}async function a4(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in i?i.value:void 0,u=d!==void 0?String(d):void 0,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},x_).catch(()=>[])}function l4(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function om(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=l4(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=s4(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,m,f,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],E_(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await a4(e)).filter(U=>T_.has(U.role??"")));let w=new Map;for(let O of m){let U=k_(O.name),j=w.get(U);(!j||j.bbox.w===0&&O.bbox.w>0)&&w.set(U,O)}let S=y.map(O=>({ax:O,dom:w.get(k_(O.name??""))})),k=r?S:S.filter(O=>O.dom?O.dom.bbox.w>0||O.dom.bbox.h>0:!0);k.sort((O,U)=>{let j=O.dom?.bbox.y??0,$=U.dom?.bbox.y??0;if(j!==$)return j-$;let B=O.dom?.bbox.x??0,P=U.dom?.bbox.x??0;return B-P}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let C=k.slice(0,n).map((O,U)=>{let j=O.ax.role??"generic",$=O.ax.name??"",B=o4(j,$,U),P=O.dom?.bbox??{x:0,y:0,w:0,h:0},N=O.dom?.type??null,_=null;O.ax.value!==void 0&&O.ax.value!==null&&(_=String(O.ax.value)),O.ax.checked!==void 0&&(_=String(O.ax.checked)),w_({role:j,kind:N})&&(_="[redacted]");let M={disabled:O.ax.disabled??!1};O.ax.checked!==void 0&&(M.checked=O.ax.checked===!0||O.ax.checked==="mixed"),O.ax.selected!==void 0&&(M.selected=O.ax.selected),O.ax.expanded!==void 0&&(M.expanded=O.ax.expanded);let I;O.dom?.testId?I=`[data-testid="${O.dom.testId}"]`:O.dom?.id&&(I=`#${O.dom.id}`);let H={id:B,role:j,label:r4($),kind:N,value:_,state:M,bbox:P};return I!==void 0&&(H.selector=I),H}),D="idle";try{let O=await e.evaluate(()=>document.readyState);O==="loading"?D="loading":O==="interactive"?D="navigating":D="idle"}catch{D="navigating"}D!=="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 R=i4(f),F=`obs_${t.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:F,url:g,title:h,textSummary:R,interactive:C,status:{httpStatus:t.httpStatus??null,loadingState:D,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:A}}var T_,x_,R_=x(()=>{"use strict";_c();T_=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);x_="a[href], button, input, select, textarea, [role], [tabindex], label"});async function C_(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>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 aS(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>C_(e,i)))).filter(o=>o!==null)}async function c4(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function lS(e,t,n){switch(t.kind){case"element_id":return d4(e,t,n);case"selector":return u4(e,t);case"semantic":return p4(e,t)}}async function d4(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await aS(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function u4(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await aS(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function p4(e,t){return t.role!==void 0?m4(e,t.text,t.role):f4(e,t.text,t)}async function m4(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await aS(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function f4(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let d=[];s>0&&d.push({loc:r,count:s}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:i,count:l});let u=await c4(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=u.slice(0,5),f=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await C_(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let k=0;k<w.length;k++)S=S*31+w.charCodeAt(k)>>>0;f.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var A_=x(()=>{"use strict"});import{randomBytes as g4}from"crypto";import{mkdir as h4,stat as y4,writeFile as b4}from"fs/promises";import{join as cS}from"path";import{gzip as w4}from"zlib";import{promisify as S4}from"util";function v4(e){return cS(Vo(e),"browser")}function k4(e){return cS(v4(e),"screenshots")}function T4(){return new Date().toISOString().replace(/[:.]/g,"-")}function E4(){return g4(3).toString("hex")}async function dS(e,t,n){if(t.length>__)throw new Error(`writeScreenshotSidecar: buffer exceeds ${__} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=k4(e);await h4(r,{recursive:!0});let o=`${T4()}-${E4()}-${n}.png`,i=cS(r,o);await b4(i,t);let{size:s}=await y4(i);return{path:i,bytes:s}}var QEe,__,I_=x(()=>{"use strict";q();_c();QEe=S4(w4);__=5*1024*1024});var M_={};Au(M_,{PlaywrightProvider:()=>uS});function P_(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var uS,O_=x(()=>{"use strict";b_();R_();A_();iS();_c();I_();uS=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new rm(t)}async open(t){let n=oS(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let l=await om(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,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),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await om(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,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),i=r.url(),s=t.timeoutMs??3e4,a=await lS(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${P_(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":{let h=sS(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){c=y}else c=h}let u=r.url();if(u!==i){let h=oS(u,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:h.reason}}let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await om(r,{observationCounter:o.observationCounter,screenshotPath:m,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}async screenshot(t){let{sessionId:n}=t,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),i;if(t.target!==void 0){let d=await lS(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${P_(t.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await d.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await dS(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);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(t){let n=this.sessions.get(t);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(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await dS(n,o,r);return i}catch{return null}}}});var gi={};Au(gi,{__resetBrowserRegistryForTests:()=>_4,browserProviderActive:()=>C4,closeBrowserProvider:()=>pS,getBrowserProvider:()=>R4,peekBrowserProvider:()=>A4});function $_(){Promise.resolve(pS()).then(()=>{process.exit(130)})}function D_(){Promise.resolve(pS()).then(()=>{process.exit(143)})}function F_(){Yn=null}function x4(){im||(process.on("SIGINT",$_),process.on("SIGTERM",D_),process.on("exit",F_),im=!0)}function L_(){im&&(process.removeListener("SIGINT",$_),process.removeListener("SIGTERM",D_),process.removeListener("exit",F_),im=!1)}async function R4(e){return Yn!==null?Yn:(fi!==null||(fi=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(O_(),M_)),n=y_(e),r=new t(n);return x4(),Yn=r,fi=null,r})()),fi)}async function pS(){if(Yn===null)return;let e=Yn;Yn=null,fi=null,L_(),await e.shutdown()}function C4(){return Yn!==null}function A4(){return Yn}function _4(){Yn=null,fi=null,L_()}var Yn,fi,im,hi=x(()=>{"use strict";iS();Yn=null,fi=null,im=!1});async function N_(e,t){try{return await u_(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function D4(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(hi(),gi));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function B_(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??D4,o=null,i=e,s=null,a=null;try{let c=await tm(n,e,{headers:$4,redirect:"follow",signal:t.signal});s=c.status,i=c.url||e;let d=c.headers.get("content-type")??"";if(c.ok){if(O4.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 c.text();if(M4.test(d)&&!P4.test(d))return{title:"",markdown:u.trim(),finalUrl:i,usedRender:!1};if(o=await N_(u,i),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<200)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),d=await N_(c.html,c.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),u=a instanceof Error?a.message:`HTTP ${s??"error"}`,m=new Error(`web_scrape could not retrieve ${e}: fetch failed (${u}) and render failed (${d}).`);throw m.cause=c,m}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${s??"error"}).`)}var P4,M4,O4,$4,U_=x(()=>{"use strict";p_();rS();ye();P4=/(text\/html|application\/xhtml\+xml)/i,M4=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,O4=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,$4={"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 N4(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(F4,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),L4),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Cr(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function j_(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?N4({apiKey:e.exaApiKey,fetchFn:e.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 H_(e,t){if(t.length===0)return`# Search results for "${e}"
872
+ `).trim()}function DV(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}async function u_(e,t){let{JSDOM:n,Readability:r,turndown:o}=await $V(),s=new n(e,{url:t}).window.document,a=(s.title??"").trim(),l=(()=>{try{let m=s.cloneNode(!0);return new r(m).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let m=d_(o.turndown(l.content)),f=(l.title??"").trim()||a,g=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:m,textLength:g,usedFallback:!1}}let c=s.body,d=c?.innerHTML??"",u=d_(o.turndown(d));return{title:a,markdown:u,textLength:DV(c),usedFallback:!0}}var nS,p_=x(()=>{"use strict";nS=null});function LV(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(i),r(t?.reason??new Error("aborted"))},i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function m_(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function NV(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function tm(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??LV,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await e(t,n);if(!FV.has(u.status)||d===o)return u;let m=NV(u,s)??m_(d,i,s);W("[web/retryFetch] retrying",{url:t,attempt:d,status:u.status,waitMs:m}),await u.body?.cancel().catch(()=>{}),await a(m,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let m=m_(d,i,s);W("[web/retryFetch] retrying after error",{url:t,attempt:d,waitMs:m}),await a(m,l)}}throw c??new Error("retryFetch: exhausted without a result")}var FV,rS=x(()=>{"use strict";ye();FV=new Set([429,502,503,504])});import{readFileSync as BV}from"node:fs";import{join as UV}from"path";function jV(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function f_(e,t){return jV(t).test(e)}function KV(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(HV.has(t))return!0;if(WV.has(t))return!1}return!1}function g_(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function GV(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function h_(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Vl(t),t}function qV(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function zV(e){try{return BV(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function JV(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=h_(t.defaultProfile)),n}function y_(e){let t=e?.env??v,n=e?.readFileSync??zV,r=e?.surface??t.AGENT_SURFACE,o=KV(t.AFK_BROWSER_HEADLESS,r),i=g_(t.AFK_BROWSER_ALLOWED_DOMAINS),s=g_(t.AFK_BROWSER_BLOCKED_DOMAINS),a=qV(t.AFK_BROWSER_DOM_SNAPSHOTS),l=GV(t.AFK_BROWSER_BACKEND),c=h_(t.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:i,blockedDomains:s,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=t.AFK_BROWSER_CONFIG,m=u!==void 0&&u.trim()!==""?u.trim():UV(bn(),"browser.json"),f=n(m);if(f===void 0)return d;let g;try{g=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${m}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${m} must be a JSON object`);let h=JV(d,g);return h.configPath=m,h}function oS(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(f_(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>f_(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var HV,WV,iS=x(()=>{"use strict";K();q();HV=new Set(["daemon","subagent","telegram","afk"]),WV=new Set(["repl","interactive","cli"])});import mi from"node:fs";import nm from"node:path";import{randomBytes as YV}from"node:crypto";import{chromium as VV}from"playwright";function XV(){try{return"5.75.2"}catch{}try{let e=nm.resolve(import.meta.dirname,"../../../package.json"),t=mi.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var QV,rm,b_=x(()=>{"use strict";q();ye();QV=XV(),rm=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}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=VV.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i=()=>{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",i,{once:!0});try{let s=await o.newPage(),a=await s.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await s.content(),c=s.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);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(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.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/${QV}`}}loadStorageState(t){let n=Xl(t);try{if(!mi.existsSync(n))return;let r=JSON.parse(mi.readFileSync(n,"utf8"));return W("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){W("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Xl(t);if(!mi.existsSync(r))return;let o=await n.storageState(),i=nm.join(nm.dirname(r),`.${nm.basename(r)}.${process.pid}.${YV(4).toString("hex")}.tmp`);mi.writeFileSync(i,JSON.stringify(o),{mode:384}),mi.chmodSync(i,384),mi.renameSync(i,r),W("[browser/vault] saved session",{profile:t,file:r})}catch(r){W("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as ZV}from"crypto";function sS(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of e4)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function w_(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&t4.test(e.label))}function S_(e){return ZV("sha256").update(e,"utf8").digest("hex").slice(0,8)}function v_(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var e4,t4,_c=x(()=>{"use strict";e4=[{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}];t4=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as n4}from"node:crypto";function r4(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function o4(e,t,n){return`el_${n4("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function i4(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function k_(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function E_(e,t){let n=e.role??"",r=e.name??"";T_.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])E_(i,t)}async function s4(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let d=window.getComputedStyle(s);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},x_).catch(()=>[])}async function a4(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in i?i.value:void 0,u=d!==void 0?String(d):void 0,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},x_).catch(()=>[])}function l4(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function om(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=l4(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=s4(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,m,f,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],E_(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await a4(e)).filter(U=>T_.has(U.role??"")));let w=new Map;for(let O of m){let U=k_(O.name),j=w.get(U);(!j||j.bbox.w===0&&O.bbox.w>0)&&w.set(U,O)}let S=y.map(O=>({ax:O,dom:w.get(k_(O.name??""))})),k=r?S:S.filter(O=>O.dom?O.dom.bbox.w>0||O.dom.bbox.h>0:!0);k.sort((O,U)=>{let j=O.dom?.bbox.y??0,$=U.dom?.bbox.y??0;if(j!==$)return j-$;let B=O.dom?.bbox.x??0,P=U.dom?.bbox.x??0;return B-P}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let C=k.slice(0,n).map((O,U)=>{let j=O.ax.role??"generic",$=O.ax.name??"",B=o4(j,$,U),P=O.dom?.bbox??{x:0,y:0,w:0,h:0},N=O.dom?.type??null,_=null;O.ax.value!==void 0&&O.ax.value!==null&&(_=String(O.ax.value)),O.ax.checked!==void 0&&(_=String(O.ax.checked)),w_({role:j,kind:N})&&(_="[redacted]");let M={disabled:O.ax.disabled??!1};O.ax.checked!==void 0&&(M.checked=O.ax.checked===!0||O.ax.checked==="mixed"),O.ax.selected!==void 0&&(M.selected=O.ax.selected),O.ax.expanded!==void 0&&(M.expanded=O.ax.expanded);let I;O.dom?.testId?I=`[data-testid="${O.dom.testId}"]`:O.dom?.id&&(I=`#${O.dom.id}`);let H={id:B,role:j,label:r4($),kind:N,value:_,state:M,bbox:P};return I!==void 0&&(H.selector=I),H}),D="idle";try{let O=await e.evaluate(()=>document.readyState);O==="loading"?D="loading":O==="interactive"?D="navigating":D="idle"}catch{D="navigating"}D!=="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 R=i4(f),F=`obs_${t.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:F,url:g,title:h,textSummary:R,interactive:C,status:{httpStatus:t.httpStatus??null,loadingState:D,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:A}}var T_,x_,R_=x(()=>{"use strict";_c();T_=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);x_="a[href], button, input, select, textarea, [role], [tabindex], label"});async function C_(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>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 aS(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>C_(e,i)))).filter(o=>o!==null)}async function c4(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function lS(e,t,n){switch(t.kind){case"element_id":return d4(e,t,n);case"selector":return u4(e,t);case"semantic":return p4(e,t)}}async function d4(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await aS(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function u4(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await aS(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function p4(e,t){return t.role!==void 0?m4(e,t.text,t.role):f4(e,t.text,t)}async function m4(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await aS(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function f4(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let d=[];s>0&&d.push({loc:r,count:s}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:i,count:l});let u=await c4(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=u.slice(0,5),f=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await C_(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let k=0;k<w.length;k++)S=S*31+w.charCodeAt(k)>>>0;f.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var A_=x(()=>{"use strict"});import{randomBytes as g4}from"crypto";import{mkdir as h4,stat as y4,writeFile as b4}from"fs/promises";import{join as cS}from"path";import{gzip as w4}from"zlib";import{promisify as S4}from"util";function v4(e){return cS(Vo(e),"browser")}function k4(e){return cS(v4(e),"screenshots")}function T4(){return new Date().toISOString().replace(/[:.]/g,"-")}function E4(){return g4(3).toString("hex")}async function dS(e,t,n){if(t.length>__)throw new Error(`writeScreenshotSidecar: buffer exceeds ${__} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=k4(e);await h4(r,{recursive:!0});let o=`${T4()}-${E4()}-${n}.png`,i=cS(r,o);await b4(i,t);let{size:s}=await y4(i);return{path:i,bytes:s}}var QEe,__,I_=x(()=>{"use strict";q();_c();QEe=S4(w4);__=5*1024*1024});var M_={};Au(M_,{PlaywrightProvider:()=>uS});function P_(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var uS,O_=x(()=>{"use strict";b_();R_();A_();iS();_c();I_();uS=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new rm(t)}async open(t){let n=oS(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let l=await om(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,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),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await om(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,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),i=r.url(),s=t.timeoutMs??3e4,a=await lS(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${P_(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":{let h=sS(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){c=y}else c=h}let u=r.url();if(u!==i){let h=oS(u,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:h.reason}}let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await om(r,{observationCounter:o.observationCounter,screenshotPath:m,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}async screenshot(t){let{sessionId:n}=t,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),i;if(t.target!==void 0){let d=await lS(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${P_(t.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await d.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await dS(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);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(t){let n=this.sessions.get(t);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(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await dS(n,o,r);return i}catch{return null}}}});var gi={};Au(gi,{__resetBrowserRegistryForTests:()=>_4,browserProviderActive:()=>C4,closeBrowserProvider:()=>pS,getBrowserProvider:()=>R4,peekBrowserProvider:()=>A4});function $_(){Promise.resolve(pS()).then(()=>{process.exit(130)})}function D_(){Promise.resolve(pS()).then(()=>{process.exit(143)})}function F_(){Yn=null}function x4(){im||(process.on("SIGINT",$_),process.on("SIGTERM",D_),process.on("exit",F_),im=!0)}function L_(){im&&(process.removeListener("SIGINT",$_),process.removeListener("SIGTERM",D_),process.removeListener("exit",F_),im=!1)}async function R4(e){return Yn!==null?Yn:(fi!==null||(fi=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(O_(),M_)),n=y_(e),r=new t(n);return x4(),Yn=r,fi=null,r})()),fi)}async function pS(){if(Yn===null)return;let e=Yn;Yn=null,fi=null,L_(),await e.shutdown()}function C4(){return Yn!==null}function A4(){return Yn}function _4(){Yn=null,fi=null,L_()}var Yn,fi,im,hi=x(()=>{"use strict";iS();Yn=null,fi=null,im=!1});async function N_(e,t){try{return await u_(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function D4(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(hi(),gi));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function B_(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??D4,o=null,i=e,s=null,a=null;try{let c=await tm(n,e,{headers:$4,redirect:"follow",signal:t.signal});s=c.status,i=c.url||e;let d=c.headers.get("content-type")??"";if(c.ok){if(O4.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 c.text();if(M4.test(d)&&!P4.test(d))return{title:"",markdown:u.trim(),finalUrl:i,usedRender:!1};if(o=await N_(u,i),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<200)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),d=await N_(c.html,c.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),u=a instanceof Error?a.message:`HTTP ${s??"error"}`,m=new Error(`web_scrape could not retrieve ${e}: fetch failed (${u}) and render failed (${d}).`);throw m.cause=c,m}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${s??"error"}).`)}var P4,M4,O4,$4,U_=x(()=>{"use strict";p_();rS();ye();P4=/(text\/html|application\/xhtml\+xml)/i,M4=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,O4=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,$4={"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 N4(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(F4,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),L4),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Cr(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function j_(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?N4({apiKey:e.exaApiKey,fetchFn:e.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 H_(e,t){if(t.length===0)return`# Search results for "${e}"
873
873
 
874
874
  (no results)`;let n=[`# Search results for "${e}"`,""];return t.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(`
875
875
  `).trimEnd()}var F4,L4,W_=x(()=>{"use strict";co();F4="https://api.exa.ai/search",L4=10});function G4(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.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,i;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};i=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let s=B4;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};s=Math.min(t.timeout_ms,U4)}let a=j4;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(t.max_bytes,H4)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function mS(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:Er(e,t),truncated:!0}}function q4(e){let t=[],n=e;for(let o=0;o<4&&n instanceof Error;o++)t.push(n.message),n=n.cause;let r=t.join(" | ");return K4.some(o=>r.includes(o))}function z4(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env;return async(r,o)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let i=G4(r);if("error"in i)return{content:i.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 s=new AbortController,a=()=>{s.abort(o.reason)},l,c=()=>{let d=s.signal.reason;return d instanceof Error?d.message:String(d??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),l=setTimeout(()=>{s.abort(new Error(`web_scrape timeout after ${i.timeoutMs}ms`))},i.timeoutMs),i.mode==="raw"){let u;try{u=await tm(t,i.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:s.signal})}catch(g){return s.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape network error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}if(!u.ok)return{content:`web_scrape HTTP ${u.status} ${u.statusText||""}`.trimEnd()+` for ${i.url}`,isError:!0};let m;try{m=await u.text()}catch(g){return{content:`web_scrape read error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}let f=mS(m,i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let u=await B_(i.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:i.timeoutMs,signal:s.signal});if(u.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${i.url}.`,isError:!0};let m=mS(u.markdown,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}catch(u){if(s.signal.aborted)return{content:`web_scrape aborted: ${c()}`,isError:!0};let m=u instanceof Error?u.message:String(u),f=q4(u)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${m}${f}`,isError:!0}}let d=j_({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in d)return{content:d.error,isError:!0};try{let u=await d.search(i.query,{limit:W4,timeoutMs:i.timeoutMs,signal:s.signal}),m=mS(H_(i.query,u),i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}catch(u){return s.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${u instanceof Error?u.message:String(u)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),o.removeEventListener("abort",a)}}}var B4,U4,j4,H4,W4,K4,K_,G_=x(()=>{"use strict";U_();W_();rS();Ws();B4=3e4,U4=12e4,j4=1e5,H4=1e6,W4=10,K4=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"];K_=z4()});import{existsSync as z_,mkdirSync as J4,readFileSync as Y4,renameSync as V4,unlinkSync as X4,writeFileSync as Q4}from"node:fs";import{dirname as q_,join as Z4}from"node:path";import{randomBytes as e8}from"node:crypto";function cn(e){let t=e??fb();if(!z_(t))return[];try{let n=Y4(t,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${t}: ${r}`),[]}}function yi(e,t){let n=t??fb();J4(q_(n),{recursive:!0});let r=Z4(q_(n),`.schedules.json.${process.pid}.${e8(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{Q4(r,o,"utf-8"),V4(r,n)}catch(i){try{z_(r)&&X4(r)}catch{}throw i}}function sm(e,t){let n=cn(t),r=n.map(l=>l.id),o=t8(e.name),i=n8(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),yi(n,t),a}function am(e,t){let n=cn(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(yi(o,t),!0)}function Ic(e,t){return cn(t).find(n=>n.id===e)}function t8(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function n8(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function J_(e){return{taskId:e.id,command:e.command,trigger:e.trigger??"cron",...e.cron!==void 0?{cronExpression:e.cron}:{},...e.notifyOn!==void 0?{notifyOn:e.notifyOn}:{},...e.notifyChat!==void 0?{notifyChat:e.notifyChat}:{}}}var lm=x(()=>{"use strict";q()});import{existsSync as r8,readFileSync as o8}from"node:fs";import{join as i8}from"node:path";async function En(e,t,n){let r;try{let o=i8(Lu("default"),"port");if(!r8(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=o8(o,"utf-8").trim();if(r=parseInt(i,10),Number.isNaN(r))return{synced:!1,detail:"daemon-not-detected (invalid port file)"}}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let o=await fetch(`http://localhost:${r}${t}`,{method:e,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return o.ok?{synced:!0,detail:"synced"}:e==="POST"&&o.status===409?{synced:!0,detail:"already-registered"}:e==="DELETE"&&o.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${o.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}var mo,fS=x(()=>{"use strict";q();mo="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start."});import{existsSync as s8}from"node:fs";import{readFile as a8}from"node:fs/promises";var Y_,V_,X_,Q_,Z_=x(()=>{"use strict";lm();q();fS();Y_=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=n.notifyChat;if(o!==void 0&&typeof o!="number"&&typeof o!="string")return{content:"Invalid input: notifyChat must be a number (chat id) or string (chat id or alias name)",isError:!0};let i=sm({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),s=i.enabled?await En("POST","/tasks",{taskId:i.id,command:i.command,cron:i.cron,trigger:i.trigger,notifyOn:i.notifyOn,...i.notifyChat!==void 0?{notifyChat:i.notifyChat}:{}}):await En("DELETE",`/tasks/${i.id}`);return{content:JSON.stringify({id:i.id,name:i.name,cron:i.cron,enabled:i.enabled,daemonSynced:s.synced,syncDetail:s.detail,...s.synced?{}:{syncNote:mo}})}},V_=async(e,t)=>{let n=cn();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},X_=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,i=Fn();if(!s8(i))return{content:JSON.stringify([])};let s;try{let c=await a8(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
@@ -1582,7 +1582,7 @@ ${d}`}function rT(e,t){let n=rN[t.status];e.out.line(` ${n} ${p.bold(t.jobId)}
1582
1582
  `,i=Fre(r,n,{trim:!1,hard:!0,wordWrap:!1}).split(`
1583
1583
  `);for(;i.length>0&&i[i.length-1]==="";)i.pop();return i}measure(t,n){let r=this.stream.columns??80,o=Math.max(1,e.wrapToPhysicalLines(t,r).length),i=Math.max(1,n);return{topRow:Math.max(1,i-o+1),lineCount:o}}render(t,n,r){let o=Math.max(1,n),i=Math.max(1,r??1),s=this.stream.columns??80,a=this.stream.isTTY===!0,l=e.wrapToPhysicalLines(t,s),c=Math.max(1,l.length),d=this.previousRawLineCount>c?this.previousRawLineCount-c:0,u=Math.max(0,o-c+1-i),m=Math.min(d,u),f=m>0?[...Array(m).fill(""),...l]:l,g=f.length,h=Math.max(1,o-g+1),y="";if(a&&(y+=mB),this.previousLineCount>0)for(let b=0;b<this.previousLineCount;b++){let w=this.previousTopRow+b;y+=jd(w,1)+mT}for(let b=0;b<g;b++){let w=h+b;y+=jd(w,1)+mT+(f[b]??"")}if(y+=jd(h+g-1,1),a&&(y+=fB),this.stream.isTTY)try{this.stream.write(Lre)}catch{}try{this.stream.write(y)}catch{try{this.stream.isTTY&&this.stream.write(gB)}catch{}}if(v.NODE_ENV!=="production"&&g<c)throw new Error(`CupFrameRenderer invariant violation: lineCount (${g}) < rawLineCount (${c}). previousLineCount must cover at least previousRawLineCount \u2014 padded footprint must be \u2265 raw content size; see PR #557.`);this.previousTopRow=h,this.previousLineCount=g,this.previousRawLineCount=c}resetGeometry(){this.previousTopRow=0,this.previousLineCount=0,this.previousRawLineCount=0}clear(t=0){if(this.previousLineCount===0)return;let n="",r=this.stream.isTTY===!0;r&&(n+=mB);for(let o=0;o<this.previousLineCount;o++){let i=this.previousTopRow+o;n+=jd(i,1)+mT}n+=jd(Math.max(1,(this.stream.rows??24)-1-t),1),r&&(n+=fB);try{this.stream.write(n)}catch{}this.previousTopRow=0,this.previousLineCount=0,this.previousRawLineCount=0}done(){if(this.previousTopRow=0,this.previousLineCount=0,this.previousRawLineCount=0,this.stream.isTTY)try{this.stream.write(gB)}catch{}}};var Hd=null;function Wd(e){if(Hd!==null)throw new Error(`stdin claim conflict: '${Hd.name}' already holds the claim, '${e}' cannot acquire it concurrently.`);let t=!1,n={release(){t||(t=!0,Hd?.handle===n&&(Hd=null))}};return Hd={name:e,handle:n},n}async function hB(e,t){let n=Wd(e);try{return await t()}finally{n.release()}}function yB(e){if(!(!e.armed||e.suspended)){if(e.logUpdate)try{e.logUpdate.clear(e.scrollRegion?.getExtraRows()??0),e.logUpdate.done()}catch{}e.handleKeypress&&e.stdin.removeListener("keypress",e.handleKeypress);try{e.stdin.setRawMode(!1)}catch{}e.caretBlinkController.stop(),e.suspended=!0}}function bB(e){if(!(!e.armed||!e.suspended)){try{e.stdin.setRawMode(!0)}catch{}e.handleKeypress&&e.stdin.on("keypress",e.handleKeypress),e.suspended=!1,e.repaint(),e.caretBlinkController.start()}}async function wB(e){if(e.armed)throw new Error("TerminalCompositor: arm() called while already armed");if(!(!e.stdout.isTTY||!e.stdin.isTTY)){e.anchorRow=e.declaredAnchorRow,e.logUpdate||(e.logUpdate=new hh(e.stdout)),e.stdinClaim=Wd("TerminalCompositor.arm"),e.wasRaw=e.stdin.isRaw??!1;try{e.stdin.setRawMode(!0)}catch{e.stdinClaim?.release(),e.stdinClaim=null,e.logUpdate=null,e.wasRaw=!1;return}try{e.stdout.write("\x1B[?2004h")}catch{}e.stdin.resume(),Fi(e.stdin),e.handleKeypress=(t,n)=>{let r=e.pasting?!1:e.caretBlinkController.resetVisible(),o=e.repaintCount;dB(e,t,n),r&&e.repaintCount===o&&e.repaint()},e.stdin.on("keypress",e.handleKeypress),e.armed=!0,e.canceled=!1,e.resizeUnsub=He.subscribe(()=>{e.armed&&e.repaint()}),e.resizeImmediateUnsub=He.subscribeImmediate(()=>{if(!e.armed)return;let t=e.stdout.rows??24;if(e.lastKnownRows>0&&t>e.lastKnownRows){let n=e.scrollRegion?.getExtraRows()??0,r=e.logUpdate?.topRow??0,o=e.committedBand.length>0?e.committedBandTopRow:0,i=[r,o].filter(l=>l>0),s=i.length>0?Math.min(...i):0,a=Math.max(1,e.lastKnownRows-1-n);s>0&&s<=a&&(e.pendingResizeErase={top:s,bottom:a})}else e.pendingResizeErase=null;e.logUpdate?.resetGeometry?.(),e.bandGeometryStale=!0}),e.repaint(),e.caretBlinkController.start()}}function SB(e){if(e.spinnerController.dispose(),e.caretBlinkController.stop(),!e.armed){e.resetState();return}if(e.handleKeypress&&(e.stdin.removeListener("keypress",e.handleKeypress),e.handleKeypress=null),e.resizeUnsub&&(e.resizeUnsub(),e.resizeUnsub=null),e.resizeImmediateUnsub&&(e.resizeImmediateUnsub(),e.resizeImmediateUnsub=null),Nre(e),e.logUpdate)try{e.logUpdate.clear(e.scrollRegion?.getExtraRows()??0),e.logUpdate.done()}catch{}if(e.stdout.isTTY&&e.stdin.isTTY){try{e.stdout.write("\x1B[?2004l")}catch{}try{e.stdin.setRawMode(e.wasRaw)}catch{}}e.stdinClaim&&(e.stdinClaim.release(),e.stdinClaim=null),e.armed=!1,e.resetState(),e.ghostEngine?.dispose()}function Nre(e){let t=e.committedBand.length-e.committedBandPaintedRows;if(t<=0)return;let n=e.committedBand.slice(0,t),r=Math.max(1,e.stdout.rows??24),o=Math.max(e.anchorRow??1,1),i=()=>{let s=Math.max(1,r-o+1);for(let a=0;a<n.length;a+=s){let l=n.slice(a,Math.min(a+s,n.length)),c=l.map((d,u)=>et(o+u,d)).join("");e.stdout.write(`${c}\x1B[${r};1H${`
1584
1584
  `.repeat(l.length)}`)}};try{e.scrollRegion?e.scrollRegion.withFullScrollRegion(i):i()}catch{}}function vB(e){e.overlay="",e.input=J.seed(""),e.queued=!1,e.pendingSubmissions=[],e.canceled=!1,e.backgrounded=!1,e.softStopped=!1,e.postEscCoalesce=!1,e.postEscPayload=null,e.paused=!1,e.pendingTrailingRepaint=!1,e.burstActive=!1,e.activeGhost=null,e.anchorRow=void 0,e.hasCommitted=!1,e.clearCommittedBand(),e.commitInFlight=!1,e.pendingResizeErase=null,e.bandGeometryStale=!1,e.lastKnownRows=0,e.pickerController=null,e.inputMode="streaming",e.attachments=[],e.pasting=!1,e.pasteStartBufferLen=0,e.pasteStartCursor=0,e.pasteRegistry.clear(),e.clipboardFailureMsg=null,e.autocompleteState?.reset(),e.resizeUnsub&&(e.resizeUnsub(),e.resizeUnsub=null),e.resizeImmediateUnsub&&(e.resizeImmediateUnsub(),e.resizeImmediateUnsub=null)}var al=class{stdout;stdin;onCancel;onSoftStop;softStopped=!1;postEscCoalesce=!1;postEscPayload=null;onBackground;onRewindRequest;lastIdleEscAt=0;onPauseInterrupt;onShiftTab;onOpenEditor;promptTextFn;history;autocompleteState;formatInputBuffer;scrollRegion;anchorRow;declaredAnchorRow;onSubmit;attachments=[];pasting=!1;pasteStartBufferLen=0;pasteStartCursor=0;pasteRegistry=new Map;clipboardInFlight=!1;clipboardFailureMsg=null;inputMode="streaming";pickerController=null;pickerSavedMode="streaming";armed=!1;suspended=!1;canceled=!1;backgrounded=!1;paused=!1;wasRaw=!1;stdinClaim=null;logUpdate=null;overlay="";input=J.seed("");queued=!1;pendingSubmissions=[];handleKeypress=null;resizeUnsub=null;resizeImmediateUnsub=null;spinnerController;caretBlinkController;repaintCount=0;pendingTrailingRepaint=!1;burstActive=!1;committing=!1;hasCommitted=!1;committedBand=[];committedBandTopRow=0;committedBandBottomRow=0;lastMeasuredFrameTop=0;committedBandPaintedRows=0;bandReflowCache=null;lastKnownRows=0;pendingResizeErase=null;bandGeometryStale=!1;commitInFlight=!1;debugCompositor=!!v.AFK_DEBUG_COMPOSITOR;ghostEngine;ghostGetContext;activeGhost=null;debugLog(t,n={}){if(!this.debugCompositor)return;let r=process.hrtime.bigint(),o=Object.entries(n).map(([i,s])=>{let a=typeof s=="string"?JSON.stringify(s.length>60?s.slice(0,57)+"...":s):String(s);return`${i}=${a}`}).join(" ");process.stderr.write(`[compositor] t=${r} ${t}${o?" "+o:""}
1585
- `)}constructor(t){this.stdout=t.stdout,this.stdin=t.stdin,this.onCancel=t.onCancel,this.onSoftStop=t.onSoftStop,this.onBackground=t.onBackground,this.onPauseInterrupt=t.onPauseInterrupt,this.onShiftTab=t.onShiftTab,this.onOpenEditor=t.onOpenEditor;let n=t.promptText;if(typeof n=="function")this.promptTextFn=n;else if(typeof n=="string")this.promptTextFn=()=>n;else{let r=" "+p.dim("\u23AF")+" ";this.promptTextFn=()=>r}this.history=t.history,this.autocompleteState=t.autocompleteState,this.formatInputBuffer=t.formatInputBuffer,this.scrollRegion=t.scrollRegion,this.spinnerController=new oh({captureMode:t.captureMode??!1,goblin:t.goblinSpinner??!1,onTick:()=>this.repaint()}),this.caretBlinkController=new ih({enabled:t.caretBlink??!1,captureMode:t.captureMode??!1,intervalMs:t.caretBlinkIntervalMs??530,onTick:()=>this.repaint()}),this.onSubmit=t.onSubmit,this.anchorRow=t.anchorRow,this.declaredAnchorRow=t.anchorRow,this.ghostEngine=t.suggest?.engine,this.ghostGetContext=t.suggest?.getContext}isArmed(){return this.armed}setAnchorRow(t){this.anchorRow=t,this.declaredAnchorRow=t}suspendInput(){yB(this)}resumeInput(){bB(this)}setOnSubmit(t){this.onSubmit=t??void 0}setOnCancel(t){this.onCancel=t??void 0}getOnCancel(){return this.onCancel}setOnBackground(t){this.onBackground=t??void 0}setOnRewindRequest(t){this.onRewindRequest=t??void 0}setOnOpenEditor(t){this.onOpenEditor=t??void 0}enterPickerMode(t){eB(this,t)}exitPickerMode(){tB(this)}repaintPicker(){nB(this)}setInputMode(t){this.flushPendingRepaint(),rB(this,t)}getInputMode(){return oB(this)}async arm(){return wB(this)}disarm(){SB(this)}setOverlay(t){t!==this.overlay&&(this.debugLog("setOverlay",{framesLen:t.length,anchorRow:this.anchorRow??null}),this.overlay=t,this.repaint())}setSpinner(t){this.stdout.isTTY&&this.spinnerController.set(t)}commitAbove(t){this.flushPendingRepaint(),YN(this,t)}clearCommittedBand(){Nd(this)}flushResizeGhostErase(){XN(this)}resetCommittedBand(){VN(this)}repositionCommittedBand(t,n,r){QN(this,t,n,r)}getBuffer(){return EN(this)}getPendingCount(){return this.pendingSubmissions.length}getAttachments(){return[...this.attachments]}get caretVisible(){return this.caretBlinkController.visible}renderInputLine(){return GN(this)}updateAutocomplete(){dh(this)}updateGhost(){jN(this)}renderDropdownRows(){return qN(this)}renderHintRow(){return zN(this)}repaint(){this.repaintCount++,this.pendingTrailingRepaint=!1,gh(this)}scheduleRepaint(){if(this.repaintCount++,!this.burstActive){this.burstActive=!0,this.pendingTrailingRepaint=!1,gh(this),queueMicrotask(()=>{this.burstActive=!1,this.flushPendingRepaint()});return}this.pendingTrailingRepaint=!0}flushPendingRepaint(){this.pendingTrailingRepaint&&(this.pendingTrailingRepaint=!1,this.armed&&gh(this))}clearScreen(){this.logUpdate?.resetGeometry?.(),this.stdout.write("\x1B[H\x1B[2J"),this.repaint()}resetState(){vB(this)}applyEdit(t){return cB(this,t)}prefillInput(t){this.applyEdit(J.seed(t))}applyDropdownSelection(){return HN(this)}applyGhostAccept(){return WN(this)}};K();import fT from"chalk";var Hre=/(?<=\s|^)(\/[A-Za-z][\w:-]*)(?=\s|$)/g,Wre=/(?<=\s|^)(@[~\w./-]*)(?=\s|$)/g,Kre=/\[Pasted text #[0-9a-f]+ \+\d+ (?:lines|chars)\]/g,kB={mint:p.mint};function Gre(e){let t=kB[e];if(t)return t;let n=e.lastIndexOf(":");if(n>=0){let r=e.slice(n+1),o=kB[r];if(o)return o}return null}var TB=null,EB=null,xB=null,RB=null,CB="";function No(e,t){if(fT.level===0)return e;let n=t.version?.(),r=n!==void 0;if(r&&RB===t&&TB===e&&EB===fT.level&&xB===n)return CB;let s=e.replace(Hre,a=>{let l=a.slice(1);return t.has(l)?(Gre(l)??p.brand)(a):p.meta(a)}).replace(Wre,a=>p.fileRef(a)).replace(Kre,a=>p.meta(a));return r&&(RB=t,TB=e,EB=fT.level,xB=n,CB=s),s}K();import{pathToFileURL as qre}from"node:url";var zre="\x1B]8;;\x1B\\",Jre=new Set(["iterm2","wezterm","kitty","vscode","ghostty","windows-terminal","konsole","gnome-terminal","alacritty"]),Yre=5e3;function Vre(e=process.env,t=process.stdout.isTTY===!0){let n=e.FORCE_HYPERLINK;if(n!==void 0&&n.length>0)return n!=="0"&&n.toLowerCase()!=="false";if(!t||e.CI!==void 0&&e.CI.length>0)return!1;let r=Ui(e);if(!Jre.has(r))return!1;if(r==="gnome-terminal"&&e.VTE_VERSION!==void 0){let o=Number.parseInt(e.VTE_VERSION,10);if(!Number.isFinite(o)||o<Yre)return!1}return!0}var gT;function yh(){return gT===void 0&&(gT=Vre()),gT}function Xre(e,t){return`\x1B]8;;${t}\x1B\\${e}${zre}`}function bh(e,t){try{return Xre(e,qre(t).href)}catch{return e}}function Kd(e){let t=/[a-z][a-z0-9+.-]*:\/\/[^\s<>\"`]+/gi,n="",r=0;for(let o of e.matchAll(t)){let i=o[0]??"",s=o.index??r;n+=AB(e.slice(r,s)),n+=i,r=s+i.length}return n+=AB(e.slice(r)),n}function AB(e){let t=yh();return e.replace(/\/(?:[^/\s,)]+\/){2,}([^/\s,)]+)/g,(n,r)=>t?bh(r,n):r)}function Qre(e){let t=/^(\s*[("]?\s*)cd\s+\S+\s+&&\s+(?!cd\s)(.+)$/.exec(e);return t?(t[1]??"")+(t[2]??""):e}var _B=60;function hT(e,t){let n=e.trim().replace(/^\((.*)\)$/s,"$1"),r;try{r=JSON.parse(n)}catch{return e}if(!r||typeof r!="object")return e;let o=r;for(let i of t){let s=o[i];if(typeof s=="string"&&s.length>0){let a=De(s);if(a.length===0)continue;return`(${a.length>_B?ae(a,_B,"\u2026"):a})`}}return e}function IB(e,t){if(e==="bash"||e==="Bash")return Qre(t);if(e==="compose"||e==="Compose"){let n=t.trim().replace(/^\((.*)\)$/s,"$1");try{let r=JSON.parse(n);if(r&&typeof r=="object"){let o=Array.isArray(r.nodes)?r.nodes.length:void 0,i=Array.isArray(r.edges)?r.edges.length:0;if(o!==void 0){let s=`${o} node${o===1?"":"s"}`,a=i>0?`, ${i} edge${i===1?"":"s"}`:"";return`(${s}${a})`}}}catch{}}return e==="agent"||e==="Agent"?hT(t,["id_prefix","prompt"]):e==="Task"?hT(t,["description","prompt"]):e==="skill"||e==="Skill"?hT(t,["name","arguments"]):e==="ask_question"?Zre(t):t}function Zre(e){let t=e.trim().replace(/^\((.*)\)$/s,"$1");try{let n=JSON.parse(t);if(!n||typeof n!="object")return e;let r=n,o=typeof r.type=="string"?r.type:"text";if(o==="choice"||o==="multi_choice"){let i=r.choices,s=Array.isArray(i)?i.length:0;return s>0?`(${o}: ${s} option${s===1?"":"s"})`:`(${o})`}return`(${o})`}catch{return e}}function eoe(e){return e.replace(/[\r\n]+/g," ")}var toe={"(":")","{":"}","[":"]"};function PB(e,t,n="\u2026"){let r=e.charAt(0),o=toe[r];return!(o&&e.endsWith(o)&&e.length>=2)||X(e)<=t?ae(e,t,n):t<3?t>=2?r+o:ae(e,t,n):ae(e,t-1,n)+o}function Ur(e,t){let n=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/s.exec(e);if(n){let r=n[1],o=Kd(IB(r,n[2]??"")),i=tr(r),{color:s,glyph:a}=Ha(r),l=lv(i),c=l?` [${l}]`:"";if(t!==void 0){let u=(a+" ").length+r.length+c.length,m=Math.max(1,t-u);o=PB(o,m)}o=eoe(o);let d=s(a+" ")+s.bold(r)+p.toolArg(o);return l?d+p.dim(c):d}return p.chrome("\u25CF ")+p.toolArg(e)}K();var MB=8,wh=30;function noe(){let e=v.AFK_DIFF_LINES;if(e===void 0)return wh;let t=e.trim();if(!/^\d+$/.test(t))return wh;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:wh}function roe(){let e=v.AFK_SHOW_DIFFS;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function ooe(e){let t=p.diffAdd(`+${e.addedLines}`),n=p.diffRemove(`-${e.removedLines}`),r=e.hunks.length,o=p.dim(`across ${r} hunk${r===1?"":"s"}`);return`${t} ${n} ${o}`}var ioe=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;function soe(e){let t=Ie(e.text).replace(ioe,"");return e.kind==="+"?p.diffAdd("+ "+t):e.kind==="-"?p.diffRemove("- "+t):p.dim(" "+t)}var bT=new WeakMap;function jr(e,t,n){if(roe())return[];if(e.hunks.length===0)return[];let r=t==="overlay"?MB:noe(),o=t+"|"+n+"|"+r,i=bT.get(e);if(i!==void 0){let f=i.get(o);if(f!==void 0)return f}let s=[];s.push(n+ooe(e));let a=[];for(let f of e.hunks){let g=`@@ -${f.oldStart},${f.oldLines} +${f.newStart},${f.newLines} @@`;a.push({kind:"header",text:p.diffHunk(g)});for(let h of f.lines)a.push({kind:"body",text:soe(h)})}if(r===0){for(let f of a)s.push(n+f.text);return yT(e,o,s),s}let l=0;for(let f of a)f.kind==="body"&&l++;if(l<=r){for(let f of a)s.push(n+f.text);return yT(e,o,s),s}let c=0;for(let f of a)f.kind==="header"?s.push(n+f.text):c<r&&(s.push(n+f.text),c++);let d=l-r,u=`line${d===1?"":"s"}`,m=t==="flush"?" (set AFK_DIFF_LINES=0 to expand)":"";return s.push(n+p.dim(`\u2026 +${d} more diff ${u}${m}`)),yT(e,o,s),s}function yT(e,t,n){let r=bT.get(e);r===void 0&&(r=new Map,bT.set(e,r)),r.set(t,n)}function Bo(e){return e?p.error("\u2717"):p.success("\u2713")}var Gd=3,OB=2,$B=3;function DB(e){switch(tr(e)){case"read":return"Reading\u2026";case"write":return"Writing\u2026";case"web":return"Fetching\u2026";case"shell":return"Running\u2026";default:return"Running\u2026"}}function aoe(e,t){return e?e==="grep"||e==="Grep"?t===1?"match":"matches":e==="glob"||e==="Glob"?t===1?"path":"paths":t===1?"line":"lines":t===1?"line":"lines"}function Hr(e,t,n=60,r){let o=e.isError?p.error:p.dim,i=t??v.HOME??"___NOHOME___";if(e.display!==void 0&&!e.isError)return o(e.display);if(e.persistedPath){let a=e.persistedPath.startsWith(i)?"~"+e.persistedPath.slice(i.length):e.persistedPath,l=yh()?bh(a,e.persistedPath):a;return o(`saved \u2192 ${l}`)}if(e.lineCount!==void 0&&e.lineCount>1)return o(`${e.lineCount} ${aoe(r,e.lineCount)}`);let s=e.content.length>n?e.content.slice(0,n-3)+"\u2026":e.content;return o(De(s))}function ll(e){return!e||typeof e.batchSize!="number"||typeof e.batchIndex!="number"||e.batchSize<=1?"":p.dim(` \u2225${e.batchIndex}/${e.batchSize}`)}K();function qd(e,t){if(e.length<=t)return e;let n=e.length-t,r=e.slice(0,n),o=e.slice(n),i=LB(r);return[{kind:"overflow",count:r.length,text:i},...o]}function loe(e,t){return t<=1||e.endsWith("s")||/(sh|ch|x|z)$/i.test(e)?e:e+"s"}var coe=5,FB=60;function LB(e){let t=new Map,n=0;for(let i of e)i.kind==="group"?(t.set(i.toolName,(t.get(i.toolName)??0)+i.entries.length),n+=i.entries.length):(t.set(i.toolName,(t.get(i.toolName)??0)+1),n+=1);if(n===0)return"";if(e.length>0&&e.every(i=>Je.has(i.toolName))&&new Set(e.map(i=>i.toolName)).size===1){let i=[],s=!1;for(let a of e){let c=(a.kind==="group"?a.label:a.toolInput).trim();if(!c.startsWith("(")||!c.endsWith(")")){s=!0;break}let d=c.slice(1,-1),u=De(d);if(!u){s=!0;break}let m=u.length>FB?u.slice(0,FB-1)+"\u2026":u,f=a.kind==="group"?a.entries.length:1;i.push({display:m,entries:f})}if(!s&&i.length>0){let a=i.slice(0,coe),l=a.map(({display:m,entries:f})=>f>1?`${m} \xD7${f}`:m),c=a.reduce((m,f)=>m+f.entries,0),d=n-c,u=l.join(", ")+(d>0?` (+${d})`:"");return`\u2026 +${n} more: ${u}`}}let o=[];for(let[i,s]of t)o.push(`${s} ${loe(i,s)}`);return`\u2026 +${n} (${o.join(", ")})`}function Sh(e,t=Pn()){return e.map((n,r)=>({sibling:n,connector:r===e.length-1?t.lastConnector:t.midConnector}))}function wT(e,t){return t?[...e,{kind:"resultSummary",summary:t}]:e}function ST(e){if(e.length===0)return[];let t=new Map;for(let o of e){let i=NB(o),s=t.get(i);s||(s=[],t.set(i,s)),s.push(o)}let n=[],r=new Set;for(let o of e){let i=NB(o),s=t.get(i);s.length>=doe(o.toolName)?r.has(i)||(n.push({kind:"group",toolName:o.toolName,label:Je.has(o.toolName)?o.toolInput:"",entries:s}),r.add(i)):n.push(o)}return n}function vT(e){let t=e.entries.length,n=e.entries.filter(a=>a.result),r=n.filter(a=>a.result.isError),o=n.length,i;if(r.length>0){let a=o-r.length,l=[];a>0&&l.push(`${a} ok`),l.push(`${r.length} error${r.length===1?"":"s"}`),i=l.join(", ")}else o===t?i=`${t} done`:o===0?i=`${t} running`:i=`${o}/${t} done`;return Ur(e.toolName+e.label)+p.dim(` \xD7${t} \u2014 ${i}`)}function NB(e){return Je.has(e.toolName)?e.toolName+"::"+e.toolInput:e.toolName}function doe(e){return Je.has(e)?OB:$B}function BB(e,t,n,r){return e>0||t?cl([...n,!0],r):cl(n,r)}function UB(e,t){return!Je.has(e.toolName)||e.headerEmitted!==!0?!1:(t.get(e.toolUseId)??[]).every(r=>r.kind==="tool"&&UB(r,t))}function vh(e,t,n,r=ne(),o=[],i=Pn(),s){let a=cl(o,i),l=zd(a,i),c=e.filter(h=>h.kind==="text"),d=e.filter(h=>h.kind==="tool").filter(h=>!UB(h,t)),u=ST(d),m=qd(u,Gd),f=Sh(m,i);for(let{sibling:h,connector:y}of f){let b=p.dim(y),w=y===i.lastConnector;if(h.kind==="overflow")n.push(Me(l+b+p.dim(h.text),r));else if(h.kind==="group")n.push(Me(l+b+vT(h),r));else if(h.kind==="resultSummary")n.push(Me(l+b+h.summary,r));else{let S=h,k=t.get(S.toolUseId);if(Je.has(S.toolName)&&k&&k.length>0){S.headerEmitted?n.push(Me(l+b,r)):n.push(Me(l+b+S.prefix,r));let T=s??w;if(vh(k,t,n,r,[...o,T],i,w),S.thinkingTail){let C=zd(cl([...o,T],i),i);n.push(Me(C+p.thinking("\u2307 "+De(S.thinkingTail)),r))}}else if(!(Je.has(S.toolName)&&S.headerEmitted))if(S.result){if(n.push(Me(l+b+S.prefix+p.dim(" \u2014 ")+Bo(S.result.isError)+" "+Hr(S.result,void 0,60,S.toolName),r)),S.diff&&!S.result.isError){let T=l+(w?i.spineClosed:p.dim(i.spine))+" ";for(let C of jr(S.diff,"overlay",T))n.push(Me(C,r))}}else{n.push(Me(l+b+S.prefix,r));let T=l+(w?i.spineClosed:p.dim(i.spine))+" ";S.thinkingTail?n.push(Me(T+p.thinking("\u2307 "+De(S.thinkingTail)),r)):n.push(Me(T+p.dim(DB(S.toolName)),r))}}}let g=BB(d.length,!1,o,i);for(let h of c)for(let y of kT(h.text,g,i))n.push(Me(y,r))}function Jd(e,t,n,r,o=ne(),i=[],s=Pn(),a){let l=cl(i,s),c=zd(l,s),d=[],u=e.filter(w=>w.kind==="text"),m=e.filter(w=>w.kind==="tool"),f=ST(m),g=qd(f,Gd),h=wT(g,r),y=Sh(h,s);for(let{sibling:w,connector:S}of y){let k=p.dim(S),T=S===s.lastConnector;if(w.kind==="overflow")d.push(Me(c+k+p.dim(w.text),o));else if(w.kind==="resultSummary")d.push(Me(c+k+w.summary,o));else if(w.kind==="group")d.push(Me(c+k+vT(w),o));else{let C=w,D=t.get(C.toolUseId);if(Je.has(C.toolName)&&D&&D.length>0){if(C.headerEmitted){let F=C.toolInput?`${C.toolName} ${De(C.toolInput)}`:C.toolName;d.push(Me(c+k+p.dim("\u21B3 "+F),o))}else d.push(Me(c+k+C.prefix,o));let R=a??T;d.push(...Jd(D,t,n,void 0,o,[...i,R],s,T))}else if(C.result){if(d.push(Me(c+k+C.prefix+p.dim(" \u2014 ")+Bo(C.result.isError)+" "+Hr(C.result,n,60,C.toolName),o)),C.diff&&!C.result.isError){let R=c+(T?s.spineClosed:p.dim(s.spine))+" ";for(let F of jr(C.diff,"flush",R))d.push(Me(F,o))}}else d.push(Me(c+k+C.prefix,o))}}let b=BB(m.length,r!=null,i,s);for(let w of u)for(let S of kT(w.text,b,s))d.push(Me(S,o));return d}function jB(e){return e.agentResultSummary?p.dim(e.agentResultSummary)+ll(e.result):e.agentResultSummary}function Yd(e,t,n,r,o=[]){let i=Pn(),s=t.filter(h=>h.kind==="tool"),l=s.filter(h=>h.result).reduce((h,y)=>h+(y.result.lineCount??0),0),c=[];s.length>Gd&&(c.push($a(s.length)),l>0&&c.push(`${l} lines`));let d=p.dim(i.spine.repeat(o.length)),u=o,m=p.dim(i.turnRoot),f=c.length>0?d+m+e.prefix+p.dim(" \u2014 "+c.join(" \xB7 ")):d+m+e.prefix,g=Jd(t,n,r,jB(e),ne(),u,i);return[f,...g].join(`
1585
+ `)}constructor(t){this.stdout=t.stdout,this.stdin=t.stdin,this.onCancel=t.onCancel,this.onSoftStop=t.onSoftStop,this.onBackground=t.onBackground,this.onPauseInterrupt=t.onPauseInterrupt,this.onShiftTab=t.onShiftTab,this.onOpenEditor=t.onOpenEditor;let n=t.promptText;if(typeof n=="function")this.promptTextFn=n;else if(typeof n=="string")this.promptTextFn=()=>n;else{let r=" "+p.dim("\u23AF")+" ";this.promptTextFn=()=>r}this.history=t.history,this.autocompleteState=t.autocompleteState,this.formatInputBuffer=t.formatInputBuffer,this.scrollRegion=t.scrollRegion,this.spinnerController=new oh({captureMode:t.captureMode??!1,goblin:t.goblinSpinner??!1,onTick:()=>this.repaint()}),this.caretBlinkController=new ih({enabled:t.caretBlink??!1,captureMode:t.captureMode??!1,intervalMs:t.caretBlinkIntervalMs??530,onTick:()=>this.repaint()}),this.onSubmit=t.onSubmit,this.anchorRow=t.anchorRow,this.declaredAnchorRow=t.anchorRow,this.ghostEngine=t.suggest?.engine,this.ghostGetContext=t.suggest?.getContext}isArmed(){return this.armed}setAnchorRow(t){this.anchorRow=t,this.declaredAnchorRow=t}suspendInput(){yB(this)}resumeInput(){bB(this)}setOnSubmit(t){this.onSubmit=t??void 0}setOnCancel(t){this.onCancel=t??void 0}getOnCancel(){return this.onCancel}setOnRewindRequest(t){this.onRewindRequest=t??void 0}setOnOpenEditor(t){this.onOpenEditor=t??void 0}enterPickerMode(t){eB(this,t)}exitPickerMode(){tB(this)}repaintPicker(){nB(this)}setInputMode(t){this.flushPendingRepaint(),rB(this,t)}getInputMode(){return oB(this)}async arm(){return wB(this)}disarm(){SB(this)}setOverlay(t){t!==this.overlay&&(this.debugLog("setOverlay",{framesLen:t.length,anchorRow:this.anchorRow??null}),this.overlay=t,this.repaint())}setSpinner(t){this.stdout.isTTY&&this.spinnerController.set(t)}commitAbove(t){this.flushPendingRepaint(),YN(this,t)}clearCommittedBand(){Nd(this)}flushResizeGhostErase(){XN(this)}resetCommittedBand(){VN(this)}repositionCommittedBand(t,n,r){QN(this,t,n,r)}getBuffer(){return EN(this)}getPendingCount(){return this.pendingSubmissions.length}getAttachments(){return[...this.attachments]}get caretVisible(){return this.caretBlinkController.visible}renderInputLine(){return GN(this)}updateAutocomplete(){dh(this)}updateGhost(){jN(this)}renderDropdownRows(){return qN(this)}renderHintRow(){return zN(this)}repaint(){this.repaintCount++,this.pendingTrailingRepaint=!1,gh(this)}scheduleRepaint(){if(this.repaintCount++,!this.burstActive){this.burstActive=!0,this.pendingTrailingRepaint=!1,gh(this),queueMicrotask(()=>{this.burstActive=!1,this.flushPendingRepaint()});return}this.pendingTrailingRepaint=!0}flushPendingRepaint(){this.pendingTrailingRepaint&&(this.pendingTrailingRepaint=!1,this.armed&&gh(this))}clearScreen(){this.logUpdate?.resetGeometry?.(),this.stdout.write("\x1B[H\x1B[2J"),this.repaint()}resetState(){vB(this)}applyEdit(t){return cB(this,t)}prefillInput(t){this.applyEdit(J.seed(t))}applyDropdownSelection(){return HN(this)}applyGhostAccept(){return WN(this)}};K();import fT from"chalk";var Hre=/(?<=\s|^)(\/[A-Za-z][\w:-]*)(?=\s|$)/g,Wre=/(?<=\s|^)(@[~\w./-]*)(?=\s|$)/g,Kre=/\[Pasted text #[0-9a-f]+ \+\d+ (?:lines|chars)\]/g,kB={mint:p.mint};function Gre(e){let t=kB[e];if(t)return t;let n=e.lastIndexOf(":");if(n>=0){let r=e.slice(n+1),o=kB[r];if(o)return o}return null}var TB=null,EB=null,xB=null,RB=null,CB="";function No(e,t){if(fT.level===0)return e;let n=t.version?.(),r=n!==void 0;if(r&&RB===t&&TB===e&&EB===fT.level&&xB===n)return CB;let s=e.replace(Hre,a=>{let l=a.slice(1);return t.has(l)?(Gre(l)??p.brand)(a):p.meta(a)}).replace(Wre,a=>p.fileRef(a)).replace(Kre,a=>p.meta(a));return r&&(RB=t,TB=e,EB=fT.level,xB=n,CB=s),s}K();import{pathToFileURL as qre}from"node:url";var zre="\x1B]8;;\x1B\\",Jre=new Set(["iterm2","wezterm","kitty","vscode","ghostty","windows-terminal","konsole","gnome-terminal","alacritty"]),Yre=5e3;function Vre(e=process.env,t=process.stdout.isTTY===!0){let n=e.FORCE_HYPERLINK;if(n!==void 0&&n.length>0)return n!=="0"&&n.toLowerCase()!=="false";if(!t||e.CI!==void 0&&e.CI.length>0)return!1;let r=Ui(e);if(!Jre.has(r))return!1;if(r==="gnome-terminal"&&e.VTE_VERSION!==void 0){let o=Number.parseInt(e.VTE_VERSION,10);if(!Number.isFinite(o)||o<Yre)return!1}return!0}var gT;function yh(){return gT===void 0&&(gT=Vre()),gT}function Xre(e,t){return`\x1B]8;;${t}\x1B\\${e}${zre}`}function bh(e,t){try{return Xre(e,qre(t).href)}catch{return e}}function Kd(e){let t=/[a-z][a-z0-9+.-]*:\/\/[^\s<>\"`]+/gi,n="",r=0;for(let o of e.matchAll(t)){let i=o[0]??"",s=o.index??r;n+=AB(e.slice(r,s)),n+=i,r=s+i.length}return n+=AB(e.slice(r)),n}function AB(e){let t=yh();return e.replace(/\/(?:[^/\s,)]+\/){2,}([^/\s,)]+)/g,(n,r)=>t?bh(r,n):r)}function Qre(e){let t=/^(\s*[("]?\s*)cd\s+\S+\s+&&\s+(?!cd\s)(.+)$/.exec(e);return t?(t[1]??"")+(t[2]??""):e}var _B=60;function hT(e,t){let n=e.trim().replace(/^\((.*)\)$/s,"$1"),r;try{r=JSON.parse(n)}catch{return e}if(!r||typeof r!="object")return e;let o=r;for(let i of t){let s=o[i];if(typeof s=="string"&&s.length>0){let a=De(s);if(a.length===0)continue;return`(${a.length>_B?ae(a,_B,"\u2026"):a})`}}return e}function IB(e,t){if(e==="bash"||e==="Bash")return Qre(t);if(e==="compose"||e==="Compose"){let n=t.trim().replace(/^\((.*)\)$/s,"$1");try{let r=JSON.parse(n);if(r&&typeof r=="object"){let o=Array.isArray(r.nodes)?r.nodes.length:void 0,i=Array.isArray(r.edges)?r.edges.length:0;if(o!==void 0){let s=`${o} node${o===1?"":"s"}`,a=i>0?`, ${i} edge${i===1?"":"s"}`:"";return`(${s}${a})`}}}catch{}}return e==="agent"||e==="Agent"?hT(t,["id_prefix","prompt"]):e==="Task"?hT(t,["description","prompt"]):e==="skill"||e==="Skill"?hT(t,["name","arguments"]):e==="ask_question"?Zre(t):t}function Zre(e){let t=e.trim().replace(/^\((.*)\)$/s,"$1");try{let n=JSON.parse(t);if(!n||typeof n!="object")return e;let r=n,o=typeof r.type=="string"?r.type:"text";if(o==="choice"||o==="multi_choice"){let i=r.choices,s=Array.isArray(i)?i.length:0;return s>0?`(${o}: ${s} option${s===1?"":"s"})`:`(${o})`}return`(${o})`}catch{return e}}function eoe(e){return e.replace(/[\r\n]+/g," ")}var toe={"(":")","{":"}","[":"]"};function PB(e,t,n="\u2026"){let r=e.charAt(0),o=toe[r];return!(o&&e.endsWith(o)&&e.length>=2)||X(e)<=t?ae(e,t,n):t<3?t>=2?r+o:ae(e,t,n):ae(e,t-1,n)+o}function Ur(e,t){let n=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/s.exec(e);if(n){let r=n[1],o=Kd(IB(r,n[2]??"")),i=tr(r),{color:s,glyph:a}=Ha(r),l=lv(i),c=l?` [${l}]`:"";if(t!==void 0){let u=(a+" ").length+r.length+c.length,m=Math.max(1,t-u);o=PB(o,m)}o=eoe(o);let d=s(a+" ")+s.bold(r)+p.toolArg(o);return l?d+p.dim(c):d}return p.chrome("\u25CF ")+p.toolArg(e)}K();var MB=8,wh=30;function noe(){let e=v.AFK_DIFF_LINES;if(e===void 0)return wh;let t=e.trim();if(!/^\d+$/.test(t))return wh;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:wh}function roe(){let e=v.AFK_SHOW_DIFFS;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function ooe(e){let t=p.diffAdd(`+${e.addedLines}`),n=p.diffRemove(`-${e.removedLines}`),r=e.hunks.length,o=p.dim(`across ${r} hunk${r===1?"":"s"}`);return`${t} ${n} ${o}`}var ioe=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;function soe(e){let t=Ie(e.text).replace(ioe,"");return e.kind==="+"?p.diffAdd("+ "+t):e.kind==="-"?p.diffRemove("- "+t):p.dim(" "+t)}var bT=new WeakMap;function jr(e,t,n){if(roe())return[];if(e.hunks.length===0)return[];let r=t==="overlay"?MB:noe(),o=t+"|"+n+"|"+r,i=bT.get(e);if(i!==void 0){let f=i.get(o);if(f!==void 0)return f}let s=[];s.push(n+ooe(e));let a=[];for(let f of e.hunks){let g=`@@ -${f.oldStart},${f.oldLines} +${f.newStart},${f.newLines} @@`;a.push({kind:"header",text:p.diffHunk(g)});for(let h of f.lines)a.push({kind:"body",text:soe(h)})}if(r===0){for(let f of a)s.push(n+f.text);return yT(e,o,s),s}let l=0;for(let f of a)f.kind==="body"&&l++;if(l<=r){for(let f of a)s.push(n+f.text);return yT(e,o,s),s}let c=0;for(let f of a)f.kind==="header"?s.push(n+f.text):c<r&&(s.push(n+f.text),c++);let d=l-r,u=`line${d===1?"":"s"}`,m=t==="flush"?" (set AFK_DIFF_LINES=0 to expand)":"";return s.push(n+p.dim(`\u2026 +${d} more diff ${u}${m}`)),yT(e,o,s),s}function yT(e,t,n){let r=bT.get(e);r===void 0&&(r=new Map,bT.set(e,r)),r.set(t,n)}function Bo(e){return e?p.error("\u2717"):p.success("\u2713")}var Gd=3,OB=2,$B=3;function DB(e){switch(tr(e)){case"read":return"Reading\u2026";case"write":return"Writing\u2026";case"web":return"Fetching\u2026";case"shell":return"Running\u2026";default:return"Running\u2026"}}function aoe(e,t){return e?e==="grep"||e==="Grep"?t===1?"match":"matches":e==="glob"||e==="Glob"?t===1?"path":"paths":t===1?"line":"lines":t===1?"line":"lines"}function Hr(e,t,n=60,r){let o=e.isError?p.error:p.dim,i=t??v.HOME??"___NOHOME___";if(e.display!==void 0&&!e.isError)return o(e.display);if(e.persistedPath){let a=e.persistedPath.startsWith(i)?"~"+e.persistedPath.slice(i.length):e.persistedPath,l=yh()?bh(a,e.persistedPath):a;return o(`saved \u2192 ${l}`)}if(e.lineCount!==void 0&&e.lineCount>1)return o(`${e.lineCount} ${aoe(r,e.lineCount)}`);let s=e.content.length>n?e.content.slice(0,n-3)+"\u2026":e.content;return o(De(s))}function ll(e){return!e||typeof e.batchSize!="number"||typeof e.batchIndex!="number"||e.batchSize<=1?"":p.dim(` \u2225${e.batchIndex}/${e.batchSize}`)}K();function qd(e,t){if(e.length<=t)return e;let n=e.length-t,r=e.slice(0,n),o=e.slice(n),i=LB(r);return[{kind:"overflow",count:r.length,text:i},...o]}function loe(e,t){return t<=1||e.endsWith("s")||/(sh|ch|x|z)$/i.test(e)?e:e+"s"}var coe=5,FB=60;function LB(e){let t=new Map,n=0;for(let i of e)i.kind==="group"?(t.set(i.toolName,(t.get(i.toolName)??0)+i.entries.length),n+=i.entries.length):(t.set(i.toolName,(t.get(i.toolName)??0)+1),n+=1);if(n===0)return"";if(e.length>0&&e.every(i=>Je.has(i.toolName))&&new Set(e.map(i=>i.toolName)).size===1){let i=[],s=!1;for(let a of e){let c=(a.kind==="group"?a.label:a.toolInput).trim();if(!c.startsWith("(")||!c.endsWith(")")){s=!0;break}let d=c.slice(1,-1),u=De(d);if(!u){s=!0;break}let m=u.length>FB?u.slice(0,FB-1)+"\u2026":u,f=a.kind==="group"?a.entries.length:1;i.push({display:m,entries:f})}if(!s&&i.length>0){let a=i.slice(0,coe),l=a.map(({display:m,entries:f})=>f>1?`${m} \xD7${f}`:m),c=a.reduce((m,f)=>m+f.entries,0),d=n-c,u=l.join(", ")+(d>0?` (+${d})`:"");return`\u2026 +${n} more: ${u}`}}let o=[];for(let[i,s]of t)o.push(`${s} ${loe(i,s)}`);return`\u2026 +${n} (${o.join(", ")})`}function Sh(e,t=Pn()){return e.map((n,r)=>({sibling:n,connector:r===e.length-1?t.lastConnector:t.midConnector}))}function wT(e,t){return t?[...e,{kind:"resultSummary",summary:t}]:e}function ST(e){if(e.length===0)return[];let t=new Map;for(let o of e){let i=NB(o),s=t.get(i);s||(s=[],t.set(i,s)),s.push(o)}let n=[],r=new Set;for(let o of e){let i=NB(o),s=t.get(i);s.length>=doe(o.toolName)?r.has(i)||(n.push({kind:"group",toolName:o.toolName,label:Je.has(o.toolName)?o.toolInput:"",entries:s}),r.add(i)):n.push(o)}return n}function vT(e){let t=e.entries.length,n=e.entries.filter(a=>a.result),r=n.filter(a=>a.result.isError),o=n.length,i;if(r.length>0){let a=o-r.length,l=[];a>0&&l.push(`${a} ok`),l.push(`${r.length} error${r.length===1?"":"s"}`),i=l.join(", ")}else o===t?i=`${t} done`:o===0?i=`${t} running`:i=`${o}/${t} done`;return Ur(e.toolName+e.label)+p.dim(` \xD7${t} \u2014 ${i}`)}function NB(e){return Je.has(e.toolName)?e.toolName+"::"+e.toolInput:e.toolName}function doe(e){return Je.has(e)?OB:$B}function BB(e,t,n,r){return e>0||t?cl([...n,!0],r):cl(n,r)}function UB(e,t){return!Je.has(e.toolName)||e.headerEmitted!==!0?!1:(t.get(e.toolUseId)??[]).every(r=>r.kind==="tool"&&UB(r,t))}function vh(e,t,n,r=ne(),o=[],i=Pn(),s){let a=cl(o,i),l=zd(a,i),c=e.filter(h=>h.kind==="text"),d=e.filter(h=>h.kind==="tool").filter(h=>!UB(h,t)),u=ST(d),m=qd(u,Gd),f=Sh(m,i);for(let{sibling:h,connector:y}of f){let b=p.dim(y),w=y===i.lastConnector;if(h.kind==="overflow")n.push(Me(l+b+p.dim(h.text),r));else if(h.kind==="group")n.push(Me(l+b+vT(h),r));else if(h.kind==="resultSummary")n.push(Me(l+b+h.summary,r));else{let S=h,k=t.get(S.toolUseId);if(Je.has(S.toolName)&&k&&k.length>0){S.headerEmitted?n.push(Me(l+b,r)):n.push(Me(l+b+S.prefix,r));let T=s??w;if(vh(k,t,n,r,[...o,T],i,w),S.thinkingTail){let C=zd(cl([...o,T],i),i);n.push(Me(C+p.thinking("\u2307 "+De(S.thinkingTail)),r))}}else if(!(Je.has(S.toolName)&&S.headerEmitted))if(S.result){if(n.push(Me(l+b+S.prefix+p.dim(" \u2014 ")+Bo(S.result.isError)+" "+Hr(S.result,void 0,60,S.toolName),r)),S.diff&&!S.result.isError){let T=l+(w?i.spineClosed:p.dim(i.spine))+" ";for(let C of jr(S.diff,"overlay",T))n.push(Me(C,r))}}else{n.push(Me(l+b+S.prefix,r));let T=l+(w?i.spineClosed:p.dim(i.spine))+" ";S.thinkingTail?n.push(Me(T+p.thinking("\u2307 "+De(S.thinkingTail)),r)):n.push(Me(T+p.dim(DB(S.toolName)),r))}}}let g=BB(d.length,!1,o,i);for(let h of c)for(let y of kT(h.text,g,i))n.push(Me(y,r))}function Jd(e,t,n,r,o=ne(),i=[],s=Pn(),a){let l=cl(i,s),c=zd(l,s),d=[],u=e.filter(w=>w.kind==="text"),m=e.filter(w=>w.kind==="tool"),f=ST(m),g=qd(f,Gd),h=wT(g,r),y=Sh(h,s);for(let{sibling:w,connector:S}of y){let k=p.dim(S),T=S===s.lastConnector;if(w.kind==="overflow")d.push(Me(c+k+p.dim(w.text),o));else if(w.kind==="resultSummary")d.push(Me(c+k+w.summary,o));else if(w.kind==="group")d.push(Me(c+k+vT(w),o));else{let C=w,D=t.get(C.toolUseId);if(Je.has(C.toolName)&&D&&D.length>0){if(C.headerEmitted){let F=C.toolInput?`${C.toolName} ${De(C.toolInput)}`:C.toolName;d.push(Me(c+k+p.dim("\u21B3 "+F),o))}else d.push(Me(c+k+C.prefix,o));let R=a??T;d.push(...Jd(D,t,n,void 0,o,[...i,R],s,T))}else if(C.result){if(d.push(Me(c+k+C.prefix+p.dim(" \u2014 ")+Bo(C.result.isError)+" "+Hr(C.result,n,60,C.toolName),o)),C.diff&&!C.result.isError){let R=c+(T?s.spineClosed:p.dim(s.spine))+" ";for(let F of jr(C.diff,"flush",R))d.push(Me(F,o))}}else d.push(Me(c+k+C.prefix,o))}}let b=BB(m.length,r!=null,i,s);for(let w of u)for(let S of kT(w.text,b,s))d.push(Me(S,o));return d}function jB(e){return e.agentResultSummary?p.dim(e.agentResultSummary)+ll(e.result):e.agentResultSummary}function Yd(e,t,n,r,o=[]){let i=Pn(),s=t.filter(h=>h.kind==="tool"),l=s.filter(h=>h.result).reduce((h,y)=>h+(y.result.lineCount??0),0),c=[];s.length>Gd&&(c.push($a(s.length)),l>0&&c.push(`${l} lines`));let d=p.dim(i.spine.repeat(o.length)),u=o,m=p.dim(i.turnRoot),f=c.length>0?d+m+e.prefix+p.dim(" \u2014 "+c.join(" \xB7 ")):d+m+e.prefix,g=Jd(t,n,r,jB(e),ne(),u,i);return[f,...g].join(`
1586
1586
  `)}function TT(e,t=[]){let n=Pn(),r=p.dim(n.spine.repeat(t.length)),o=p.dim(n.turnRoot);return r+o+e.prefix}function Vd(e,t,n,r,o=[]){let i=Pn(),s=o;return Jd(t,n,r,jB(e),ne(),s,i)}function dl(e,t,n){let r=[],o=ne();for(let i of t){let s=e.get(i);if(s.length===1){let a=s[0];if(a.result){if(r.push(" "+a.prefix+p.dim(" \u2014 ")+Bo(a.result.isError)+" "+Hr(a.result,n,60,a.toolName)+ll(a.result)),a.diff&&!a.result.isError)for(let l of jr(a.diff,"flush"," "))r.push(Me(l,o))}else r.push(" "+a.prefix)}else{r.push(HB(i,s,n));let a=s.filter(c=>c.diff&&c.result&&!c.result.isError),l=a.length>1;for(let c of a){if(l){let d=De(c.toolInput),u=Kd(d).trim()||d.trim();r.push(" "+p.dim(`\u2500\u2500 ${u} \u2500\u2500`))}for(let d of jr(c.diff,"flush"," "))r.push(Me(d,o))}}}return r}function HB(e,t,n){let{color:r,glyph:o}=Ha(e),i=t.map(d=>Kd(De(d.toolInput)).trim()),s=r(o+" ")+r.bold(e)+p.dim(` \xD7${t.length}`)+" "+p.toolArg(i.join(", ")),a=t.filter(d=>d.result),l=a.filter(d=>d.result.isError);if(l.length>0){let d=a.length-l.length,m=a.filter(g=>!g.result.isError).map(g=>g.result.lineCount).filter(g=>g!==void 0).reduce((g,h)=>g+h,0),f=[];return m>0&&f.push(`${m} lines`),d>0&&f.push(`${d} ok`),f.push(p.error(`${l.length} error${l.length>1?"s":""}`))," "+s+p.dim(" \u2014 ")+f.join(p.dim(", "))}let c=a.map(d=>d.result?.lineCount).filter(d=>d!==void 0);if(c.length===a.length&&c.length>0){if(c.every(m=>m===c[0]))return" "+s+p.dim(` \u2014 ${c[0]} lines each`);let u=c.reduce((m,f)=>m+f,0);return" "+s+p.dim(` \u2014 ${u} lines total`)}if(a.length>0){let d=a.map(u=>Hr(u.result,n,60,u.toolName));return" "+s+p.dim(" \u2014 ")+d.join(p.dim(", "))}return" "+s}function Me(e,t){return ae(e,t)}var ET=Object.freeze({spine:"\u2502 ",spineClosed:" ",lead:" ",turnRoot:"\u25C9 ",midConnector:"\u251C\u2500 ",lastConnector:"\u2570\u2500 ",textPrefix:"\u2502 "}),uoe=Object.freeze({spine:"| ",spineClosed:" ",lead:" ",turnRoot:"o ",midConnector:"+- ",lastConnector:"\\- ",textPrefix:"| "}),mze=ET.midConnector,fze=ET.lastConnector;function Pn(){let e=v.AGENT_AFK_ASCII;return e&&/^(1|true|yes)$/i.test(e)?uoe:ET}function cl(e,t){let n="";for(let r of e)n+=r?t.spineClosed:t.spine;return n+=t.spine,n}function zd(e,t){let n="";for(let r=0;r<e.length;r+=2){let o=e.slice(r,r+2);n+=o===t.spine?p.dim(o):o}return n}function kT(e,t,n){if(!e||!e.trim())return[];let r=p.dim(n.textPrefix),o=Math.max(1,ne()-t.length-2-2),i=zd(t,n),s=[];for(let a of e.split(`
1587
1587
  `)){let l=Ak(a),c=pe(l,o);for(let d of c.split(`
1588
1588
  `))s.push(i+r+d)}return s}var WB=6,Xd=class{entries=new Map;order=[];agentIdStack=[];addStart(t,n,r){let o=Ie(r),i=Ur(n+o),s=this.agentIdStack.at(-1)??void 0,a={kind:"tool",toolUseId:t,toolName:n,toolInput:o,prefix:i,...s!==void 0?{agentContext:s}:{}};this.entries.set(t,a),this.order.push(t),wo.has(n)&&this.agentIdStack.push(t)}addStartWithAgentContext(t,n,r,o,i){let s=Ie(r),a=this.entries.get(t);if(a?.kind==="tool"){a.toolInput=s,a.prefix=Ur(n+s,i),o!==void 0&&(a.agentContext=o);return}let l=Ur(n+s,i),c={kind:"tool",toolUseId:t,toolName:n,toolInput:s,prefix:l,...o!==void 0?{agentContext:o}:{}};this.entries.set(t,c),this.order.push(t)}mergeAgentLabel(t,n,r){let o=this.entries.get(t);if(o?.kind!=="tool"||!wo.has(o.toolName)||o.toolName==="Agent")return!1;let s=`(${Ie(n)})`;return o.toolName="Agent",o.toolInput=s,o.prefix=Ur("Agent"+s,r),!0}setAgentContext(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(n===void 0?delete r.agentContext:r.agentContext=n)}setAgentResultSummary(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.agentResultSummary=n)}setThinkingTail(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(n===void 0?delete r.thinkingTail:r.thinkingTail=n)}addResult(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.result=n),this.agentIdStack.at(-1)===t&&this.agentIdStack.pop()}addDiff(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.diff=n)}upsertTextChild(t,n,r){let o=this.entries.get(t);if(o?.kind==="text"){o.text=r,o.agentContext=n;return}let i={kind:"text",toolUseId:t,text:r,agentContext:n};this.entries.set(t,i),this.order.push(t)}removeTextChildrenUnder(t){let n=[];for(let[r,o]of this.entries)o.kind==="text"&&o.agentContext===t&&n.push(r);for(let r of n)this.entries.delete(r);if(n.length>0){let r=new Set(n);this.order=this.order.filter(o=>!r.has(o))}}hasPending(){return this.entries.size>0}hasEntry(t){return this.entries.get(t)?.kind==="tool"}findLastSkillEntryId(){for(let t=this.order.length-1;t>=0;t--){let n=this.order[t],r=this.entries.get(n);if(r?.kind==="tool"&&Jc.has(r.toolName))return n}}peekTrailingCompletedRootToolName(){for(let t=this.order.length-1;t>=0;t--){let n=this.order[t],r=this.entries.get(n);if(!(!r||r.kind!=="tool")&&!r.agentContext)return r.result===void 0||Je.has(r.toolName)?void 0:r.toolName}}getOverlay(){let t=this.buildChildMap(),n=[],r=Pn(),o=ne(),i=u=>ae(u,o),s=[];for(let u of this.order){let m=this.entries.get(u);!m||m.kind!=="tool"||m.agentContext||s.push(m)}let a=s,l=0;if(s.length>WB){let u=s.filter(h=>!h.result),m=s.filter(h=>h.result),f=Math.max(0,WB-u.length),g=new Set(m.slice(-f));l=m.length-g.size,a=s.filter(h=>!h.result||g.has(h))}let d=a.some(u=>Je.has(u.toolName))?p.dim(r.turnRoot):" ";for(let u of a){let m=t.get(u.toolUseId);if(Je.has(u.toolName)&&m&&m.length>0)u.headerEmitted?n.push(i(p.dim(r.turnRoot))):n.push(i(p.dim(r.turnRoot)+u.prefix)),vh(m,t,n,o,void 0,r),u.thinkingTail&&n.push(i(p.dim(r.spine)+p.thinking("\u2307 "+De(u.thinkingTail))));else if(!(Je.has(u.toolName)&&u.headerEmitted))if(Je.has(u.toolName))u.result?n.push(i(p.dim(r.turnRoot)+u.prefix+p.dim(" \u2014 ")+Bo(u.result.isError)+" "+Hr(u.result,void 0,60,u.toolName)+ll(u.result))):n.push(i(p.dim(r.turnRoot)+u.prefix+p.dim(" \u2026"))),u.thinkingTail&&n.push(i(p.dim(r.spine)+p.thinking("\u2307 "+De(u.thinkingTail))));else if(u.result){if(n.push(i(d+u.prefix+p.dim(" \u2014 ")+Bo(u.result.isError)+" "+Hr(u.result,void 0,60,u.toolName)+ll(u.result))),u.diff&&!u.result.isError)for(let f of jr(u.diff,"overlay"," "))n.push(i(f))}else n.push(i(d+u.prefix+p.dim(" \u2026"))),u.thinkingTail&&n.push(i(p.dim(r.spine)+p.thinking("\u2307 "+De(u.thinkingTail))))}return l>0&&n.push(i(" "+p.dim(`\u2026 +${l} done`))),n.join(`
@@ -1752,7 +1752,7 @@ ${S}
1752
1752
  ${k}`})}return{fileBlocks:a,warnings:l}}async function S1(e,t,n,r,o="summary",i,s){let a=ZN(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),Xa(process.stdout,Rd(process.cwd(),!0));let l="",c=0,d=!1,u=!1,m=!1,f=!1,g,h=!1,y=!1,b={abort:null},w=0,S=3e3,k=[],T=new Map,C=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,D=()=>{let j=r.subagentControl;j?.hasPromotableForeground()&&j.promoteActiveForeground().then($=>{for(let B of $)(i??{fn:console.log}).fn(p.dim(` \u2192 subagent backgrounded as ${B.jobId}: ${B.label}`))}).catch(()=>{})},R=r.getCompositor?r.getCompositor():null,F=()=>new gl({out:hl(i),thinkingMode:o,...C?{activeSkillName:C}:{},onCancel:()=>{t.interrupt().catch(j=>{We()&&console.error(" "+p.error("session.interrupt() failed:"),j)})},...r.subagentControl?{onBackground:D}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...R?{compositor:R}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),A=F(),O=async()=>{if(!m){m=!0;try{await A.dispose()}catch{}}},U=async()=>{await A.arm();let j=A.getCompositor();if(i&&j){let $=j;i.fn=B=>$.commitAbove(B),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(j),r.setInterruptNotifier?.($=>A.setInterrupting($)),r.rearmStatus?.()};try{R?R.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{h=!0,A.setSoftStopping(!0),t.interrupt().catch(M=>{We()&&console.error(" "+p.error("soft-stop session.interrupt() failed:"),M)});let _=r.subagentControl;_?.hasActiveForeground()&&_.cancelActiveForeground().catch(M=>{We()&&console.error(" "+p.error("soft-stop cancelActiveForeground() failed:"),M)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{y=!0,t.interrupt().catch(_=>{We()&&console.error(" "+p.error("pause-interrupt session.interrupt() failed:"),_)})}),await U(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(D);let{fileBlocks:j,warnings:$}=w1(e.text,{rootDir:process.cwd()});for(let _ of $)(i??{fn:console.log}).fn(p.dim(` @-file: ${_}`));let B=j.length>0||e.attachments.length>0?y1(e.text,e.attachments,void 0,j):e.text,P=t.sendMessageStream(B);if(await Us((_,M)=>{A.process(_,M)},async()=>{for await(let _ of P){if(h||y)break;if(_.type==="chunk"&&_.chunk.type==="content"?(l+=_.chunk.content,d=!0):_.type==="message"&&!d&&(l=_.message.content),_.type==="stream_retry"&&(l=l.slice(0,c)),_.type==="chunk"&&_.chunk.type==="tool_use_detail"){let M=_.chunk,I={toolName:M.toolName,toolUseId:M.toolUseId,input:M.toolInput,...M.toolInputRaw!==void 0&&{inputRaw:M.toolInputRaw}};T.set(M.toolUseId,I),k.push(I)}else if(_.type==="chunk"&&_.chunk.type==="tool_result"){let M=_.chunk;c=l.length;let I=T.get(M.toolUseId);if(I&&(I.result=M.content,I.isError=M.isError,T.delete(M.toolUseId)),r.onContextProgress){let H=Date.now();if(H-w>=S){w=H;try{let G=r.onContextProgress();G instanceof Promise&&await G}catch(G){We()&&console.error(" "+p.error("onContextProgress (status refresh) failed:"),G)}}}}if(_.type==="paused"){if(r.setPausedState?.(!0),await O(),R&&_.autoResume===!0){let M=new AbortController;b.abort=M;let I=_.resetsAt?_.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,H=I?`Keep waiting \u2014 auto-resumes at ${I}`:"Keep waiting \u2014 auto-resume in progress",G="Switch model / provider (type /model after)",Q="Stop waiting",ee=[p.warning(" \u23F3 Usage limit reached.")+(I?p.dim(` Auto-resumes at ${I}.`):""),p.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];lr(R,{header:ee,options:[H,G,Q],signal:M.signal,initialIndex:0}).then(ie=>{if(b.abort=null,!ie)return;let z=ie[0];z===void 0||z===H||(y=!0,z===G&&(i??{fn:console.log}).fn(p.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(fe=>{We()&&console.error(" "+p.error("picker pause-interrupt session.interrupt() failed:"),fe)}))}).catch(ie=>{We()&&console.error(" "+p.error("picker promise rejected:"),ie)})}else(i??{fn:console.log}).fn(LR({reason:_.reason,..._.resetsAt!==void 0?{resetsAt:_.resetsAt}:{},..._.accountId!==void 0?{accountId:_.accountId}:{},..._.autoResume!==void 0?{autoResume:_.autoResume}:{}}));continue}if(_.type==="resumed"){r.setPausedState?.(!1),b.abort?.abort(),b.abort=null;let M=_.hotSwapped&&_.accountId?`\u25B6 Resumed on ${_.accountId}`:"\u25B6 Resumed";l="",c=0,d=!1,k.length=0,T.clear(),f=!1,g=void 0,u=!1,A=F(),m=!1,await U(),(i??{fn:console.log}).fn(p.success(M));continue}if(_.type==="error"){await O(),ks(hs(_.error)),u=!0;continue}A.process(_),_.type==="done"&&(f=!0,g=_.metadata)}}),await O(),h){let _=i?i.fn:console.log,M=R?R.getPendingCount():0,I=M>0?` \xB7 ${M} queued`:"";_(p.warning(`\u23F8 Stopped${I} \u2014 work so far kept.`)+p.dim(" Send a message to continue.")),_("")}if(y){let _=i?i.fn:console.log;_(p.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),_("")}if(f&&!h&&!y){Pi(n,a,l,g,k),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),Va(process.stdout),WF(process.stdout,"afk: turn complete");let _=I=>{i?i.fn(I):console.log(I)},M=fy(l);if(M){_(h1(M)),_("");let I=mL(k);if(r.onTerminalState)try{r.onTerminalState(M,{doneHasCorroboratingEvidence:I})}catch{}if(n.permissionMode==="autonomous"){let H=M.kind==="done"&&mc().verifyDone===!0&&!I;gL(M,void 0,{unverified:H})}}if(Mle(g,n,_),r.onAfterTurn){let I=r.onAfterTurn();I instanceof Promise&&await I.catch(()=>{})}}}catch(j){await O(),u||ks(hs(j))}finally{await O(),Xa(process.stdout,Rd(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),b.abort?.abort(),b.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function Ple(e,t){let n=Math.round(e*100),r=de(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${de(o)} tok \u2014 model output may be silently truncated`}}return e>=.95?{tier:"near",text:` context ${n}% used of ${r} \u2014 near limit; output may soon truncate (consider /clear or a fresh session)`}:e>=.8?{tier:"caution",text:` context ${n}% used of ${r} \u2014 approaching limit`}:e>.5?{tier:"normal",text:` context ${n}% used of ${r}`}:{tier:"quiet",text:null}}function Mle(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(ve(e.durationMs)),e.totalCostUsd!==void 0&&r.push(st(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(de(o+i)+" tok"),r.length>0&&n(p.dim(" \u25E6 "+r.join(" \xB7 ")));let s=Kk(t),a=Gt(t.model),l=Ple(s,a);if(l.text!==null){let c=l.tier==="over"||l.tier==="near"?p.error:l.tier==="caution"?p.warning:p.dim;n(c(l.text))}n("")}var Ole=5e3,$le=3,Dle="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function Fle(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(p.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function v1(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,verdictLedger:d,shellPassthrough:u,bgResultNotifier:m}=s,f=null,g=[];e.session.current.waitForInitialization().then(async D=>{We()&&(f=Jg(D)),await eu(e.session.current),We()&&(g=nE())}).catch(()=>{});let h=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,y,b=!1,w=!1,S,k,T,C=0;for(m.onInjectable=()=>{C>=$le||!o.isAwaitingInput()||!o.bufferIsEmpty()||(C++,Va(process.stdout),h={text:Dle,attachments:[]},o.abortPendingRead())};;){if(f&&(e.replRenderer.writeLine(f),e.replRenderer.writeLine(""),f=null),g.length>0){for(let P of g)e.replRenderer.writeLine(P);e.replRenderer.writeLine(""),g=[]}let D=u.drainNotifications();for(let{job:P,result:N}of D){let _=N.errorReason===void 0?"\u2713":"\u2717",M=N.errorReason==="abort"?"killed":N.errorReason==="timeout"?"timed out":N.errorReason==="signal-killed"?"killed by signal":`exit ${N.exitCode??0}`,I=Math.max(0,Math.round(N.durationMs/100)/10);e.replRenderer.writeLine(p.dim(` ${_} [${P.id}] ${M} \xB7 ${I}s \xB7 `)+P.command)}let R=m.drainNotifications();for(let{job:P}of R){let N=P.status==="completed"?"\u2713":P.status==="failed"?"\u2717":"\u2298",_=P.endedAt!==void 0?Math.max(0,Math.round((P.endedAt-P.startedAt)/100)/10):0,M=P.label.length>60?`${P.label.slice(0,60)}\u2026`:P.label;e.replRenderer.writeLine(p.dim(` ${N} [${P.jobId}] subagent ${P.status} \xB7 ${_}s \xB7 `)+M)}let F=l.renderIfChanged(e.stats.sessionId);if(F.length>0){for(let P of F)e.replRenderer.writeLine(P);e.replRenderer.writeLine("")}let A,O;if(h===void 0){let P=await e.session.current.takePendingPlanExitSeed();P!==void 0&&(e.stats.permissionMode=P.mode,h={text:P.message,attachments:[]})}if(h!==void 0){let P=h;h=void 0;let N=Sl(e.stats.permissionMode),_=ji({buffer:P.text,promptText:N,isTTY:!!process.stdout.isTTY,attachmentSummary:il([...P.attachments])});e.replRenderer.writeLine(_),A=P.text.trim(),O=P.attachments}else{let P=y;y=void 0;let N=await o.readLine({promptFn:()=>Sl(e.stats.permissionMode),...P!==void 0?{initialBuffer:P}:{},onSigint:r,onShiftTab:()=>{dy(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});A=N.text.trim(),O=N.attachments}if(!A&&O.length===0)continue;if(A.startsWith("!")){let P=/^(0|false|off|no)$/i.test(v.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!P&&(b||(b=!0,e.replRenderer.writeLine(p.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await u.dispatch(A))){e.statusLine.rearm();continue}}let U=!1;if(A.startsWith("/")){let P=await tL(A,e.slashCtx,O);if(P.handled){if(P.result==="exit"){e.rl.close();return}if((A==="/clear"||A.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(p.dim(` transcript: ${t.path()}`)),d.reset(),S=void 0),P.result!==null&&typeof P.result=="object"&&"kind"in P.result&&P.result.kind==="submit"){h={text:P.result.message,attachments:O??[]},e.statusLine.rearm();continue}if(P.result!==null&&typeof P.result=="object"&&"kind"in P.result&&P.result.kind==="prefill"){y=P.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}U=!0}a.push(A),await Fle(e,A);let j=A;if(U){let P=Wk(A);if(P){let N=P.name.replace(/^\//,"").split(":").pop()??"";if(N&&QT(N)){let _={skillName:N,rawArgs:P.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},M=e.session.current.sessionId,I=Vi(M),H=Date.now();W(`[afk trace] preflight.start commandName=${N}`);let G=!1,Q=await Yi(_,{cwd:e.stats.cwd??process.cwd(),artifactDir:I},ee=>{We()&&e.replRenderer.writeLine(p.warning(`\u26A0 preflight(${N}) failed: `)+(ee instanceof Error?ee.message:String(ee)))});G=Q!==null,W(`[afk trace] preflight.end commandName=${N} durationMs=${Date.now()-H} success=${G}`),j=eE(Q?.manifestBlock,A)}}}let $=u.drainInjections();$.length>0&&(j=$+j);let B=m.drainInjections();if(B.length>0&&(j=B+j),S!==void 0&&(j=S+`
1753
1753
 
1754
1754
  `+j,S=void 0),e.hookRegistry)try{let P={event:"UserPromptSubmit",prompt:j,sessionId:e.stats.sessionId},N=await e.hookRegistry.dispatch(P);N.injectContext&&(j=N.injectContext+j)}catch(P){if(P instanceof he){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+(P.reason?p.dim(`: ${Cr(P.reason)}`):"")),e.statusLine.rearm();continue}if(P instanceof Wn){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+p.dim(`: handler timed out after ${P.timeoutMs}ms`)),e.statusLine.rearm();continue}throw P}if(k=void 0,T=void 0,await S1({text:j,attachments:O},e.session.current,e.stats,{setInFlight(P){n.turnInFlight=P},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(P){await t.appendUser(P)},async onTurnComplete(P,N){if(await t.appendTurn(P,N),e.stats.sessionId)try{Mo(e.stats)}catch(_){w||(w=!0,e.replRenderer.writeLine(p.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(_ instanceof Error?_.message:String(_))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(P,N)=>{d?.push(P),k=P.kind,T=N?.doneHasCorroboratingEvidence},setActiveCompositor:P=>{n.activeCompositor=P},setInterruptNotifier:P=>{n.notifyInterrupting=P},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:P=>o.setBackgroundHandler(P),setSoftStopHandler:i,setPausedState:P=>o.setPausedState(P),setPauseInterruptHandler:P=>o.setPauseInterruptHandler(P),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(ar(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:P=>c.repaint(P)}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(Sl(e.stats.permissionMode))),e.hookRegistry)try{let P=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...k!==void 0?{terminalState:k}:{},...T!==void 0?{doneHasCorroboratingEvidence:T}:{}},void 0,Ole);P.injectContext&&P.injectContext.trim().length>0&&(S=P.injectContext)}catch(P){if(P instanceof dt)throw P;P instanceof Wn?(W("[stop hook] handler timed out"),e.completionWriter.fn(p.dim(" [stop hook] timed out"))):P instanceof he?e.completionWriter.fn(p.dim(` [stop hook] blocked: ${Cr(P.reason??"no reason given")}`)):W("[stop hook] unexpected error: "+String(P))}}}function Lle(e,t){if(e!==void 0){let n=e.toLowerCase();return!(n==="0"||n==="false"||n==="off"||n==="no")}return typeof t=="boolean"?t:!0}async function k1(e,t,n,r){let o=await e1(),i=new cy({rl:e.rl,history:o,statusLine:e.statusLine}),s=Lle(v.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await i1(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar});a=g1(e,n),await v1(e,t,n,r,i,l,a,o)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.bgResultNotifier.dispose(),a?.loopStageBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await i.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}cc();Qs();import{execFile as Nle}from"node:child_process";import{dirname as Ble,isAbsolute as Ule,resolve as jle}from"node:path";import{promisify as Hle}from"node:util";var T1=Hle(Nle),Wle=3e3,Kle=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function Gle(){let t=(await T1("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=Ule(t)?t:jle(process.cwd(),t);return Ble(n)}async function E1(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await Gle()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),Wle)});try{let o=dn({execFile:T1,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),i=await Promise.race([o,r]);if(i==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let s=i;return s.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:s.candidates.filter(c=>Kle.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}op();cc();import{promises as qle}from"node:fs";import{dirname as zle,join as C1}from"node:path";import{randomBytes as Jle}from"node:crypto";var Yle=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
1755
- `),x1=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,EE=30,Vle=1024,Xle=8e3,Qle="haiku";async function Zle(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=rce(n,Vle),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??Xle),s=t.signal?oce([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await _s({token:t.token,model:t.model??Qle,system:Yle,user:r,maxTokens:32,signal:s})}catch(u){let m=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=ece(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=zle(t.worktreePath);return await tce(l,c)}function ece(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(x1.test(t)&&t.length<=EE)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>EE)break;o=s}return x1.test(o)?o:null}async function tce(e,t){if(!await nce(C1(t,e)))return e;let n=Jle(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,EE-5)}-${n}`}async function nce(e){try{return await qle.access(e),!0}catch{return!1}}function rce(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function oce(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function A1(e){let t,n,r=C1(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Zle(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${fp(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return R1(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return R1(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function R1(e,t){e&&e.setCwd(t),ice(t)}function ice(e){try{process.chdir(e)}catch{}}Ut();q();import{spawn as I1}from"child_process";import{existsSync as P1,mkdirSync as dce,readFileSync as M1,unlinkSync as _1,writeFileSync as O1}from"fs";import{get as uce}from"https";import{join as $1}from"path";import{readFileSync as sce}from"fs";import{dirname as ace,join as lce}from"path";import{fileURLToPath as cce}from"url";function mr(){try{return"5.75.0"}catch{}try{let e=ace(cce(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(sce(lce(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}K();var pce=64*1024,mce=10800*1e3,fce=800,gce=3600*1e3,hce="update-check.json",yce="pending-update.json";function xE(){return $1(ms(),hce)}function su(){return $1(ms(),yce)}function RE(){let e=ms();P1(e)||dce(e,{recursive:!0})}function D1(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),i=n(t).split(".").map(Number),s=Math.max(o.length,i.length);for(let a=0;a<s;a++){let l=o[a]??0,c=i[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function F1(){try{let e=M1(xE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function L1(){try{RE();let e=`
1755
+ `),x1=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,EE=30,Vle=1024,Xle=8e3,Qle="haiku";async function Zle(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=rce(n,Vle),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??Xle),s=t.signal?oce([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await _s({token:t.token,model:t.model??Qle,system:Yle,user:r,maxTokens:32,signal:s})}catch(u){let m=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=ece(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=zle(t.worktreePath);return await tce(l,c)}function ece(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(x1.test(t)&&t.length<=EE)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>EE)break;o=s}return x1.test(o)?o:null}async function tce(e,t){if(!await nce(C1(t,e)))return e;let n=Jle(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,EE-5)}-${n}`}async function nce(e){try{return await qle.access(e),!0}catch{return!1}}function rce(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function oce(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function A1(e){let t,n,r=C1(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Zle(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${fp(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return R1(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return R1(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function R1(e,t){e&&e.setCwd(t),ice(t)}function ice(e){try{process.chdir(e)}catch{}}Ut();q();import{spawn as I1}from"child_process";import{existsSync as P1,mkdirSync as dce,readFileSync as M1,unlinkSync as _1,writeFileSync as O1}from"fs";import{get as uce}from"https";import{join as $1}from"path";import{readFileSync as sce}from"fs";import{dirname as ace,join as lce}from"path";import{fileURLToPath as cce}from"url";function mr(){try{return"5.75.2"}catch{}try{let e=ace(cce(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(sce(lce(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}K();var pce=64*1024,mce=10800*1e3,fce=800,gce=3600*1e3,hce="update-check.json",yce="pending-update.json";function xE(){return $1(ms(),hce)}function su(){return $1(ms(),yce)}function RE(){let e=ms();P1(e)||dce(e,{recursive:!0})}function D1(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),i=n(t).split(".").map(Number),s=Math.max(o.length,i.length);for(let a=0;a<s;a++){let l=o[a]??0,c=i[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function F1(){try{let e=M1(xE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function L1(){try{RE();let e=`
1756
1756
  const https = require('https');
1757
1757
  const fs = require('fs');
1758
1758
  const url = 'https://registry.npmjs.org/agent-afk/latest';
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  var Dy=Object.defineProperty;var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var oc=(t,e)=>{for(var n in e)Dy(t,n,{get:e[n],enumerable:!0})};function Dr(t){return Or.find(e=>e.name===t)}function _i(t){return process.env[t]!==void 0}var Or,b,B=be(()=>{"use strict";Or=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_COMPACT_SHRINK_FRACTION",description:"Context-fullness fraction (0\u20131, exclusive) at/above which /compact and auto-compaction relax the keep-window so a short-but-full session (few turns, huge tool exchanges) can still be summarized instead of no-oping on turn count. Default 0.7 (see shared/compaction.ts DEFAULT_COMPACT_SHRINK_THRESHOLD).",type:"number",required:!1,example:"0.8",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. Falls back to provider default when unset.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS (or --max-output-tokens) to cap per-response output tokens; falls back to the model output ceiling when unset.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MAX_TOOL_USE_ITERATIONS",description:"Opt-in ceiling on tool-use rounds per turn for TOP-LEVEL (non-subagent) sessions, on both providers. Mirrors the maxToolUseIterations config key / max_tool_use_iterations tool param. Unset, non-numeric, or <=0 means unlimited (the default \u2014 zero behavior change): a top-level turn ends only when the model stops calling tools, the abort signal fires, the provider errors, or the dollar budget trips. A positive integer N makes top-level turns wind down gracefully after N tool rounds (one tools-stripped final round). An explicit config/CLI value wins over this env default. Does NOT affect subagent forks \u2014 they keep their own non-zero anti-hang default (SUBAGENT_DEFAULT_MAX_TOOL_USE_ITERATIONS) regardless of this var.",type:"number",required:!1,default:"0",example:"150",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MICROCOMPACT_KEEP_LAST",description:"Number of the most-recent tool_result blocks that tool-result microcompaction keeps intact regardless of size, so the agent does not lose the tool output it is actively reasoning over. Older results are the safe ones to trim. Default 4 (see shared/compaction.ts DEFAULT_MICROCOMPACT_KEEP_LAST). Values <= 0 protect nothing.",type:"number",required:!1,default:"4",example:"3",category:"model"},{name:"AFK_MICROCOMPACT_TOOL_RESULT_BYTES",description:"Byte threshold (tool_result content length) at/above which a tool_result block becomes a microcompaction candidate. When /compact and auto-compaction would otherwise no-op on a short-but-full session, microcompaction clears large/old tool_result CONTENT in place (largest first) \u2014 replacing it with a short placeholder, never removing the block \u2014 to reclaim context deterministically (no LLM call). Blocks below this size are left intact. Default 2048 (see shared/compaction.ts DEFAULT_MICROCOMPACT_TOOL_RESULT_BYTES).",type:"number",required:!1,default:"2048",example:"4096",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), fixed-identity aliases (opus, sonnet, haiku, fable), or full model IDs. Migration: AFK_MODEL=sonnet now pins the fixed Sonnet identity rather than following a rebound medium tier.",type:"string",required:!1,default:"medium",example:"claude-opus-4-5",category:"model"},{name:"AFK_MODEL_TTFB_TIMEOUT_MS",description:"Per-request time-to-first-token timeout (ms) for the anthropic-direct streaming loop. Bounds how long a single model call may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response runs unbounded, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. NOTE: a request whose FIRST token takes longer than the bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted, retried once, then surfaces as an error (raise this value or set 0 for such workloads); this trims the degrading-call tail instead of a silent ~10-min hang on the SDK default. Default 180000 (180s \u2248 2\xD7 the measured p99 ttfb). Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-4-8",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_THINKING_UI",description:"Default thinking-display mode for the interactive REPL: summary | live | digest | off. Display-only \u2014 controls how extended-thinking blocks render, never whether thinking runs (cost/latency unaffected). Overridden per-launch by --thinking-ui and mutable mid-session via /thinking. Precedence: --thinking-ui flag > this env > interactive.thinkingUi config > live. Invalid values are ignored.",type:"string",required:!1,default:"live",example:"digest",category:"misc"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to 'true' to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency. (The code checks the literal string 'true'.)",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless for daemon and subagent surfaces and headed for repl/interactive \u2014 so an operator can watch the agent work in REPL mode.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_READ_DENYLIST",description:"Colon-separated list of additional absolute paths the read_file/grep/glob/list_directory tools refuse to read. Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed.",type:"string",required:!1,example:"/Users/me/project/.env:/Users/me/secrets",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],b={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_COMPACT_SHRINK_FRACTION(){return process.env.AFK_COMPACT_SHRINK_FRACTION},get AFK_COMPANION_PRIMER(){return process.env.AFK_COMPANION_PRIMER},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MAX_TOOL_USE_ITERATIONS(){return process.env.AFK_MAX_TOOL_USE_ITERATIONS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MICROCOMPACT_KEEP_LAST(){return process.env.AFK_MICROCOMPACT_KEEP_LAST},get AFK_MICROCOMPACT_TOOL_RESULT_BYTES(){return process.env.AFK_MICROCOMPACT_TOOL_RESULT_BYTES},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_TTFB_TIMEOUT_MS(){return process.env.AFK_MODEL_TTFB_TIMEOUT_MS},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_SUBAGENT_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_TIMEOUT_MS},get AFK_SUBAGENT_IDLE_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_IDLE_TIMEOUT_MS},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_THINKING_UI(){return process.env.AFK_THINKING_UI},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_TAG_ONLY_CHAT_IDS(){return process.env.AFK_TELEGRAM_TAG_ONLY_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get COLORFGBG(){return process.env.COLORFGBG},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_READ_DENYLIST(){return process.env.AFK_READ_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get VISUAL(){return process.env.VISUAL},get EDITOR(){return process.env.EDITOR},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of Or){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(b,e.name);n&&Object.defineProperty(b,e.name,{...n,enumerable:!1})}})()});function Fy(){return b.AFK_DEBUG==="1"||b.DEBUG==="1"}function D(...t){Fy()&&console.log(...t)}var ee=be(()=>{"use strict";B()});import{existsSync as Oc,mkdirSync as rb,renameSync as ob,cpSync as sb,rmSync as ib}from"fs";import{join as W,dirname as Ni,basename as ab,isAbsolute as Fc}from"path";import{homedir as Lc}from"os";import{fileURLToPath as lb}from"url";function ae(){let t=b.AFK_HOME;if(t!==void 0&&t!==""){if(!Fc(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return W(Lc(),".afk")}function Ce(){return W(ae(),"agent-framework")}function qr(){return W(Ce(),"forge-telemetry.jsonl")}function Nc(){return W(Ce(),"briefs")}function Uc(){return W(Ce(),"facets")}function In(){return W(ae(),"skills")}function qt(){return W(ae(),"plugins")}function Bc(t=process.cwd()){return W(t,".afk")}function $c(t=process.cwd()){return W(Bc(t),"skills")}function jc(t=process.cwd()){return W(Bc(t),"plugins")}function Hc(t=process.cwd()){return W(t,".afk","plans")}function zr(){return W(qt(),".index.json")}function Ui(){return W(Cn(),"schedules.json")}function Kc(){let t=lb(import.meta.url),e=Ni(t);return W(e,"bundled-plugins")}function Cn(){return W(ae(),"config")}function ve(){let t=b.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Fc(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return W(ae(),"state")}function le(){return W(ve(),"sessions")}function Jr(){return W(ve(),"presence")}function Yr(){return W(ve(),"memory")}function Vr(){return W(ve(),"session-grants.jsonl")}function Wc(){return W(ae(),"farms")}function Gc(t){return W(Wc(),t)}function Xr(t){if(!cb.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function qc(t){return Xr(t),W(ve(),"witness",t)}function zc(t){return!t||t.startsWith("in-memory:")?null:ab(Ni(t))}function Jc(t="default"){return W(ve(),"daemon",`agent-afk@${t}`)}function Yc(){return W(ve(),"worktree-sweep.lock")}function Bi(){return W(Cn(),"afk.env")}function zt(){return W(Cn(),"afk.config.json")}function Qr(){return W(Lc(),".afk.config.json")}function db(){return W(ae(),"sessions")}function ub(t,e){if(t!==e&&Oc(t)&&!Oc(e))try{rb(Ni(e),{recursive:!0});try{ob(t,e)}catch(n){if(n.code==="EXDEV")try{sb(t,e,{recursive:!0}),ib(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
2
- `)}}}catch{}}function Vc(){ub(db(),le())}function $i(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>Dc)throw new Error(`Invalid browser profile: exceeds ${Dc} chars`);if(!pb.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function fb(){return W(ve(),"browser")}function mb(t){return $i(t),W(fb(),t)}function ji(t){return W(mb(t),"storageState.json")}function Pn(t){return typeof t=="string"&&t.length>0&&t.length<=hb&&gb.test(t)}function Mn(t){if(!Pn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return W(le(),t)}function Zr(t){return W(Mn(t),"events.jsonl")}function Xc(t){return W(Mn(t),"session.key")}var cb,pb,Dc,gb,hb,j=be(()=>{"use strict";B();cb=/^[a-zA-Z0-9_-]+$/;pb=/^[A-Za-z0-9_-]+$/,Dc=128;gb=/^[A-Za-z0-9_-]+$/,hb=128});import{readFileSync as Sk}from"node:fs";import{join as vk}from"path";function kk(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Lu(t,e){return kk(e).test(t)}function Ek(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(_k.has(e))return!0;if(Ak.has(e))return!1}return!1}function Nu(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function Tk(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 Uu(t){let e=t===void 0||t.trim()===""?"default":t.trim();return $i(e),e}function xk(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Rk(t){try{return Sk(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function Ik(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 typeof e.defaultProfile=="string"&&(n.defaultProfile=Uu(e.defaultProfile)),n}function Bu(t){let e=t?.env??b,n=t?.readFileSync??Rk,r=t?.surface??e.AGENT_SURFACE,o=Ek(e.AFK_BROWSER_HEADLESS,r),s=Nu(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Nu(e.AFK_BROWSER_BLOCKED_DOMAINS),a=xk(e.AFK_BROWSER_DOM_SNAPSHOTS),l=Tk(e.AFK_BROWSER_BACKEND),c=Uu(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():vk(Cn(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=Ik(d,m);return g.configPath=p,g}function ka(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(Lu(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Lu(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var _k,Ak,_a=be(()=>{"use strict";B();j();_k=new Set(["daemon","subagent","telegram","afk"]),Ak=new Set(["repl","interactive","cli"])});import Ct from"node:fs";import Fo from"node:path";import{randomBytes as Ck}from"node:crypto";import{chromium as Pk}from"playwright";function Mk(){try{return"5.75.0"}catch{}try{let t=Fo.resolve(import.meta.dirname,"../../../package.json"),e=Ct.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Ok,Lo,$u=be(()=>{"use strict";j();ee();Ok=Mk(),Lo=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=Pk.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 r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}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}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,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),await this.saveStorageState(this.config.defaultProfile,n.context),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/${Ok}`}}loadStorageState(e){let n=ji(e);try{if(!Ct.existsSync(n))return;let r=JSON.parse(Ct.readFileSync(n,"utf8"));return D("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){D("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=ji(e);if(!Ct.existsSync(r))return;let o=await n.storageState(),s=Fo.join(Fo.dirname(r),`.${Fo.basename(r)}.${process.pid}.${Ck(4).toString("hex")}.tmp`);Ct.writeFileSync(s,JSON.stringify(o),{mode:384}),Ct.chmodSync(s,384),Ct.renameSync(s,r),D("[browser/vault] saved session",{profile:e,file:r})}catch(r){D("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as Dk}from"crypto";function Aa(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of Fk)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function ju(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&Lk.test(t.label))}function Hu(t){return Dk("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Ku(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var Fk,Lk,Qn=be(()=>{"use strict";Fk=[{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}];Lk=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Nk}from"node:crypto";function Uk(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Bk(t,e,n){return`el_${Nk("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function $k(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Wu(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function qu(t,e){let n=t.role??"",r=t.name??"";Gu.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])qu(s,e)}async function jk(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,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},zu).catch(()=>[])}async function Hk(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},zu).catch(()=>[])}function Kk(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function No(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Kk(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=jk(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,y=!1;u!==null?(h=[],qu(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await Hk(t)).filter(H=>Gu.has(H.role??"")));let w=new Map;for(let x of p){let H=Wu(x.name),G=w.get(H);(!G||G.bbox.w===0&&x.bbox.w>0)&&w.set(H,x)}let _=h.map(x=>({ax:x,dom:w.get(Wu(x.name??""))})),S=r?_:_.filter(x=>x.dom?x.dom.bbox.w>0||x.dom.bbox.h>0:!0);S.sort((x,H)=>{let G=x.dom?.bbox.y??0,k=H.dom?.bbox.y??0;if(G!==k)return G-k;let A=x.dom?.bbox.x??0,I=H.dom?.bbox.x??0;return A-I}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=S.slice(0,n).map((x,H)=>{let G=x.ax.role??"generic",k=x.ax.name??"",A=Bk(G,k,H),I=x.dom?.bbox??{x:0,y:0,w:0,h:0},F=x.dom?.type??null,U=null;x.ax.value!==void 0&&x.ax.value!==null&&(U=String(x.ax.value)),x.ax.checked!==void 0&&(U=String(x.ax.checked)),ju({role:G,kind:F})&&(U="[redacted]");let O={disabled:x.ax.disabled??!1};x.ax.checked!==void 0&&(O.checked=x.ax.checked===!0||x.ax.checked==="mixed"),x.ax.selected!==void 0&&(O.selected=x.ax.selected),x.ax.expanded!==void 0&&(O.expanded=x.ax.expanded);let L;x.dom?.testId?L=`[data-testid="${x.dom.testId}"]`:x.dom?.id&&(L=`#${x.dom.id}`);let M={id:A,role:G,label:Uk(k),kind:F,value:U,state:O,bbox:I};return L!==void 0&&(M.selector=L),M}),C="idle";try{let x=await t.evaluate(()=>document.readyState);x==="loading"?C="loading":x==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let v=$k(f),P=`obs_${e.observationCounter.toString(36)}`,$=new Date().toISOString();return{observationId:P,url:m,title:g,textSummary:v,interactive:R,status:{httpStatus:e.httpStatus??null,loadingState:C,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:$}}var Gu,zu,Ju=be(()=>{"use strict";Qn();Gu=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);zu="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Yu(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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 Ea(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Yu(t,s)))).filter(o=>o!==null)}async function Wk(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Ta(t,e,n){switch(e.kind){case"element_id":return Gk(t,e,n);case"selector":return qk(t,e);case"semantic":return zk(t,e)}}async function Gk(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 Ea(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function qk(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 Ea(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function zk(t,e){return e.role!==void 0?Jk(t,e.text,e.role):Yk(t,e.text,e)}async function Jk(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 Ea(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Yk(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===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}),l>0&&d.push({loc:s,count:l});let u=await Wk(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 h=p[g];if(h===void 0)continue;let y=await Yu(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,_=0;for(let S=0;S<w.length;S++)_=_*31+w.charCodeAt(S)>>>0;f.push({...y,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Vu=be(()=>{"use strict"});import{randomBytes as Vk}from"crypto";import{mkdir as Xk,stat as Qk,writeFile as Zk}from"fs/promises";import{join as xa}from"path";import{gzip as e_}from"zlib";import{promisify as t_}from"util";function n_(t){return xa(qc(t),"browser")}function r_(t){return xa(n_(t),"screenshots")}function o_(){return new Date().toISOString().replace(/[:.]/g,"-")}function s_(){return Vk(3).toString("hex")}async function Ra(t,e,n){if(e.length>Xu)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Xu} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=r_(t);await Xk(r,{recursive:!0});let o=`${o_()}-${s_()}-${n}.png`,s=xa(r,o);await Zk(s,e);let{size:i}=await Qk(s);return{path:s,bytes:i}}var _L,Xu,Qu=be(()=>{"use strict";j();Qn();_L=t_(e_);Xu=5*1024*1024});var ep={};oc(ep,{PlaywrightProvider:()=>Ia});function Zu(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 Ia,tp=be(()=>{"use strict";$u();Ju();Vu();_a();Qn();Qu();Ia=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Lo(e)}async open(e){let n=ka(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(c){a=c}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await No(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}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 No(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 Ta(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Zu(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":{let g=Aa(e.value??"");await l.fill(e.value??"");break}case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.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(h){c=h}else c=g}let u=r.url();if(u!==s){let g=ka(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||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await No(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;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 Ta(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Zu(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 Ra(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 Ra(n,o,r);return s}catch{return null}}}});var Mt={};oc(Mt,{__resetBrowserRegistryForTests:()=>d_,browserProviderActive:()=>l_,closeBrowserProvider:()=>Ca,getBrowserProvider:()=>a_,peekBrowserProvider:()=>c_});function np(){Promise.resolve(Ca()).then(()=>{process.exit(130)})}function rp(){Promise.resolve(Ca()).then(()=>{process.exit(143)})}function op(){Oe=null}function i_(){Uo||(process.on("SIGINT",np),process.on("SIGTERM",rp),process.on("exit",op),Uo=!0)}function sp(){Uo&&(process.removeListener("SIGINT",np),process.removeListener("SIGTERM",rp),process.removeListener("exit",op),Uo=!1)}async function a_(t){return Oe!==null?Oe:(Pt!==null||(Pt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(tp(),ep)),n=Bu(t),r=new e(n);return i_(),Oe=r,Pt=null,r})()),Pt)}async function Ca(){if(Oe===null)return;let t=Oe;Oe=null,Pt=null,sp(),await t.shutdown()}function l_(){return Oe!==null}function c_(){return Oe}function d_(){Oe=null,Pt=null,sp()}var Oe,Pt,Uo,Ot=be(()=>{"use strict";_a();Oe=null,Pt=null,Uo=!1});ee();var pe=class extends Error{constructor(e){super(e),this.name="AbortError"}},fe=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Fr=class extends fe{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},z=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},Re=class extends Error{constructor(e){super(e),this.name="StreamIncompleteError"}},rt=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},$t=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}};ee();async function jt(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){D(`trace.emit tool_call failed: ${$e(n)}`)}}async function Be(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){D(`trace.emit hook_decision failed: ${$e(n)}`)}}async function wt(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){D(`trace.emit subagent_lifecycle failed: ${$e(n)}`)}}async function sc(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){D(`trace.emit budget failed: ${$e(n)}`)}}async function ic(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){D(`trace.emit abort failed: ${$e(n)}`)}}async function Lr(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){D(`trace.emit compaction failed: ${$e(n)}`)}}async function ac(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){D(`trace.emit closure failed: ${$e(n)}`)}}async function ne(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){D(`trace.emit browser_event failed: ${$e(n)}`)}}async function q(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){D(`trace.emit session_phase failed: ${$e(n)}`)}}function $e(t){return t instanceof Error?t.message:String(t)}import eh from"@anthropic-ai/sdk";var lc="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Ly="effort-2025-11-24",Ny="claude-cli/1.0.0 (external, cli)",Uy="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function Nr(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function En(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function we(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${lc},${Ly}`:lc,"x-app":"cli","User-Agent":Ny,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function cc(t){return t!=="oauth"?null:[{type:"text",text:Uy}]}import Hy from"@anthropic-ai/sdk";B();var Tn=["local","small","medium","large"],uc="claude-haiku-4-5-20251001",Ei="claude-sonnet-5",Ti="claude-opus-4-8",Ri="claude-fable-5",St={local:{id:""},small:{id:uc},medium:{id:Ei},large:{id:Ti}},pc="auto",Ii={opus:Ti,opus_1m:Ti,sonnet:Ei,sonnet_1m:Ei,haiku:uc,fable:Ri},Kt=[...Tn,...Object.keys(Ii)],xi;function Ci(t){xi=t}function Ai(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function Ur(t,e,n){let r={},o=Ai(t);o&&(r.id=o);let s=Ai(e);s&&(r.baseUrl=s);let i=Ai(n);return i&&(r.apiKey=i),r}function By(){return{local:Ur(b.AFK_MODEL_LOCAL,b.AFK_MODEL_LOCAL_BASE_URL,b.AFK_MODEL_LOCAL_API_KEY),small:Ur(b.AFK_MODEL_SMALL,b.AFK_MODEL_SMALL_BASE_URL,b.AFK_MODEL_SMALL_API_KEY),medium:Ur(b.AFK_MODEL_MEDIUM,b.AFK_MODEL_MEDIUM_BASE_URL,b.AFK_MODEL_MEDIUM_API_KEY),large:Ur(b.AFK_MODEL_LARGE,b.AFK_MODEL_LARGE_BASE_URL,b.AFK_MODEL_LARGE_API_KEY)}}function fc(t){let e=By(),n={};for(let r of Tn){let o=St[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},l=s?.name;l&&(a.name=l);let c=s?.provider;c&&(a.provider=c);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 Wt(t){return t||xi||fc()}function Gt(t,e=Wt()){let n=t.trim().toLowerCase();if(!(!n||n===pc)){for(let r of Tn){let o=e[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function vt(t,e=Wt()){if(t===void 0)return{id:""};let n=Gt(t,e);if(n)return e[n];let r=Ii[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function ot(t,e=Wt()){if(t!==void 0)return vt(t,e).id}function mc(t,e=Wt()){if(t===void 0)return;let n=Gt(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 gc(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Tn){let o=jy(n[r]);o&&(e[r]=o)}return e}function hc(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";if(e==="chatgpt-oauth"||e==="chatgpt")return"chatgpt-oauth"}function Ht(t){return typeof t=="string"?t.trim():""}function dc(t){return/[\x00-\x1f\x7f]/.test(t)}var $y=new Set([...Tn,pc,...Object.keys(Ii)]);function jy(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=Ht(e.id);if(!n)return;let r={id:n},o=Ht(e.name);o&&(r.name=o);let s=hc(e.provider);s&&(r.provider=s);let i=Ht(e.baseUrl);i&&(r.baseUrl=i);let a=Ht(e.apiKey);return a&&(r.apiKey=a),r}}function yc(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in e||"base_url"in e)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=Ht(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(dc(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=Ht(e.name);if(o){if(dc(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if($y.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=hc(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var Pi={opus:St.large.id,opus_1m:St.large.id,sonnet:St.medium.id,sonnet_1m:St.medium.id,haiku:St.small.id,fable:Ri};function Br(t){return t in Pi}function se(t){return ot(t)}import{randomUUID as bc}from"node:crypto";async function wc(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 l=Nr(e),c=En(e,l),d=a?a(c):new Hy(c),u=bc(),p=bc(),f=we(l,u,p),m=se(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let h=await d.messages.create({model:m,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),y=[];for(let _ of h.content)_.type==="text"&&y.push(_.text);let w=y.join("").trim();return w.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),w}import{execFileSync as Sc}from"child_process";import{existsSync as Ky,readFileSync as Wy,writeFileSync as Gy}from"fs";import{homedir as vc,userInfo as kc}from"os";import{join as _c}from"path";var qy="9d1c250a-e61b-44d9-88ed-5944d1962f5e",zy="https://platform.claude.com/v1/oauth/token",Jy=300*1e3;function Se(){let t=Ac();if(t===void 0)return;let e=Ec(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 Mi(){let t=Ac();if(t===void 0)return;let e=Ec(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Jy)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 Yy(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}:{}},Vy(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
2
+ `)}}}catch{}}function Vc(){ub(db(),le())}function $i(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>Dc)throw new Error(`Invalid browser profile: exceeds ${Dc} chars`);if(!pb.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function fb(){return W(ve(),"browser")}function mb(t){return $i(t),W(fb(),t)}function ji(t){return W(mb(t),"storageState.json")}function Pn(t){return typeof t=="string"&&t.length>0&&t.length<=hb&&gb.test(t)}function Mn(t){if(!Pn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return W(le(),t)}function Zr(t){return W(Mn(t),"events.jsonl")}function Xc(t){return W(Mn(t),"session.key")}var cb,pb,Dc,gb,hb,j=be(()=>{"use strict";B();cb=/^[a-zA-Z0-9_-]+$/;pb=/^[A-Za-z0-9_-]+$/,Dc=128;gb=/^[A-Za-z0-9_-]+$/,hb=128});import{readFileSync as Sk}from"node:fs";import{join as vk}from"path";function kk(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Lu(t,e){return kk(e).test(t)}function Ek(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(_k.has(e))return!0;if(Ak.has(e))return!1}return!1}function Nu(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function Tk(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 Uu(t){let e=t===void 0||t.trim()===""?"default":t.trim();return $i(e),e}function xk(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Rk(t){try{return Sk(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function Ik(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 typeof e.defaultProfile=="string"&&(n.defaultProfile=Uu(e.defaultProfile)),n}function Bu(t){let e=t?.env??b,n=t?.readFileSync??Rk,r=t?.surface??e.AGENT_SURFACE,o=Ek(e.AFK_BROWSER_HEADLESS,r),s=Nu(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Nu(e.AFK_BROWSER_BLOCKED_DOMAINS),a=xk(e.AFK_BROWSER_DOM_SNAPSHOTS),l=Tk(e.AFK_BROWSER_BACKEND),c=Uu(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():vk(Cn(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=Ik(d,m);return g.configPath=p,g}function ka(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(Lu(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Lu(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var _k,Ak,_a=be(()=>{"use strict";B();j();_k=new Set(["daemon","subagent","telegram","afk"]),Ak=new Set(["repl","interactive","cli"])});import Ct from"node:fs";import Fo from"node:path";import{randomBytes as Ck}from"node:crypto";import{chromium as Pk}from"playwright";function Mk(){try{return"5.75.2"}catch{}try{let t=Fo.resolve(import.meta.dirname,"../../../package.json"),e=Ct.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Ok,Lo,$u=be(()=>{"use strict";j();ee();Ok=Mk(),Lo=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=Pk.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 r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}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}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,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),await this.saveStorageState(this.config.defaultProfile,n.context),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/${Ok}`}}loadStorageState(e){let n=ji(e);try{if(!Ct.existsSync(n))return;let r=JSON.parse(Ct.readFileSync(n,"utf8"));return D("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){D("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=ji(e);if(!Ct.existsSync(r))return;let o=await n.storageState(),s=Fo.join(Fo.dirname(r),`.${Fo.basename(r)}.${process.pid}.${Ck(4).toString("hex")}.tmp`);Ct.writeFileSync(s,JSON.stringify(o),{mode:384}),Ct.chmodSync(s,384),Ct.renameSync(s,r),D("[browser/vault] saved session",{profile:e,file:r})}catch(r){D("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as Dk}from"crypto";function Aa(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of Fk)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function ju(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&Lk.test(t.label))}function Hu(t){return Dk("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Ku(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var Fk,Lk,Qn=be(()=>{"use strict";Fk=[{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}];Lk=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Nk}from"node:crypto";function Uk(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Bk(t,e,n){return`el_${Nk("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function $k(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Wu(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function qu(t,e){let n=t.role??"",r=t.name??"";Gu.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])qu(s,e)}async function jk(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,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},zu).catch(()=>[])}async function Hk(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},zu).catch(()=>[])}function Kk(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function No(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Kk(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=jk(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,y=!1;u!==null?(h=[],qu(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await Hk(t)).filter(H=>Gu.has(H.role??"")));let w=new Map;for(let x of p){let H=Wu(x.name),G=w.get(H);(!G||G.bbox.w===0&&x.bbox.w>0)&&w.set(H,x)}let _=h.map(x=>({ax:x,dom:w.get(Wu(x.name??""))})),S=r?_:_.filter(x=>x.dom?x.dom.bbox.w>0||x.dom.bbox.h>0:!0);S.sort((x,H)=>{let G=x.dom?.bbox.y??0,k=H.dom?.bbox.y??0;if(G!==k)return G-k;let A=x.dom?.bbox.x??0,I=H.dom?.bbox.x??0;return A-I}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=S.slice(0,n).map((x,H)=>{let G=x.ax.role??"generic",k=x.ax.name??"",A=Bk(G,k,H),I=x.dom?.bbox??{x:0,y:0,w:0,h:0},F=x.dom?.type??null,U=null;x.ax.value!==void 0&&x.ax.value!==null&&(U=String(x.ax.value)),x.ax.checked!==void 0&&(U=String(x.ax.checked)),ju({role:G,kind:F})&&(U="[redacted]");let O={disabled:x.ax.disabled??!1};x.ax.checked!==void 0&&(O.checked=x.ax.checked===!0||x.ax.checked==="mixed"),x.ax.selected!==void 0&&(O.selected=x.ax.selected),x.ax.expanded!==void 0&&(O.expanded=x.ax.expanded);let L;x.dom?.testId?L=`[data-testid="${x.dom.testId}"]`:x.dom?.id&&(L=`#${x.dom.id}`);let M={id:A,role:G,label:Uk(k),kind:F,value:U,state:O,bbox:I};return L!==void 0&&(M.selector=L),M}),C="idle";try{let x=await t.evaluate(()=>document.readyState);x==="loading"?C="loading":x==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let v=$k(f),P=`obs_${e.observationCounter.toString(36)}`,$=new Date().toISOString();return{observationId:P,url:m,title:g,textSummary:v,interactive:R,status:{httpStatus:e.httpStatus??null,loadingState:C,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:$}}var Gu,zu,Ju=be(()=>{"use strict";Qn();Gu=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);zu="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Yu(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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 Ea(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Yu(t,s)))).filter(o=>o!==null)}async function Wk(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Ta(t,e,n){switch(e.kind){case"element_id":return Gk(t,e,n);case"selector":return qk(t,e);case"semantic":return zk(t,e)}}async function Gk(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 Ea(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function qk(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 Ea(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function zk(t,e){return e.role!==void 0?Jk(t,e.text,e.role):Yk(t,e.text,e)}async function Jk(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 Ea(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Yk(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===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}),l>0&&d.push({loc:s,count:l});let u=await Wk(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 h=p[g];if(h===void 0)continue;let y=await Yu(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,_=0;for(let S=0;S<w.length;S++)_=_*31+w.charCodeAt(S)>>>0;f.push({...y,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Vu=be(()=>{"use strict"});import{randomBytes as Vk}from"crypto";import{mkdir as Xk,stat as Qk,writeFile as Zk}from"fs/promises";import{join as xa}from"path";import{gzip as e_}from"zlib";import{promisify as t_}from"util";function n_(t){return xa(qc(t),"browser")}function r_(t){return xa(n_(t),"screenshots")}function o_(){return new Date().toISOString().replace(/[:.]/g,"-")}function s_(){return Vk(3).toString("hex")}async function Ra(t,e,n){if(e.length>Xu)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Xu} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=r_(t);await Xk(r,{recursive:!0});let o=`${o_()}-${s_()}-${n}.png`,s=xa(r,o);await Zk(s,e);let{size:i}=await Qk(s);return{path:s,bytes:i}}var _L,Xu,Qu=be(()=>{"use strict";j();Qn();_L=t_(e_);Xu=5*1024*1024});var ep={};oc(ep,{PlaywrightProvider:()=>Ia});function Zu(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 Ia,tp=be(()=>{"use strict";$u();Ju();Vu();_a();Qn();Qu();Ia=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Lo(e)}async open(e){let n=ka(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(c){a=c}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await No(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}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 No(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 Ta(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Zu(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":{let g=Aa(e.value??"");await l.fill(e.value??"");break}case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.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(h){c=h}else c=g}let u=r.url();if(u!==s){let g=ka(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||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await No(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;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 Ta(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Zu(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 Ra(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 Ra(n,o,r);return s}catch{return null}}}});var Mt={};oc(Mt,{__resetBrowserRegistryForTests:()=>d_,browserProviderActive:()=>l_,closeBrowserProvider:()=>Ca,getBrowserProvider:()=>a_,peekBrowserProvider:()=>c_});function np(){Promise.resolve(Ca()).then(()=>{process.exit(130)})}function rp(){Promise.resolve(Ca()).then(()=>{process.exit(143)})}function op(){Oe=null}function i_(){Uo||(process.on("SIGINT",np),process.on("SIGTERM",rp),process.on("exit",op),Uo=!0)}function sp(){Uo&&(process.removeListener("SIGINT",np),process.removeListener("SIGTERM",rp),process.removeListener("exit",op),Uo=!1)}async function a_(t){return Oe!==null?Oe:(Pt!==null||(Pt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(tp(),ep)),n=Bu(t),r=new e(n);return i_(),Oe=r,Pt=null,r})()),Pt)}async function Ca(){if(Oe===null)return;let t=Oe;Oe=null,Pt=null,sp(),await t.shutdown()}function l_(){return Oe!==null}function c_(){return Oe}function d_(){Oe=null,Pt=null,sp()}var Oe,Pt,Uo,Ot=be(()=>{"use strict";_a();Oe=null,Pt=null,Uo=!1});ee();var pe=class extends Error{constructor(e){super(e),this.name="AbortError"}},fe=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Fr=class extends fe{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},z=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},Re=class extends Error{constructor(e){super(e),this.name="StreamIncompleteError"}},rt=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},$t=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}};ee();async function jt(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){D(`trace.emit tool_call failed: ${$e(n)}`)}}async function Be(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){D(`trace.emit hook_decision failed: ${$e(n)}`)}}async function wt(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){D(`trace.emit subagent_lifecycle failed: ${$e(n)}`)}}async function sc(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){D(`trace.emit budget failed: ${$e(n)}`)}}async function ic(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){D(`trace.emit abort failed: ${$e(n)}`)}}async function Lr(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){D(`trace.emit compaction failed: ${$e(n)}`)}}async function ac(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){D(`trace.emit closure failed: ${$e(n)}`)}}async function ne(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){D(`trace.emit browser_event failed: ${$e(n)}`)}}async function q(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){D(`trace.emit session_phase failed: ${$e(n)}`)}}function $e(t){return t instanceof Error?t.message:String(t)}import eh from"@anthropic-ai/sdk";var lc="claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,extended-cache-ttl-2025-04-11",Ly="effort-2025-11-24",Ny="claude-cli/1.0.0 (external, cli)",Uy="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function Nr(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function En(t,e,n,r){let o=e==="oauth"?{authToken:t}:{apiKey:t},s=typeof n=="string"&&n.length>0?{...o,baseURL:n}:o;return r?{...s,fetch:r}:s}function we(t,e,n,r){return t!=="oauth"?{}:{"anthropic-beta":r?`${lc},${Ly}`:lc,"x-app":"cli","User-Agent":Ny,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function cc(t){return t!=="oauth"?null:[{type:"text",text:Uy}]}import Hy from"@anthropic-ai/sdk";B();var Tn=["local","small","medium","large"],uc="claude-haiku-4-5-20251001",Ei="claude-sonnet-5",Ti="claude-opus-4-8",Ri="claude-fable-5",St={local:{id:""},small:{id:uc},medium:{id:Ei},large:{id:Ti}},pc="auto",Ii={opus:Ti,opus_1m:Ti,sonnet:Ei,sonnet_1m:Ei,haiku:uc,fable:Ri},Kt=[...Tn,...Object.keys(Ii)],xi;function Ci(t){xi=t}function Ai(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function Ur(t,e,n){let r={},o=Ai(t);o&&(r.id=o);let s=Ai(e);s&&(r.baseUrl=s);let i=Ai(n);return i&&(r.apiKey=i),r}function By(){return{local:Ur(b.AFK_MODEL_LOCAL,b.AFK_MODEL_LOCAL_BASE_URL,b.AFK_MODEL_LOCAL_API_KEY),small:Ur(b.AFK_MODEL_SMALL,b.AFK_MODEL_SMALL_BASE_URL,b.AFK_MODEL_SMALL_API_KEY),medium:Ur(b.AFK_MODEL_MEDIUM,b.AFK_MODEL_MEDIUM_BASE_URL,b.AFK_MODEL_MEDIUM_API_KEY),large:Ur(b.AFK_MODEL_LARGE,b.AFK_MODEL_LARGE_BASE_URL,b.AFK_MODEL_LARGE_API_KEY)}}function fc(t){let e=By(),n={};for(let r of Tn){let o=St[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},l=s?.name;l&&(a.name=l);let c=s?.provider;c&&(a.provider=c);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 Wt(t){return t||xi||fc()}function Gt(t,e=Wt()){let n=t.trim().toLowerCase();if(!(!n||n===pc)){for(let r of Tn){let o=e[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function vt(t,e=Wt()){if(t===void 0)return{id:""};let n=Gt(t,e);if(n)return e[n];let r=Ii[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function ot(t,e=Wt()){if(t!==void 0)return vt(t,e).id}function mc(t,e=Wt()){if(t===void 0)return;let n=Gt(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 gc(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Tn){let o=jy(n[r]);o&&(e[r]=o)}return e}function hc(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";if(e==="chatgpt-oauth"||e==="chatgpt")return"chatgpt-oauth"}function Ht(t){return typeof t=="string"?t.trim():""}function dc(t){return/[\x00-\x1f\x7f]/.test(t)}var $y=new Set([...Tn,pc,...Object.keys(Ii)]);function jy(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=Ht(e.id);if(!n)return;let r={id:n},o=Ht(e.name);o&&(r.name=o);let s=hc(e.provider);s&&(r.provider=s);let i=Ht(e.baseUrl);i&&(r.baseUrl=i);let a=Ht(e.apiKey);return a&&(r.apiKey=a),r}}function yc(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:'model binding must be an object with at least an "id"'};let e=t;if("apiKey"in e||"api_key"in e)return{ok:!1,error:"per-slot API keys are credentials; set AFK_MODEL_<TIER>_API_KEY via `afk config env set` instead of afk.config.json"};if("baseUrl"in e||"base_url"in e)return{ok:!1,error:"per-slot baseUrl is an endpoint-redirect credential vector; set AFK_MODEL_<TIER>_BASE_URL via `afk config env set` instead of afk.config.json"};let n=Ht(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(dc(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=Ht(e.name);if(o){if(dc(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if($y.has(o.trim().toLowerCase()))return{ok:!1,error:`model binding "name" must not shadow a built-in alias ("${o}")`};r.name=o}if(e.provider!==void 0&&e.provider!==""){let s=hc(e.provider);if(!s)return{ok:!1,error:'model binding "provider" must be one of: anthropic, openai (aliases: anthropic-direct, openai-compatible)'};r.provider=s}return{ok:!0,value:r}}var Pi={opus:St.large.id,opus_1m:St.large.id,sonnet:St.medium.id,sonnet_1m:St.medium.id,haiku:St.small.id,fable:Ri};function Br(t){return t in Pi}function se(t){return ot(t)}import{randomUUID as bc}from"node:crypto";async function wc(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 l=Nr(e),c=En(e,l),d=a?a(c):new Hy(c),u=bc(),p=bc(),f=we(l,u,p),m=se(n)??n,g={};Object.keys(f).length>0&&(g.headers=f),i&&(g.signal=i);let h=await d.messages.create({model:m,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),y=[];for(let _ of h.content)_.type==="text"&&y.push(_.text);let w=y.join("").trim();return w.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),w}import{execFileSync as Sc}from"child_process";import{existsSync as Ky,readFileSync as Wy,writeFileSync as Gy}from"fs";import{homedir as vc,userInfo as kc}from"os";import{join as _c}from"path";var qy="9d1c250a-e61b-44d9-88ed-5944d1962f5e",zy="https://platform.claude.com/v1/oauth/token",Jy=300*1e3;function Se(){let t=Ac();if(t===void 0)return;let e=Ec(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 Mi(){let t=Ac();if(t===void 0)return;let e=Ec(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+Jy)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 Yy(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}:{}},Vy(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
3
3
  `)}return n.accessToken}function Ac(){if(process.platform==="darwin")try{return Sc("security",["find-generic-password","-s","Claude Code-credentials","-a",kc().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=_c(vc(),".claude",".credentials.json");if(!Ky(t))return;try{return Wy(t,"utf-8")}catch{return}}}function Ec(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 Yy(t){try{let e=await fetch(zy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:qy})});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 xn(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 Vy(t){if(process.platform==="darwin")Sc("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",kc().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=_c(vc(),".claude",".credentials.json");Xy(e,t)}}function Xy(t,e){Gy(t,e,{encoding:"utf-8",mode:384})}function oe(t,e){if(t===null||typeof t!="object")return;let n=t.headers;if(n==null)return;if(typeof n.get=="function")return n.get(e)??void 0;if(typeof n=="object"){let o=n,s=o[e]??o[e.toUpperCase()];return typeof s=="string"?s:void 0}}function kt(t){let e=oe(t,"retry-after-ms");if(e!==void 0){let r=Number(e);if(Number.isFinite(r)&&r>=0)return r}let n=oe(t,"retry-after");if(n!==void 0){let r=Number(n);if(Number.isFinite(r)&&r>=0)return Math.round(r*1e3);let o=Date.parse(n);if(!Number.isNaN(o)){let s=o-Date.now();if(s>=0)return s}}}var Qy=300*1e3;var Zy=864e13;function Tc(t){if(!Number.isFinite(t)||t<=0)return;let e=t*1e3;if(!(e>Zy))return new Date(e)}function $r(t){if(!("status"in t))return null;let e=t.status;if(e===429){let n=t.message.split("|");if(n.length>=2){let l=Tc(parseInt(n[1].trim(),10));if(l!==void 0)return{kind:"oauth-limit",resetsAt:l}}let r=oe(t,"anthropic-ratelimit-unified-representative-claim"),o=oe(t,"anthropic-ratelimit-unified-overage-status"),s=oe(t,"anthropic-ratelimit-unified-status");if(r!==void 0||o!==void 0||s==="rejected"){let l=oe(t,"anthropic-ratelimit-unified-reset");if(l!==void 0){let c=Tc(Number(l));if(c!==void 0)return{kind:"oauth-limit",resetsAt:c}}return{kind:"oauth-limit-no-ts"}}if(oe(t,"anthropic-ratelimit-requests-remaining")!==void 0||oe(t,"anthropic-ratelimit-requests-limit")!==void 0||oe(t,"anthropic-ratelimit-requests-reset")!==void 0||oe(t,"anthropic-ratelimit-input-tokens-remaining")!==void 0||oe(t,"anthropic-ratelimit-input-tokens-limit")!==void 0||oe(t,"anthropic-ratelimit-input-tokens-reset")!==void 0||oe(t,"anthropic-ratelimit-output-tokens-remaining")!==void 0||oe(t,"anthropic-ratelimit-output-tokens-limit")!==void 0||oe(t,"anthropic-ratelimit-output-tokens-reset")!==void 0)return{kind:"rate-limit-transient",retryAfterMs:kt(t)};let a=kt(t);return a!==void 0&&a<=Qy?{kind:"rate-limit-transient",retryAfterMs:a}:{kind:"oauth-limit-no-ts"}}return e===400&&t.message.includes("invalid_request_error")&&t.message.includes("credit balance")?{kind:"credit-exhausted"}:null}async function xc(t){let{resetsAt:e,signal:n,readToken:r=Se}=t,o=r(),s=e.getTime()+3e4;return new Promise(i=>{let a,l=!1,c=p=>{l||(l=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",d),i(p))},d=()=>{c("aborted")},u=()=>n.aborted?(c("aborted"),!0):Date.now()>=s?(c("timer"),!0):r()!==o?(c("hot-swap"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),n.addEventListener("abort",d,{once:!0}))})}async function Rc(t){let{signal:e,readToken:n=Se,retryAfterMs:r}=t,o=n(),s=r!==void 0?Date.now()+r:void 0;return new Promise(i=>{let a,l=!1,c=p=>{l||(l=!0,a!==void 0&&clearInterval(a),e.removeEventListener("abort",d),i(p))},d=()=>{c("aborted")},u=()=>e.aborted?(c("aborted"),!0):n()!==o?(c("hot-swap"),!0):s!==void 0&&Date.now()>=s?(c("timer"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),e.addEventListener("abort",d,{once:!0}))})}var eb=new Set([429,503,529]);function Oi(t,e=fetch,n){return!t&&!n?e:async(r,o)=>{let s=await e(r,o);if(eb.has(s.status)){let i=kt({headers:s.headers});if(n)try{n({status:s.status,...i!==void 0?{retryAfterMs:i}:{}})}catch{}if(t){let a={status:s.status,reason:s.status===429?"rate-limit":"overloaded",source:"sdk-fetch"};i!==void 0&&(a.retryAfterMs=i),q(t,{phase:"rate_limit",...i!==void 0?{durationMs:i}:{},metadata:a})}}return s}}var jr=class{items=[];waiter=null;attempts=0;push(e){this.attempts+=1;let n={status:e.status,attempt:this.attempts,...e.retryAfterMs!==void 0?{retryAfterMs:e.retryAfterMs}:{}};this.items.push(n);let r=this.waiter;this.waiter=null,r&&r()}takeAll(){return this.items.length===0?[]:this.items.splice(0,this.items.length)}waitForItem(){return this.items.length>0?Promise.resolve():new Promise(e=>{this.waiter=e})}resetAttempts(){this.attempts=0}};import{randomUUID as Jg}from"node:crypto";function Ie(t){return t==="bypassPermissions"||t==="autonomous"}B();var tb="1h";function Hr(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=b.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 Kr(){let t=b.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":tb}function Ic(t,e){if(t.length===0)return t;let n=t[t.length-1],r=Pc(n,e);return r===n?t:[...t.slice(0,-1),r]}function Cc(t,e){if(t.length===0)return t;let n=t[t.length-1],r=nb(n,e);return r===n?t:[...t.slice(0,-1),r]}function nb(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=Pc(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function Pc(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var Wr=["## 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.","","Then, IF the task requires implementation (writing code or files), call the `exit_plan_mode` tool to present your plan. The user picks how to proceed (approve and implement, or keep planning). After calling it, END YOUR TURN \u2014 on approval you will receive a separate instruction to save the plan to a file and implement it. Do NOT use `ask_question` to ask whether the plan is OK; that is exactly what `exit_plan_mode` does \u2014 use `ask_question` only to resolve open requirement questions first. For research / read-only tasks that need no code changes, do NOT call `exit_plan_mode` \u2014 just answer.","","Manual fallbacks remain: the user can exit with `/plan off` (same save-and-implement handoff), and Shift+Tab advances the permission-mode ring without saving or implementing. Keep the plan concrete and complete enough to act on directly."].join(`
4
4
  `);function Di(t){return t!=="plan"?null:{type:"text",text:Wr}}var Gr=["## 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(`
5
5
  `);function Fi(t){return t!=="autonomous"?null:{type:"text",text:Gr}}function Rn(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 Mc(t,e){return e.has(t)}function Li(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()}}import{config as TM}from"dotenv";j();B();function eo(){return b.ANTHROPIC_API_KEY||b.CLAUDE_CODE_OAUTH_TOKEN||Se()}function Hi(){return b.OPENAI_API_KEY||b.CODEX_API_KEY||void 0}function Z(t){let e=V(t);return e==="openai-compatible"||e==="openai-codex"?Hi():eo()}B();import{readFileSync as kb,existsSync as _b}from"fs";import{join as Ab}from"path";j();B();import{execFile as yb}from"node:child_process";import{promisify as bb}from"node:util";B();j();B();var JM=bb(yb);var wb=/^[A-Za-z0-9_\-./]*$/,Qc=64;function Zc(t,e){if(t.length>Qc)throw new Error(`Invalid branch prefix from ${e}: length ${t.length} exceeds ${Qc}.`);if(!wb.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 ed(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.`)}j();import{existsSync as Dn,readdirSync as XM,readFileSync as td,realpathSync as QM,statSync as ZM}from"fs";import{homedir as nd}from"os";import{join as je}from"path";var rd=["claude-code","codex"],On=new Map,to={"claude-code":{label:"Claude Code",pluginRoots:t=>[je(t,".claude","plugins")],skillRoots:t=>[je(t,".claude","skills")],mcpConfigCandidates:t=>[je(t,".claude","mcp.json"),je(t,".claude",".mcp.json"),je(t,".claude","claude-code","mcp.json")],mcpFormat:"json",pluginEnabledState:t=>vb(t)},codex:{label:"Codex",pluginRoots:t=>[je(t,".codex","plugins")],skillRoots:t=>[je(t,".codex","skills")],mcpConfigCandidates:t=>[je(t,".codex","config.toml")],mcpFormat:"toml",pluginEnabledState:()=>On}},rO={"claude-code":to["claude-code"].label,codex:to.codex.label};function Ki(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of rd){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 Wi(){return[zt(),Qr()]}function Gi(t=Wi()){for(let e of t)if(Dn(e))try{let n=JSON.parse(td(e,"utf-8")),r=Ki(n.importFrom);if(r!==void 0)return r}catch{}}function qi(t,e=nd()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!t)return n;for(let r of rd){let o=t[r];if(!o)continue;let s=to[r];if(o.plugins)for(let i of s.pluginRoots(e))Dn(i)&&n.pluginRoots.push({dir:i,binary:r});if(o.skills){let i=`imported:${r}`;for(let a of s.skillRoots(e))Dn(a)&&n.skillRoots.push({dir:a,origin:i})}if(o.mcp){let i=Sb(s.mcpConfigCandidates(e));i&&n.mcpConfigs.push({source:i,format:s.mcpFormat})}}return n}function od(t,e=nd()){return to[t].pluginEnabledState(e)}function Sb(t){for(let e of t)if(Dn(e))return e;return null}function vb(t){let e=je(t,".claude","settings.json");if(!Dn(e))return On;let n;try{n=JSON.parse(td(e,"utf-8"))}catch{return On}if(!n||typeof n!="object")return On;let r=n.enabledPlugins;if(!r||typeof r!="object"||Array.isArray(r))return On;let o=new Map;for(let[s,i]of Object.entries(r))typeof i=="boolean"&&o.set(s,i);return o}var no;function sd(){if(no!==void 0)return no;let t=[Ab(process.cwd(),"afk.config.json"),zt(),Qr()],e=!1;for(let r of t)if(_b(r))try{let o=kb(r,"utf-8"),s=JSON.parse(o),i={},a=gc(s.models);if(typeof s.model=="string"&&s.model.length>0){let c=s.model.toLowerCase();i.model=Br(c)?c:s.model}if(typeof s.maxTokens=="number"&&(i.maxTokens=s.maxTokens),typeof s.temperature=="number"&&(i.temperature=s.temperature),typeof s.systemPrompt=="string"&&s.systemPrompt.length>0&&(i.systemPrompt=s.systemPrompt),typeof s.permissionMode=="string"){let c=s.permissionMode;(c==="default"||c==="plan"||c==="autonomous"||c==="bypassPermissions")&&(i.permissionMode=c)}if(s.autoRouting&&typeof s.autoRouting=="object"){let c={};typeof s.autoRouting.interactive=="boolean"&&(c.interactive=s.autoRouting.interactive),typeof s.autoRouting.chat=="boolean"&&(c.chat=s.autoRouting.chat),typeof s.autoRouting.telegram=="boolean"&&(c.telegram=s.autoRouting.telegram),typeof s.autoRouting.daemon=="boolean"&&(c.daemon=s.autoRouting.daemon),i.autoRouting=c}if(s.daemon&&typeof s.daemon=="object"){let c={};typeof s.daemon.task=="string"&&(c.task=s.daemon.task),typeof s.daemon.taskId=="string"&&(c.taskId=s.daemon.taskId);let d=s.daemon.worktreePrune;d&&typeof d=="object"&&(c.worktreePrune={enabled:typeof d.enabled=="boolean"?d.enabled:!0,cron:typeof d.cron=="string"?d.cron:"0 4 * * *",maxAgeDaysClean:typeof d.maxAgeDaysClean=="number"?d.maxAgeDaysClean:14,maxAgeDaysDirty:typeof d.maxAgeDaysDirty=="number"?d.maxAgeDaysDirty:30,scope:typeof d.scope=="string"?d.scope:"all"}),typeof s.daemon.verifyDone=="boolean"&&(c.verifyDone=s.daemon.verifyDone),i.daemon=c}if(s.telegram&&typeof s.telegram=="object"){let c={},d=s.telegram.notify;if(d&&typeof d=="object"){let u={};if((d.mode==="primary"||d.mode==="broadcast"||d.mode==="custom")&&(u.mode=d.mode),typeof d.primaryChatId=="number"&&Number.isFinite(d.primaryChatId)&&(u.primaryChatId=d.primaryChatId),Array.isArray(d.targets)){let p=d.targets.filter(f=>typeof f=="number"&&Number.isFinite(f));p.length>0&&(u.targets=p)}c.notify=u}if(typeof s.telegram.verifyDone=="boolean"&&(c.verifyDone=s.telegram.verifyDone),Array.isArray(s.telegram.tagOnlyChats)){let u=s.telegram.tagOnlyChats.filter(p=>typeof p=="number"&&Number.isFinite(p));u.length>0&&(c.tagOnlyChats=u)}if(s.telegram.chatAliases&&typeof s.telegram.chatAliases=="object"&&!Array.isArray(s.telegram.chatAliases)){let u={};for(let[p,f]of Object.entries(s.telegram.chatAliases))typeof f=="number"&&Number.isFinite(f)&&f!==0&&(u[p]=f);Object.keys(u).length>0&&(c.chatAliases=u)}i.telegram=c}if(s.updatePolicy&&["notify","auto","off"].includes(s.updatePolicy)&&(i.updatePolicy=s.updatePolicy),s.theme&&["dark","light","auto"].includes(s.theme)&&(i.theme=s.theme),typeof s.autoResumeOnUsageLimit=="boolean"&&(i.autoResumeOnUsageLimit=s.autoResumeOnUsageLimit),typeof s.enforceDoneEvidence=="boolean"&&(i.enforceDoneEvidence=s.enforceDoneEvidence),typeof s.bgSummaries=="boolean"&&(i.bgSummaries=s.bgSummaries),typeof s.maxSummaryCallsPerSession=="number"&&(i.maxSummaryCallsPerSession=Math.min(500,Math.max(1,s.maxSummaryCallsPerSession))),s.hooks!==null&&typeof s.hooks=="object"&&!Array.isArray(s.hooks)&&(i.hooks=s.hooks),typeof s.enableShellHooks=="boolean"&&(i.enableShellHooks=s.enableShellHooks),typeof s.enablePluginHooks=="boolean"&&(i.enablePluginHooks=s.enablePluginHooks),Wi().includes(r)){let c=Ki(s.importFrom);c!==void 0&&(i.importFrom=c)}if(s.interactive&&typeof s.interactive=="object"){let c={};typeof s.interactive.worktreeAutoname=="boolean"&&(c.worktreeAutoname=s.interactive.worktreeAutoname),typeof s.interactive.worktreeBranchPrefix=="string"&&(c.worktreeBranchPrefix=Zc(s.interactive.worktreeBranchPrefix,`${r}#/interactive/worktreeBranchPrefix`)),typeof s.interactive.worktreeBase=="string"&&s.interactive.worktreeBase.trim().length>0&&(ed(s.interactive.worktreeBase,`${r}#/interactive/worktreeBase`),c.worktreeBase=s.interactive.worktreeBase),typeof s.interactive.suggestGhost=="boolean"&&(c.suggestGhost=s.interactive.suggestGhost),(s.interactive.thinkingUi==="summary"||s.interactive.thinkingUi==="live"||s.interactive.thinkingUi==="digest"||s.interactive.thinkingUi==="off")&&(c.thinkingUi=s.interactive.thinkingUi),Object.keys(c).length>0&&(i.interactive=c)}let l={config:i,sourcePath:r,modelsPartial:a};return e||(no=l),l}catch(o){console.error(`Warning: Failed to parse ${r}:`,o),e=!0}let n={config:{},sourcePath:void 0,modelsPartial:{}};return e||(no=n),n}j();function zi(){return sd().config.telegram??{}}B();function Tb(t,e){return e!==void 0&&Number.isFinite(e)&&e!==0?e:t.find(r=>r>0)??t[0]}function xb(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=Tb(n,e.primaryChatId);return o!==void 0?[o]:[]}function id(t,e={}){if(typeof t=="number")return!Number.isFinite(t)||t===0?{ok:!1,reason:"invalid",message:`Invalid chat id: ${t}`}:{ok:!0,id:t};let n=t.trim();if(n.length===0)return{ok:!1,reason:"invalid",message:"Invalid chat: empty string"};let r=ad(n);if(r!==void 0)return{ok:!0,id:r};let o=Object.keys(e),s=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0;if(s!==void 0&&Number.isFinite(s)&&s!==0)return{ok:!0,id:s};let i=o.length>0?`Available aliases: ${o.join(", ")}.`:"No chat aliases are configured (set telegram.chatAliases in afk.config.json).";return{ok:!1,reason:"unknown-alias",message:`Unknown chat alias "${n}". ${i}`}}function ad(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 Rb(t){if(!t)return;let e=t.trim().toLowerCase();return e==="primary"||e==="broadcast"||e==="custom"?e:void 0}function Ib(){let t=zi().notify??{},e=t.mode??Rb(b.AFK_TELEGRAM_NOTIFY_MODE),n=t.primaryChatId??ad(b.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...e!==void 0?{mode:e}:{},...n!==void 0?{primaryChatId:n}:{},...t.targets!==void 0?{targets:t.targets}:{}}}function ro(){let t=Rn(b.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return xb(t,Ib())}function ld(){return zi().chatAliases??{}}function de(t,e=4096){if(t.length<=e)return[t];let n=[],r=t;for(;r.length>0;){if(r.length<=e){n.push(r);break}let o=e,s=r.lastIndexOf(`
package/dist/telegram.mjs CHANGED
@@ -855,7 +855,7 @@ Remedy: these paths are outside the fork's granted read roots. Re-dispatch with
855
855
  Note: this search ran in basic-regex (BRE) mode, where '|' is a literal pipe \u2014 not alternation. If you intended "A or B", retry with extended: true (extended regex / ERE). If you meant the literal character '|', this empty result stands.`),d({content:R});return}if(v===2){let R=Qn(g.trim());d({content:`grep error: ${R.content}`,isError:!0,...R.truncated?{truncated:!0}:{}});return}let E=rt(m.trimEnd()),x=Qn(E);d({content:x.content,...x.truncated?{truncated:!0}:{}})}),f.on("error",v=>{let E;if(p===void 0&&io(v))try{E=nr(v,process.cwd())}catch{E=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${v.message}`}else E=nr(v,p);d({content:`Failed to execute grep: ${E}`,isError:!0})})})}}var Sy,vy=b(()=>{"use strict";st();lt();dn();Id();Zn();Sy=$d()});import{promises as WP}from"fs";function Ud(t){return(e,n,r)=>GP(e,n,r,t)}var GP,ky,_y=b(()=>{"use strict";lt();GP=async(t,e,n,r)=>{if(!t||typeof t!="object")throw new Error("Invalid input: expected an object");let s=t.path;if(typeof s!="string")throw new Error("Invalid input: path must be a string");let i;try{i=Be(s,n,"read",r)}catch(a){return{content:a instanceof Error?a.message:String(a),isError:!0}}try{let a=await WP.readdir(i,{withFileTypes:!0}),l=a.filter(p=>p.isDirectory()).map(p=>`${p.name}/`),c=a.filter(p=>!p.isDirectory()).map(p=>p.name);l.sort(),c.sort();let d=[...l,...c];return d.length===0?{content:"(empty directory)"}:{content:d.join(`
856
856
  `)}}catch(a){if(a instanceof Error){let l=a;return l.code==="ENOENT"?{content:`Directory not found: ${i}`,isError:!0}:l.code==="ENOTDIR"?{content:`Not a directory: ${i}`,isError:!0}:l.code==="EACCES"?{content:`Permission denied: ${i}`,isError:!0}:{content:`Error listing directory: ${a.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}};ky=Ud()});function qP(t=Kn){return async(e,n)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let r=e,o=r.message,s=r.chat;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(s!==void 0&&typeof s!="number"&&typeof s!="string")return{content:"Invalid input: chat must be a number (chat id) or string (chat id or alias name)",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>Ay)return{content:`Invalid input: message exceeds Telegram's ${Ay}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let i=_.TELEGRAM_BOT_TOKEN;if(!i)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 a;if(s!==void 0){let c=Mg(s,Dg());if(!c.ok)return{content:c.message,isError:!0};let d=sn(_.AFK_TELEGRAM_ALLOWED_CHAT_IDS);if(!fg(c.id,d)){let u=[...d];return{content:`Refusing to send: chat ${c.id} is not in the allowlist (AFK_TELEGRAM_ALLOWED_CHAT_IDS). `+(u.length>0?`Allowed chat id(s): ${u.join(", ")}. `:"The allowlist is empty or unset. ")+"Add the chat id to the allowlist before targeting it.",isError:!0}}a=[c.id]}else a=ai();if(a.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 l=[];for(let c of a){let d=await t({token:i,chatId:c,text:o});d.ok||l.push(`chat ${c}: ${d.errorMessage??`HTTP ${d.status}`}`)}return l.length===a.length?{content:`Failed to send Telegram message to any chat. ${l.join("; ")}`,isError:!0}:l.length>0?{content:`Sent Telegram message to ${a.length-l.length}/${a.length} chat(s); ${l.length} failed: ${l.join("; ")}`}:{content:a.length===1?`Sent Telegram message to chat ${a[0]}.`:`Sent Telegram message to ${a.length} chats.`}}}var Ay,Ey,Ty=b(()=>{"use strict";G();Zr();Yc();Gr();Ay=4096;Ey=qP()});async function zP(){let[{JSDOM:t},{Readability:e},{default:n}]=await Promise.all([import("jsdom"),import("@mozilla/readability"),import("turndown")]),r=new n({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});return r.remove(["script","style","noscript","iframe"]),{JSDOM:t,Readability:e,turndown:r}}function JP(){return Bd===null&&(Bd=zP()),Bd}function xy(t){return t.replace(/\n{3,}/g,`
857
857
 
858
- `).trim()}function VP(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}async function Ry(t,e){let{JSDOM:n,Readability:r,turndown:o}=await JP(),i=new n(t,{url:e}).window.document,a=(i.title??"").trim(),l=(()=>{try{let p=i.cloneNode(!0);return new r(p).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let p=xy(o.turndown(l.content)),f=(l.title??"").trim()||a,m=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:p,textLength:m,usedFallback:!1}}let c=i.body,d=c?.innerHTML??"",u=xy(o.turndown(d));return{title:a,markdown:u,textLength:VP(c),usedFallback:!0}}var Bd,Cy=b(()=>{"use strict";Bd=null});function XP(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function Iy(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function QP(t,e){let n=t.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,e)}async function Ki(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??XP,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await t(e,n);if(!YP.has(u.status)||d===o)return u;let p=QP(u,i)??Iy(d,s,i);H("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let p=Iy(d,s,i);H("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var YP,Hd=b(()=>{"use strict";ie();YP=new Set([429,502,503,504])});import{readFileSync as ZP}from"node:fs";import{join as eM}from"path";function tM(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Py(t,e){return tM(e).test(t)}function oM(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(nM.has(e))return!0;if(rM.has(e))return!1}return!1}function My(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function sM(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 Oy(t){let e=t===void 0||t.trim()===""?"default":t.trim();return lc(e),e}function iM(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function aM(t){try{return ZP(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function lM(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 typeof e.defaultProfile=="string"&&(n.defaultProfile=Oy(e.defaultProfile)),n}function Dy(t){let e=t?.env??_,n=t?.readFileSync??aM,r=t?.surface??e.AGENT_SURFACE,o=oM(e.AFK_BROWSER_HEADLESS,r),s=My(e.AFK_BROWSER_ALLOWED_DOMAINS),i=My(e.AFK_BROWSER_BLOCKED_DOMAINS),a=iM(e.AFK_BROWSER_DOM_SNAPSHOTS),l=sM(e.AFK_BROWSER_BACKEND),c=Oy(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():eM(gt(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=lM(d,m);return g.configPath=p,g}function jd(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(Py(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Py(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var nM,rM,Kd=b(()=>{"use strict";G();q();nM=new Set(["daemon","subagent","telegram","afk"]),rM=new Set(["repl","interactive","cli"])});import Sn from"node:fs";import Wi from"node:path";import{randomBytes as cM}from"node:crypto";import{chromium as dM}from"playwright";function uM(){try{return"5.75.0"}catch{}try{let t=Wi.resolve(import.meta.dirname,"../../../package.json"),e=Sn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var pM,Gi,Fy=b(()=>{"use strict";q();ie();pM=uM(),Gi=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=dM.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 r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}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}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,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),await this.saveStorageState(this.config.defaultProfile,n.context),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/${pM}`}}loadStorageState(e){let n=cc(e);try{if(!Sn.existsSync(n))return;let r=JSON.parse(Sn.readFileSync(n,"utf8"));return H("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){H("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=cc(e);if(!Sn.existsSync(r))return;let o=await n.storageState(),s=Wi.join(Wi.dirname(r),`.${Wi.basename(r)}.${process.pid}.${cM(4).toString("hex")}.tmp`);Sn.writeFileSync(s,JSON.stringify(o),{mode:384}),Sn.chmodSync(s,384),Sn.renameSync(s,r),H("[browser/vault] saved session",{profile:e,file:r})}catch(r){H("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as fM}from"crypto";function Wd(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of mM)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Ly(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&gM.test(t.label))}function Ny(t){return fM("sha256").update(t,"utf8").digest("hex").slice(0,8)}function $y(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var mM,gM,uo=b(()=>{"use strict";mM=[{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}];gM=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as hM}from"node:crypto";function yM(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function bM(t,e,n){return`el_${hM("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function wM(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Uy(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Hy(t,e){let n=t.role??"",r=t.name??"";By.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Hy(s,e)}async function SM(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,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},jy).catch(()=>[])}async function vM(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},jy).catch(()=>[])}function kM(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function qi(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=kM(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=SM(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,w=!1;u!==null?(h=[],Hy(u,h)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,h=(await vM(t)).filter(B=>By.has(B.role??"")));let k=new Map;for(let P of p){let B=Uy(P.name),j=k.get(B);(!j||j.bbox.w===0&&P.bbox.w>0)&&k.set(B,P)}let A=h.map(P=>({ax:P,dom:k.get(Uy(P.name??""))})),v=r?A:A.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);v.sort((P,B)=>{let j=P.dom?.bbox.y??0,C=B.dom?.bbox.y??0;if(j!==C)return j-C;let M=P.dom?.bbox.x??0,F=B.dom?.bbox.x??0;return M-F}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=v.slice(0,n).map((P,B)=>{let j=P.ax.role??"generic",C=P.ax.name??"",M=bM(j,C,B),F=P.dom?.bbox??{x:0,y:0,w:0,h:0},D=P.dom?.type??null,O=null;P.ax.value!==void 0&&P.ax.value!==null&&(O=String(P.ax.value)),P.ax.checked!==void 0&&(O=String(P.ax.checked)),Ly({role:j,kind:D})&&(O="[redacted]");let U={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(U.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(U.selected=P.ax.selected),P.ax.expanded!==void 0&&(U.expanded=P.ax.expanded);let $;P.dom?.testId?$=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&($=`#${P.dom.id}`);let L={id:M,role:j,label:yM(C),kind:D,value:O,state:U,bbox:F};return $!==void 0&&(L.selector=$),L}),R="idle";try{let P=await t.evaluate(()=>document.readyState);P==="loading"?R="loading":P==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let S=wM(f),T=`obs_${e.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:T,url:m,title:g,textSummary:S,interactive:x,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:I}}var By,jy,Ky=b(()=>{"use strict";uo();By=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);jy="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Wy(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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 Gd(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Wy(t,s)))).filter(o=>o!==null)}async function _M(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function qd(t,e,n){switch(e.kind){case"element_id":return AM(t,e,n);case"selector":return EM(t,e);case"semantic":return TM(t,e)}}async function AM(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 Gd(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function EM(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 Gd(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function TM(t,e){return e.role!==void 0?xM(t,e.text,e.role):RM(t,e.text,e)}async function xM(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 Gd(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function RM(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===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}),l>0&&d.push({loc:s,count:l});let u=await _M(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 h=p[g];if(h===void 0)continue;let w=await Wy(h.locator,h.index);if(w!==null){let k=`${w.role}:${w.label}:${g}`,A=0;for(let v=0;v<k.length;v++)A=A*31+k.charCodeAt(v)>>>0;f.push({...w,id:`el_${A.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Gy=b(()=>{"use strict"});import{randomBytes as CM}from"crypto";import{mkdir as IM,stat as PM,writeFile as MM}from"fs/promises";import{join as zd}from"path";import{gzip as OM}from"zlib";import{promisify as DM}from"util";function FM(t){return zd(Ss(t),"browser")}function LM(t){return zd(FM(t),"screenshots")}function NM(){return new Date().toISOString().replace(/[:.]/g,"-")}function $M(){return CM(3).toString("hex")}async function Jd(t,e,n){if(e.length>qy)throw new Error(`writeScreenshotSidecar: buffer exceeds ${qy} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=LM(t);await IM(r,{recursive:!0});let o=`${NM()}-${$M()}-${n}.png`,s=zd(r,o);await MM(s,e);let{size:i}=await PM(s);return{path:s,bytes:i}}var AJ,qy,zy=b(()=>{"use strict";q();uo();AJ=DM(OM);qy=5*1024*1024});var Vy={};tc(Vy,{PlaywrightProvider:()=>Vd});function Jy(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 Vd,Yy=b(()=>{"use strict";Fy();Ky();Gy();Kd();uo();zy();Vd=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Gi(e)}async open(e){let n=jd(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(c){a=c}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await qi(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}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 qi(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 qd(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Jy(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":{let g=Wd(e.value??"");await l.fill(e.value??"");break}case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.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(h){c=h}else c=g}let u=r.url();if(u!==s){let g=jd(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||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await qi(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;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 qd(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Jy(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 Jd(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 Jd(n,o,r);return s}catch{return null}}}});var kn={};tc(kn,{__resetBrowserRegistryForTests:()=>KM,browserProviderActive:()=>HM,closeBrowserProvider:()=>Yd,getBrowserProvider:()=>BM,peekBrowserProvider:()=>jM});function Xy(){Promise.resolve(Yd()).then(()=>{process.exit(130)})}function Qy(){Promise.resolve(Yd()).then(()=>{process.exit(143)})}function Zy(){ct=null}function UM(){zi||(process.on("SIGINT",Xy),process.on("SIGTERM",Qy),process.on("exit",Zy),zi=!0)}function eb(){zi&&(process.removeListener("SIGINT",Xy),process.removeListener("SIGTERM",Qy),process.removeListener("exit",Zy),zi=!1)}async function BM(t){return ct!==null?ct:(vn!==null||(vn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Yy(),Vy)),n=Dy(t),r=new e(n);return UM(),ct=r,vn=null,r})()),vn)}async function Yd(){if(ct===null)return;let t=ct;ct=null,vn=null,eb(),await t.shutdown()}function HM(){return ct!==null}function jM(){return ct}function KM(){ct=null,vn=null,eb()}var ct,vn,zi,_n=b(()=>{"use strict";Kd();ct=null,vn=null,zi=!1});async function tb(t,e){try{return await Ry(t,e)}catch(n){return H("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function VM(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(_n(),kn));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function nb(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??VM,o=null,s=t,i=null,a=null;try{let c=await Ki(n,t,{headers:JM,redirect:"follow",signal:e.signal});i=c.status,s=c.url||t;let d=c.headers.get("content-type")??"";if(c.ok){if(zM.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 c.text();if(qM.test(d)&&!GM.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};if(o=await tb(u,s),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(c){if(e.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<200)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=await tb(c.html,c.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(e.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),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=c,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 GM,qM,zM,JM,rb=b(()=>{"use strict";Cy();Hd();ie();GM=/(text\/html|application\/xhtml\+xml)/i,qM=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,zM=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,JM={"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 QM(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(YM,{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),XM),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=Yn(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function ob(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?QM({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 sb(t,e){if(e.length===0)return`# Search results for "${t}"
858
+ `).trim()}function VP(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}async function Ry(t,e){let{JSDOM:n,Readability:r,turndown:o}=await JP(),i=new n(t,{url:e}).window.document,a=(i.title??"").trim(),l=(()=>{try{let p=i.cloneNode(!0);return new r(p).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let p=xy(o.turndown(l.content)),f=(l.title??"").trim()||a,m=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:p,textLength:m,usedFallback:!1}}let c=i.body,d=c?.innerHTML??"",u=xy(o.turndown(d));return{title:a,markdown:u,textLength:VP(c),usedFallback:!0}}var Bd,Cy=b(()=>{"use strict";Bd=null});function XP(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function Iy(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function QP(t,e){let n=t.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,e)}async function Ki(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??XP,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await t(e,n);if(!YP.has(u.status)||d===o)return u;let p=QP(u,i)??Iy(d,s,i);H("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let p=Iy(d,s,i);H("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var YP,Hd=b(()=>{"use strict";ie();YP=new Set([429,502,503,504])});import{readFileSync as ZP}from"node:fs";import{join as eM}from"path";function tM(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Py(t,e){return tM(e).test(t)}function oM(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(nM.has(e))return!0;if(rM.has(e))return!1}return!1}function My(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function sM(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 Oy(t){let e=t===void 0||t.trim()===""?"default":t.trim();return lc(e),e}function iM(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function aM(t){try{return ZP(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function lM(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 typeof e.defaultProfile=="string"&&(n.defaultProfile=Oy(e.defaultProfile)),n}function Dy(t){let e=t?.env??_,n=t?.readFileSync??aM,r=t?.surface??e.AGENT_SURFACE,o=oM(e.AFK_BROWSER_HEADLESS,r),s=My(e.AFK_BROWSER_ALLOWED_DOMAINS),i=My(e.AFK_BROWSER_BLOCKED_DOMAINS),a=iM(e.AFK_BROWSER_DOM_SNAPSHOTS),l=sM(e.AFK_BROWSER_BACKEND),c=Oy(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():eM(gt(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=lM(d,m);return g.configPath=p,g}function jd(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(Py(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Py(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var nM,rM,Kd=b(()=>{"use strict";G();q();nM=new Set(["daemon","subagent","telegram","afk"]),rM=new Set(["repl","interactive","cli"])});import Sn from"node:fs";import Wi from"node:path";import{randomBytes as cM}from"node:crypto";import{chromium as dM}from"playwright";function uM(){try{return"5.75.2"}catch{}try{let t=Wi.resolve(import.meta.dirname,"../../../package.json"),e=Sn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var pM,Gi,Fy=b(()=>{"use strict";q();ie();pM=uM(),Gi=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=dM.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 r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}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}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,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),await this.saveStorageState(this.config.defaultProfile,n.context),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/${pM}`}}loadStorageState(e){let n=cc(e);try{if(!Sn.existsSync(n))return;let r=JSON.parse(Sn.readFileSync(n,"utf8"));return H("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){H("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=cc(e);if(!Sn.existsSync(r))return;let o=await n.storageState(),s=Wi.join(Wi.dirname(r),`.${Wi.basename(r)}.${process.pid}.${cM(4).toString("hex")}.tmp`);Sn.writeFileSync(s,JSON.stringify(o),{mode:384}),Sn.chmodSync(s,384),Sn.renameSync(s,r),H("[browser/vault] saved session",{profile:e,file:r})}catch(r){H("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as fM}from"crypto";function Wd(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of mM)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Ly(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&gM.test(t.label))}function Ny(t){return fM("sha256").update(t,"utf8").digest("hex").slice(0,8)}function $y(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var mM,gM,uo=b(()=>{"use strict";mM=[{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}];gM=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as hM}from"node:crypto";function yM(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function bM(t,e,n){return`el_${hM("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function wM(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Uy(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Hy(t,e){let n=t.role??"",r=t.name??"";By.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Hy(s,e)}async function SM(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,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},jy).catch(()=>[])}async function vM(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},jy).catch(()=>[])}function kM(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function qi(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=kM(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=SM(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,w=!1;u!==null?(h=[],Hy(u,h)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,h=(await vM(t)).filter(B=>By.has(B.role??"")));let k=new Map;for(let P of p){let B=Uy(P.name),j=k.get(B);(!j||j.bbox.w===0&&P.bbox.w>0)&&k.set(B,P)}let A=h.map(P=>({ax:P,dom:k.get(Uy(P.name??""))})),v=r?A:A.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);v.sort((P,B)=>{let j=P.dom?.bbox.y??0,C=B.dom?.bbox.y??0;if(j!==C)return j-C;let M=P.dom?.bbox.x??0,F=B.dom?.bbox.x??0;return M-F}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=v.slice(0,n).map((P,B)=>{let j=P.ax.role??"generic",C=P.ax.name??"",M=bM(j,C,B),F=P.dom?.bbox??{x:0,y:0,w:0,h:0},D=P.dom?.type??null,O=null;P.ax.value!==void 0&&P.ax.value!==null&&(O=String(P.ax.value)),P.ax.checked!==void 0&&(O=String(P.ax.checked)),Ly({role:j,kind:D})&&(O="[redacted]");let U={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(U.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(U.selected=P.ax.selected),P.ax.expanded!==void 0&&(U.expanded=P.ax.expanded);let $;P.dom?.testId?$=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&($=`#${P.dom.id}`);let L={id:M,role:j,label:yM(C),kind:D,value:O,state:U,bbox:F};return $!==void 0&&(L.selector=$),L}),R="idle";try{let P=await t.evaluate(()=>document.readyState);P==="loading"?R="loading":P==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let S=wM(f),T=`obs_${e.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:T,url:m,title:g,textSummary:S,interactive:x,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:I}}var By,jy,Ky=b(()=>{"use strict";uo();By=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);jy="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Wy(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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 Gd(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Wy(t,s)))).filter(o=>o!==null)}async function _M(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function qd(t,e,n){switch(e.kind){case"element_id":return AM(t,e,n);case"selector":return EM(t,e);case"semantic":return TM(t,e)}}async function AM(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 Gd(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function EM(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 Gd(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function TM(t,e){return e.role!==void 0?xM(t,e.text,e.role):RM(t,e.text,e)}async function xM(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 Gd(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function RM(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===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}),l>0&&d.push({loc:s,count:l});let u=await _M(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 h=p[g];if(h===void 0)continue;let w=await Wy(h.locator,h.index);if(w!==null){let k=`${w.role}:${w.label}:${g}`,A=0;for(let v=0;v<k.length;v++)A=A*31+k.charCodeAt(v)>>>0;f.push({...w,id:`el_${A.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Gy=b(()=>{"use strict"});import{randomBytes as CM}from"crypto";import{mkdir as IM,stat as PM,writeFile as MM}from"fs/promises";import{join as zd}from"path";import{gzip as OM}from"zlib";import{promisify as DM}from"util";function FM(t){return zd(Ss(t),"browser")}function LM(t){return zd(FM(t),"screenshots")}function NM(){return new Date().toISOString().replace(/[:.]/g,"-")}function $M(){return CM(3).toString("hex")}async function Jd(t,e,n){if(e.length>qy)throw new Error(`writeScreenshotSidecar: buffer exceeds ${qy} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=LM(t);await IM(r,{recursive:!0});let o=`${NM()}-${$M()}-${n}.png`,s=zd(r,o);await MM(s,e);let{size:i}=await PM(s);return{path:s,bytes:i}}var AJ,qy,zy=b(()=>{"use strict";q();uo();AJ=DM(OM);qy=5*1024*1024});var Vy={};tc(Vy,{PlaywrightProvider:()=>Vd});function Jy(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 Vd,Yy=b(()=>{"use strict";Fy();Ky();Gy();Kd();uo();zy();Vd=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Gi(e)}async open(e){let n=jd(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(c){a=c}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await qi(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}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 qi(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 qd(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Jy(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":{let g=Wd(e.value??"");await l.fill(e.value??"");break}case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.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(h){c=h}else c=g}let u=r.url();if(u!==s){let g=jd(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||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await qi(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;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 qd(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Jy(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 Jd(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 Jd(n,o,r);return s}catch{return null}}}});var kn={};tc(kn,{__resetBrowserRegistryForTests:()=>KM,browserProviderActive:()=>HM,closeBrowserProvider:()=>Yd,getBrowserProvider:()=>BM,peekBrowserProvider:()=>jM});function Xy(){Promise.resolve(Yd()).then(()=>{process.exit(130)})}function Qy(){Promise.resolve(Yd()).then(()=>{process.exit(143)})}function Zy(){ct=null}function UM(){zi||(process.on("SIGINT",Xy),process.on("SIGTERM",Qy),process.on("exit",Zy),zi=!0)}function eb(){zi&&(process.removeListener("SIGINT",Xy),process.removeListener("SIGTERM",Qy),process.removeListener("exit",Zy),zi=!1)}async function BM(t){return ct!==null?ct:(vn!==null||(vn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Yy(),Vy)),n=Dy(t),r=new e(n);return UM(),ct=r,vn=null,r})()),vn)}async function Yd(){if(ct===null)return;let t=ct;ct=null,vn=null,eb(),await t.shutdown()}function HM(){return ct!==null}function jM(){return ct}function KM(){ct=null,vn=null,eb()}var ct,vn,zi,_n=b(()=>{"use strict";Kd();ct=null,vn=null,zi=!1});async function tb(t,e){try{return await Ry(t,e)}catch(n){return H("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function VM(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(_n(),kn));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function nb(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??VM,o=null,s=t,i=null,a=null;try{let c=await Ki(n,t,{headers:JM,redirect:"follow",signal:e.signal});i=c.status,s=c.url||t;let d=c.headers.get("content-type")??"";if(c.ok){if(zM.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 c.text();if(qM.test(d)&&!GM.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};if(o=await tb(u,s),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(c){if(e.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<200)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=await tb(c.html,c.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(e.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),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=c,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 GM,qM,zM,JM,rb=b(()=>{"use strict";Cy();Hd();ie();GM=/(text\/html|application\/xhtml\+xml)/i,qM=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,zM=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,JM={"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 QM(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(YM,{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),XM),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=Yn(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function ob(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?QM({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 sb(t,e){if(e.length===0)return`# Search results for "${t}"
859
859
 
860
860
  (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(`
861
861
  `).trimEnd()}var YM,XM,ib=b(()=>{"use strict";dn();YM="https://api.exa.ai/search",XM=10});function sO(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 l;try{l=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let i=ZM;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,eO)}let a=tO;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,nO)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Xd(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:kt(t,e),truncated:!0}}function iO(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 oO.some(o=>r.includes(o))}function aO(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=sO(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)},l,c=()=>{let d=i.signal.reason;return d instanceof Error?d.message:String(d??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),l=setTimeout(()=>{i.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.mode==="raw"){let u;try{u=await Ki(e,s.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:i.signal})}catch(m){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape network error: ${m instanceof Error?m.message:String(m)}`,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(m){return{content:`web_scrape read error: ${m instanceof Error?m.message:String(m)}`,isError:!0}}let f=Xd(p,s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let u=await nb(s.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:s.timeoutMs,signal:i.signal});if(u.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let p=Xd(u.markdown,s.maxBytes);return{content:p.content,...p.truncated?{truncated:!0}:{}}}catch(u){if(i.signal.aborted)return{content:`web_scrape aborted: ${c()}`,isError:!0};let p=u instanceof Error?u.message:String(u),f=iO(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=ob({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:rO,timeoutMs:s.timeoutMs,signal:i.signal}),p=Xd(sb(s.query,u),s.maxBytes);return{content:p.content,...p.truncated?{truncated:!0}:{}}}catch(u){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${u instanceof Error?u.message:String(u)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),o.removeEventListener("abort",a)}}}var ZM,eO,tO,nO,rO,oO,ab,lb=b(()=>{"use strict";rb();ib();Hd();Zn();ZM=3e4,eO=12e4,tO=1e5,nO=1e6,rO=10,oO=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"];ab=aO()});import{existsSync as db,mkdirSync as lO,readFileSync as cO,renameSync as dO,unlinkSync as uO,writeFileSync as pO}from"node:fs";import{dirname as cb,join as fO}from"node:path";import{randomBytes as mO}from"node:crypto";function sr(t){let e=t??sc();if(!db(e))return[];try{let n=cO(e,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${e}: ${r}`),[]}}function Ji(t,e){let n=e??sc();lO(cb(n),{recursive:!0});let r=fO(cb(n),`.schedules.json.${process.pid}.${mO(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{pO(r,o,"utf-8"),dO(r,n)}catch(s){try{db(r)&&uO(r)}catch{}throw s}}function ub(t,e){let n=sr(e),r=n.map(l=>l.id),o=gO(t.name),s=hO(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),Ji(n,e),a}function pb(t,e){let n=sr(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(Ji(o,e),!0)}function fb(t,e){return sr(e).find(n=>n.id===t)}function gO(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function hO(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}var mb=b(()=>{"use strict";q()});import{existsSync as yO,readFileSync as bO}from"node:fs";import{join as wO}from"node:path";async function po(t,e,n){let r;try{let o=wO(Nf("default"),"port");if(!yO(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let s=bO(o,"utf-8").trim();if(r=parseInt(s,10),Number.isNaN(r))return{synced:!1,detail:"daemon-not-detected (invalid port file)"}}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let o=await fetch(`http://localhost:${r}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return o.ok?{synced:!0,detail:"synced"}:t==="POST"&&o.status===409?{synced:!0,detail:"already-registered"}:t==="DELETE"&&o.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${o.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}var Qd,gb=b(()=>{"use strict";q();Qd="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start."});import{existsSync as SO}from"node:fs";import{readFile as vO}from"node:fs/promises";var hb,yb,bb,wb,Sb=b(()=>{"use strict";mb();q();gb();hb=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=n.notifyChat;if(o!==void 0&&typeof o!="number"&&typeof o!="string")return{content:"Invalid input: notifyChat must be a number (chat id) or string (chat id or alias name)",isError:!0};let s=ub({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),i=s.enabled?await po("POST","/tasks",{taskId:s.id,command:s.command,cron:s.cron,trigger:s.trigger,notifyOn:s.notifyOn,...s.notifyChat!==void 0?{notifyChat:s.notifyChat}:{}}):await po("DELETE",`/tasks/${s.id}`);return{content:JSON.stringify({id:s.id,name:s.name,cron:s.cron,enabled:s.enabled,daemonSynced:i.synced,syncDetail:i.detail,...i.synced?{}:{syncNote:Qd}})}},yb=async(t,e)=>{let n=sr();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},bb=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,s=fs();if(!SO(s))return{content:JSON.stringify([])};let i;try{let c=await vO(s);i=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-afk",
3
- "version": "5.75.0",
3
+ "version": "5.75.2",
4
4
  "description": "Open-source coding-agent harness you can actually change — own the loop (prompts, gates, routing, skills, terminal states), use any model, run long tasks while you're away.",
5
5
  "main": "dist/index.mjs",
6
6
  "types": "dist/index.d.ts",