agent-afk 5.82.11 → 5.82.12
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.
|
@@ -44,16 +44,22 @@ Never fabricate intent. When none is available the value is the literal `(none s
|
|
|
44
44
|
|
|
45
45
|
**Triage (inline).** From the resolved diff extract: change type (hotfix | feature | refactor | dep-bump | new-service), files changed, total lines changed, summary. Classify regime: `light` if ≤300 lines or change type is hotfix/dep-bump; `full` otherwise.
|
|
46
46
|
|
|
47
|
+
**Concurrency floor — declared, conditional, and enforced.** *Through synthesis*, a full-regime review peaks at **2 concurrent sub-agent sessions** (Wave 1's two dimension agents) and dispatches **3 in total** (Wave 1 ×2, then Wave 2 ×1, sequential). Wave 1.5 runs inline in the orchestrator and dispatches nothing. **No wave nests a child**: the sub-agents are shell-less by design, and nothing in this skill requires them to run a command, so none of them needs to nest a `git-investigator` to comply. If you add a requirement here that needs a shell, you have silently doubled this floor — put that requirement in Wave 1.5 instead.
|
|
48
|
+
|
|
49
|
+
**The post-synthesis tail is the conditional half of that budget.** A review that surfaces a `critical`/`high` finding invokes `/shadow-verify` (see **Post-synthesis** below), which dispatches one verifier per claim in parallel — so the whole-run budget is **peak 3 concurrent, 5–6 total**, and it lands on exactly the high-stakes reviews most likely to hit a rate ceiling. Bound it: **at most 3 claims in a single round, no repeat rounds**, and hand the verifiers Wave 1.5's manifest so each re-derives the *claim* instead of re-locating evidence Wave 1.5 already pinned at the ref. Wave 1.5 verifies that a citation is real; shadow-verify re-derives whether the inference drawn from it holds — never substitute one for the other.
|
|
50
|
+
|
|
47
51
|
**Wave 1 — Full review (regime=full, 2 parallel agents, `subagent_type: "research-agent"`).** Dispatch:
|
|
48
52
|
- **security · api-compat** — contracts, auth, injection, breaking changes, secret exposure.
|
|
49
53
|
- **correctness · spec-compliance · test-coverage · perf-observability** — logic bugs, regressions, whether the change satisfies its **stated intent** (unmet requirement or unrequested scope creep), missing tests, hot-path perf, logging gaps.
|
|
50
54
|
|
|
51
55
|
Each agent receives: full diff + file tree + triage header + **reviewed ref (SHA)** + the **stated intent** (what the change is meant to accomplish, or `(none supplied)`), the severity rubric, and the finding schema.
|
|
52
56
|
|
|
53
|
-
**Citation requirement (enforced per agent)
|
|
54
|
-
1. State the ref it
|
|
55
|
-
2.
|
|
56
|
-
3. If the line
|
|
57
|
+
**Citation requirement (enforced per agent).** Wave 1 agents cite from the diff and from file reads available in their own session. They do **not** run git and do **not** re-read at the reviewed ref — that verification is centralized in Wave 1.5 below, which re-reads every `blocking`/`critical`/`high` citation **and every `file-state` citation at any severity** at the ref, then drops the fabricated ones. Each agent must:
|
|
58
|
+
1. State the reviewed ref it was given in each finding: `ref: <sha>`.
|
|
59
|
+
2. Classify every citation as `diff-context` (line visible in the diff hunk) or `file-state` (line in the post-merge file, not visible in the hunk). Tag every `file-state` citation `[UNVERIFIED: not re-read]` so Wave 1.5 knows to check it — a Wave 1 `Read` observes the **working tree**, which equals the reviewed ref only when that ref is the checked-out HEAD, so for a PR, branch, or commit target that is not checked out locally the tag is load-bearing, not decorative.
|
|
60
|
+
3. Never paraphrase or reconstruct a line from memory. If the line is not visible in the diff, cite it as `file-state` and let Wave 1.5 resolve it — do not invent the content.
|
|
61
|
+
|
|
62
|
+
**Invariant — why Wave 1 does not run git.** `research-agent` has no shell (`tools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)` — no `Bash`, and that single `Agent(...)` entry is the nesting path this rule closes), so a mandatory `git show` forces it to dispatch a nested `git-investigator` purely to run one command. That doubles the concurrent session count of *every* Wave 1 agent, and is the structural cause of the rate-limit cascade in #726. Ref-anchored verification is therefore performed once, centrally, by a shell-capable actor — never N times by shell-less ones. Do not reintroduce a per-agent re-read here.
|
|
57
63
|
|
|
58
64
|
Banned words: "ensure", "consider", "may", "could". No `file:line` citation → omit the finding.
|
|
59
65
|
|
|
@@ -62,14 +68,14 @@ Banned words: "ensure", "consider", "may", "could". No `file:line` citation →
|
|
|
62
68
|
- `stated-intent` is `(none supplied)` → do **not** assess spec-compliance and do **not** substitute the global constraints for the spec. Emit exactly one line: `unverified — spec-compliance not assessed: no stated intent supplied (pass --brief/--spec, or review a PR/commit)`. Silently treating the diff or the constraints as "the spec" is the precise failure this rule prevents.
|
|
63
69
|
|
|
64
70
|
**api-compat reachability pre-check (mandatory before surfacing any breaking-change finding).**
|
|
65
|
-
For every symbol flagged as a breaking change,
|
|
71
|
+
For every symbol flagged as a breaking change, search production source files with the `Grep` tool — which needs no shell, so this check never forces a nested dispatch — for imports or usages of that symbol, excluding `*.test.*`, `*.spec.*`, `__tests__/`, `__mocks__/`, `/test/`, `/tests/`. Decision table:
|
|
66
72
|
- Zero production importers → downgrade finding to `nit`, append `[UNVERIFIED: no production importers]`, set confidence `low`.
|
|
67
73
|
- One or more production importers → severity stands; include one importer path as evidence.
|
|
68
74
|
|
|
69
|
-
If
|
|
75
|
+
If the `Grep` tool is unavailable, tag the finding `[UNVERIFIED: reachability not checked]` and downgrade one severity tier.
|
|
70
76
|
|
|
71
|
-
**Absence-claim grounding (mandatory for any claim that something does not exist).** Before emitting a finding of the form "no test covers X", "no handler validates Y", "no caller invokes Z", "X is not tested":
|
|
72
|
-
- Zero matches → finding stands; cite the
|
|
77
|
+
**Absence-claim grounding (mandatory for any claim that something does not exist).** Before emitting a finding of the form "no test covers X", "no handler validates Y", "no caller invokes Z", "X is not tested": search the production tree with the `Grep` tool — which needs no shell, so this check never forces a nested dispatch — for plausible match strings. Decision table:
|
|
78
|
+
- Zero matches → finding stands; cite the search pattern in the evidence field.
|
|
73
79
|
- One or more matches → emit `unverified — absence claim refuted by <path>:<line>` instead of the finding.
|
|
74
80
|
- Grep tooling unavailable or claim cannot be reduced to a pattern → tag finding `[UNVERIFIED: absence not checked]` and downgrade one severity tier.
|
|
75
81
|
|
|
@@ -77,14 +83,14 @@ This is the agent's first-line self-check; **Wave 1.5 Check B** independently re
|
|
|
77
83
|
|
|
78
84
|
**Wave 1 — Light review (regime=light, 1 agent, `subagent_type: "research-agent"`).** Single agent covers all dimensions (including spec-compliance). Same `stated-intent` input, rubric, schema, and citation requirement.
|
|
79
85
|
|
|
80
|
-
**Wave 1.5 — Citation + absence-claim verification (
|
|
86
|
+
**Wave 1.5 — Citation + absence-claim verification (INLINE — run by the orchestrator, dispatches nothing).** Run after Wave 1 returns, before Wave 2 synthesis. The orchestrator already holds exactly the read-only shell this verification needs (`git show` / `git diff` / `gh pr diff` / `grep` / `rg` — see the shell grant above), so running it inline costs **zero** additional sessions and zero nesting. A shell-less sub-agent here would have to nest a `git-investigator` to run the very commands the orchestrator can already run. Two independent checks:
|
|
81
87
|
|
|
82
|
-
**Check A — Citation verification.** Extracts every `file:line` citation from any `blocking`, `critical`, or `high` finding across all Wave 1 results. For each citation, runs `git show <reviewed-ref>:<file>` (or equivalent) and checks whether the quoted evidence snippet actually appears at that line in the reviewed ref — not in main, not in diff context alone. Classifies each citation as:
|
|
88
|
+
**Check A — Citation verification.** Extracts (a) every `file:line` citation from any `blocking`, `critical`, or `high` finding, **and (b) every citation tagged `file-state` at any severity** — `medium`, `low`, and `nit` included — across all Wave 1 results. Both sets are checked, because Wave 1 never re-reads at the ref: an unverified `file-state` citation in a `low` finding is exactly as fabricable as one in a `high` finding, and quoting a line absent from the reviewed change is a defect at every tier. For each citation, runs `git show <reviewed-ref>:<file>` (or equivalent) and checks whether the quoted evidence snippet actually appears at that line in the reviewed ref — not in main, not in diff context alone. Classifies each citation as:
|
|
83
89
|
- `verified` — content matches what is actually at that line on the reviewed ref.
|
|
84
90
|
- `diff-only` — line appears in the diff hunk but no longer exists at the reviewed ref HEAD (e.g., deleted block). Finding must be downgraded: the issue may already be resolved.
|
|
85
91
|
- `fabricated` — line does not exist at the reviewed ref and was not in the diff hunk; the evidence snippet is unverifiable. Finding is **dropped** from the report.
|
|
86
92
|
|
|
87
|
-
**Check B — Absence-claim verification.** Extracts every **absence claim**
|
|
93
|
+
**Check B — Absence-claim verification.** Extracts every **absence claim** across all Wave 1 results **at any severity** — `medium`, `low`, and `nit` included, for the same reason Check A checks every `file-state` citation: Wave 1's absence grounding is a self-check by an agent that never re-read at the ref, so an unverified absence claim in a `low` finding is exactly as fabricable as one in a `high` finding. These are claims of the form "no test covers X", "no handler validates Y", "no caller invokes Z", "X is not tested", "Y has no validation". Citations are not required for absence claims, so Check A cannot catch them; they need their own gate. For each, identify the asserted-absent symbol, test name, or behavior, then run `git grep -n <pattern> <reviewed-ref>` (or `rg --no-heading -n <pattern>` if outside a git context) across the production tree (exclude the same paths as the api-compat reachability check: tests, mocks, fixtures, when the claim is about production code). Classify as:
|
|
88
94
|
- `confirmed-absent` — zero matches in the asserted scope; finding stands.
|
|
89
95
|
- `false-absent` — one or more matches in the asserted scope; finding is **dropped** (the asserted-absent entity exists at the reviewed ref). Name the matching path(s) in the dropped-findings manifest.
|
|
90
96
|
- `grep-unavailable` — tooling missing, symbol ambiguous, or absence claim cannot be reduced to a grep pattern; finding tagged `[UNVERIFIED: absence not checked]` and downgraded one severity tier.
|
|
@@ -106,12 +112,12 @@ Sort overall: critical → high → medium → low → nit; security first withi
|
|
|
106
112
|
|
|
107
113
|
Confidence `low` → auto-downgrade one tier + append `[low confidence — verify with runtime context]`.
|
|
108
114
|
|
|
109
|
-
**Output per dimension:** if you have read the file(s)
|
|
115
|
+
**Output per dimension:** if you have read the relevant file(s) and have either real findings or a confirmed clean read, emit findings or `no issues found — read <file>`. If evidence is insufficient — you could not read the file, the tool was unavailable, no production importers were found for the symbol, or no test file exists at the asserted path — emit `unverified — <reason>` naming the missing evidence rather than invent a finding to fill the slot. Banned words from the hedging list (`ensure`, `consider`, `may`, `could`) remain banned **inside findings**; the `unverified` channel is the sanctioned path for uncertainty.
|
|
110
116
|
|
|
111
117
|
**Finding schema:** `severity · confidence · dimension · file:line_range · ref:<sha> · citation-type:(diff-context|file-state) · finding (one concrete sentence naming the failure mode) · evidence (verbatim code ≤4 lines) · suggestion (one concrete fix)`.
|
|
112
118
|
|
|
113
119
|
**Epistemic scope disclosure (required in synthesis output).** The "What was not checked" section must include:
|
|
114
|
-
- Which ref
|
|
120
|
+
- Which ref citations were verified against in Wave 1.5 (list the SHA or `unknown` if patch-file input). Example: `Citations verified inline against branch HEAD abc1234.`
|
|
115
121
|
- If any citations could not be verified against a live ref (patch-file input): `Citation verification skipped — no live ref available; diff-context citations only.`
|
|
116
122
|
- Any topical gaps (e.g. 'did not review Telegram surface', 'did not run tests').
|
|
117
123
|
- Whether a **stated intent** was available and spec-compliance was assessed. Example: `Stated intent: PR #123 title+body — spec-compliance assessed.` or `Stated intent: (none supplied) — spec-compliance not assessed.`
|
package/dist/cli.mjs
CHANGED
|
@@ -870,7 +870,7 @@ Remedy: these paths are outside the fork's granted read roots. Re-dispatch with
|
|
|
870
870
|
|
|
871
871
|
`).trim()}function b8(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}async function II(e,t){let{JSDOM:n,Readability:r,turndown:o}=await y8(),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=_I(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=_I(o.turndown(d));return{title:a,markdown:u,textLength:b8(c),usedFallback:!0}}var GS,PI=R(()=>{"use strict";GS=null});function S8(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 MI(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function v8(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 Am(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??S8,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(!w8.has(u.status)||d===o)return u;let m=v8(u,s)??MI(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=MI(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 w8,qS=R(()=>{"use strict";ye();w8=new Set([429,502,503,504])});import{readFileSync as k8}from"node:fs";import{join as T8}from"path";function E8(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function OI(e,t){return E8(t).test(e)}function A8(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(x8.has(t))return!0;if(R8.has(t))return!1}return!1}function $I(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function C8(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 DI(e){let t=e===void 0||e.trim()===""?"default":e.trim();return cc(t),t}function _8(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function I8(e){try{return k8(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function P8(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=DI(t.defaultProfile)),n}function FI(e){let t=e?.env??v,n=e?.readFileSync??I8,r=e?.surface??t.AGENT_SURFACE,o=A8(t.AFK_BROWSER_HEADLESS,r),i=$I(t.AFK_BROWSER_ALLOWED_DOMAINS),s=$I(t.AFK_BROWSER_BLOCKED_DOMAINS),a=_8(t.AFK_BROWSER_DOM_SNAPSHOTS),l=C8(t.AFK_BROWSER_BACKEND),c=DI(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():T8(En(),"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=P8(d,g);return h.configPath=m,h}function Cm(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(OI(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>OI(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var x8,R8,_m=R(()=>{"use strict";G();z();x8=new Set(["daemon","subagent","telegram","afk"]),R8=new Set(["repl","interactive","cli"])});import{existsSync as M8,readFileSync as O8}from"node:fs";import{createRequire as $8}from"node:module";import{dirname as D8,join as F8}from"node:path";function BI(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<N8&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function Nt(e){let t=BI(e);return NI.some(n=>t.includes(n))}function B8(){try{let t=$8(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(O8(t,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let i=F8(D8(t),o);return M8(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function qc(){return LI??=B8()??L8,LI}function zS(e){return e.includes("install chromium")}function un(e,t){let n=BI(e),r=t?.latched===!0?` ${U8}`:"";if(n.includes("Executable doesn't exist")){let o="";return t?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":t?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${qc()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${qc()}). Or pick a different tool.${r}`}function zc(e,t,n=!1){if(!Nt(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
|
|
872
872
|
|
|
873
|
-
${un(e,{headless:t,latched:n})}`,{cause:e})}var NI,L8,N8,LI,U8,Im=R(()=>{"use strict";NI=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],L8="pnpm exec playwright install chromium",N8=4;U8="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import vi from"node:fs";import Pm from"node:path";import{randomBytes as j8}from"node:crypto";import{chromium as H8}from"playwright";function W8(){try{return"5.82.11"}catch{}try{let e=Pm.resolve(import.meta.dirname,"../../../package.json"),t=vi.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var K8,Mm,UI=R(()=>{"use strict";Im();z();ye();K8=W8(),Mm=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=H8.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=zc(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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){this.clearLaunchFailure();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.clearLaunchFailure(),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/${K8}`}}loadStorageState(t){let n=dc(t);try{if(!vi.existsSync(n))return;let r=JSON.parse(vi.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=dc(t);if(!vi.existsSync(r))return;let o=await n.storageState(),i=Pm.join(Pm.dirname(r),`.${Pm.basename(r)}.${process.pid}.${j8(4).toString("hex")}.tmp`);vi.writeFileSync(i,JSON.stringify(o),{mode:384}),vi.chmodSync(i,384),vi.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 G8}from"crypto";function jI(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&q8.test(e.label))}function HI(e){return G8("sha256").update(e,"utf8").digest("hex").slice(0,8)}function WI(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var q8,Om=R(()=>{"use strict";q8=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as z8}from"node:crypto";function J8(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function Y8(e,t,n){return`el_${z8("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function V8(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function KI(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function qI(e,t){let n=e.role??"",r=e.name??"";GI.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])qI(i,t)}async function X8(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},zI).catch(()=>[])}async function Q8(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},zI).catch(()=>[])}function Z8(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function $m(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=Z8(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=X8(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=[],qI(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await Q8(e)).filter(B=>GI.has(B.role??"")));let w=new Map;for(let P of m){let B=KI(P.name),j=w.get(B);(!j||j.bbox.w===0&&P.bbox.w>0)&&w.set(B,P)}let S=y.map(P=>({ax:P,dom:w.get(KI(P.name??""))})),T=r?S:S.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);T.sort((P,B)=>{let j=P.dom?.bbox.y??0,$=B.dom?.bbox.y??0;if(j!==$)return j-$;let H=P.dom?.bbox.x??0,M=B.dom?.bbox.x??0;return H-M}),T.length>200&&o.push("page has 200+ interactive elements; consider scoping");let C=T.slice(0,n).map((P,B)=>{let j=P.ax.role??"generic",$=P.ax.name??"",H=Y8(j,$,B),M=P.dom?.bbox??{x:0,y:0,w:0,h:0},N=P.dom?.type??null,I=null;P.ax.value!==void 0&&P.ax.value!==null&&(I=String(P.ax.value)),P.ax.checked!==void 0&&(I=String(P.ax.checked)),jI({role:j,kind:N})&&(I="[redacted]");let F={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(F.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(F.selected=P.ax.selected),P.ax.expanded!==void 0&&(F.expanded=P.ax.expanded);let _;P.dom?.testId?_=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(_=`#${P.dom.id}`);let U={id:H,role:j,label:J8($),kind:N,value:I,state:F,bbox:M};return _!==void 0&&(U.selector=_),U}),D="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?D="loading":P==="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 E=V8(f),O=`obs_${t.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:O,url:g,title:h,textSummary:E,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 GI,zI,JI=R(()=>{"use strict";Om();GI=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);zI="a[href], button, input, select, textarea, [role], [tabindex], label"});async function YI(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 JS(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>YI(e,i)))).filter(o=>o!==null)}async function e5(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 YS(e,t,n){switch(t.kind){case"element_id":return t5(e,t,n);case"selector":return n5(e,t);case"semantic":return r5(e,t)}}async function t5(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 JS(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function n5(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 JS(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function r5(e,t){return t.role!==void 0?o5(e,t.text,t.role):i5(e,t.text,t)}async function o5(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 JS(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function i5(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 e5(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 YI(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let T=0;T<w.length;T++)S=S*31+w.charCodeAt(T)>>>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 VI=R(()=>{"use strict"});async function VS(e,t,n,r){let o=e.url();if(o===n)return null;let i=Cm(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var XI=R(()=>{"use strict";_m()});import{randomBytes as s5}from"crypto";import{mkdir as a5,stat as l5,writeFile as c5}from"fs/promises";import{join as XS}from"path";import{gzip as d5}from"zlib";import{promisify as u5}from"util";function p5(e){return XS(Zo(e),"browser")}function m5(e){return XS(p5(e),"screenshots")}function f5(){return new Date().toISOString().replace(/[:.]/g,"-")}function g5(){return s5(3).toString("hex")}async function QS(e,t,n){if(t.length>QI)throw new Error(`writeScreenshotSidecar: buffer exceeds ${QI} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=m5(e);await a5(r,{recursive:!0});let o=`${f5()}-${g5()}-${n}.png`,i=XS(r,o);await c5(i,t);let{size:s}=await l5(i);return{path:i,bytes:s}}var UAe,QI,ZI=R(()=>{"use strict";z();Om();UAe=u5(d5);QI=5*1024*1024});var tP={};ep(tP,{PlaywrightProvider:()=>ZS});function eP(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 ZS,nP=R(()=>{"use strict";UI();JI();VI();_m();XI();ZI();ZS=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Mm(t)}async open(t){let n=Cm(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(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await VS(o,this.config,t.url,()=>this.close({sessionId:r}));if(u!==null)return u}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let d=await $m(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,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}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 $m(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 YS(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${eP(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":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=await VS(r,this.config,i,()=>this.close({sessionId:n}));if(u!==null)return u;let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await $m(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 YS(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${eP(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 QS(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 QS(n,o,r);return i}catch{return null}}}});var Ti={};ep(Ti,{__resetBrowserRegistryForTests:()=>S5,browserProviderActive:()=>b5,closeBrowserProvider:()=>ev,getBrowserProvider:()=>y5,peekBrowserProvider:()=>w5});function rP(){Promise.resolve(ev()).then(()=>{process.exit(130)})}function oP(){Promise.resolve(ev()).then(()=>{process.exit(143)})}function iP(){rr=null}function h5(){Dm||(process.on("SIGINT",rP),process.on("SIGTERM",oP),process.on("exit",iP),Dm=!0)}function sP(){Dm&&(process.removeListener("SIGINT",rP),process.removeListener("SIGTERM",oP),process.removeListener("exit",iP),Dm=!1)}async function y5(e){return rr!==null?rr:(ki!==null||(ki=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(nP(),tP)),n=FI(e),r=new t(n);return h5(),rr=r,ki=null,r})()),ki)}async function ev(){if(rr===null)return;let e=rr;rr=null,ki=null,sP(),await e.shutdown()}function b5(){return rr!==null}function w5(){return rr}function S5(){rr=null,ki=null,sP()}var rr,ki,Dm,Ei=R(()=>{"use strict";_m();rr=null,ki=null,Dm=!1});async function aP(e,t){try{return await II(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function R5(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Ei(),Ti));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function lP(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??R5,o=null,i=e,s=null,a=null;try{let c=await Am(n,e,{headers:x5,redirect:"follow",signal:t.signal});s=c.status,i=c.url||e;let d=c.headers.get("content-type")??"";if(c.ok){if(E5.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(T5.test(d)&&!k5.test(d))return{title:"",markdown:u.trim(),finalUrl:i,usedRender:!1};if(o=await aP(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 aP(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 k5,T5,E5,x5,cP=R(()=>{"use strict";PI();qS();ye();k5=/(text\/html|application\/xhtml\+xml)/i,T5=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,E5=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,x5={"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 _5(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(A5,{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),C5),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Ir(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 dP(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?_5({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 uP(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
873
|
+
${un(e,{headless:t,latched:n})}`,{cause:e})}var NI,L8,N8,LI,U8,Im=R(()=>{"use strict";NI=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],L8="pnpm exec playwright install chromium",N8=4;U8="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import vi from"node:fs";import Pm from"node:path";import{randomBytes as j8}from"node:crypto";import{chromium as H8}from"playwright";function W8(){try{return"5.82.12"}catch{}try{let e=Pm.resolve(import.meta.dirname,"../../../package.json"),t=vi.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var K8,Mm,UI=R(()=>{"use strict";Im();z();ye();K8=W8(),Mm=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=H8.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=zc(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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){this.clearLaunchFailure();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.clearLaunchFailure(),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/${K8}`}}loadStorageState(t){let n=dc(t);try{if(!vi.existsSync(n))return;let r=JSON.parse(vi.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=dc(t);if(!vi.existsSync(r))return;let o=await n.storageState(),i=Pm.join(Pm.dirname(r),`.${Pm.basename(r)}.${process.pid}.${j8(4).toString("hex")}.tmp`);vi.writeFileSync(i,JSON.stringify(o),{mode:384}),vi.chmodSync(i,384),vi.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 G8}from"crypto";function jI(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&q8.test(e.label))}function HI(e){return G8("sha256").update(e,"utf8").digest("hex").slice(0,8)}function WI(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var q8,Om=R(()=>{"use strict";q8=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as z8}from"node:crypto";function J8(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function Y8(e,t,n){return`el_${z8("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function V8(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function KI(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function qI(e,t){let n=e.role??"",r=e.name??"";GI.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])qI(i,t)}async function X8(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},zI).catch(()=>[])}async function Q8(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},zI).catch(()=>[])}function Z8(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function $m(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=Z8(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=X8(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=[],qI(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await Q8(e)).filter(B=>GI.has(B.role??"")));let w=new Map;for(let P of m){let B=KI(P.name),j=w.get(B);(!j||j.bbox.w===0&&P.bbox.w>0)&&w.set(B,P)}let S=y.map(P=>({ax:P,dom:w.get(KI(P.name??""))})),T=r?S:S.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);T.sort((P,B)=>{let j=P.dom?.bbox.y??0,$=B.dom?.bbox.y??0;if(j!==$)return j-$;let H=P.dom?.bbox.x??0,M=B.dom?.bbox.x??0;return H-M}),T.length>200&&o.push("page has 200+ interactive elements; consider scoping");let C=T.slice(0,n).map((P,B)=>{let j=P.ax.role??"generic",$=P.ax.name??"",H=Y8(j,$,B),M=P.dom?.bbox??{x:0,y:0,w:0,h:0},N=P.dom?.type??null,I=null;P.ax.value!==void 0&&P.ax.value!==null&&(I=String(P.ax.value)),P.ax.checked!==void 0&&(I=String(P.ax.checked)),jI({role:j,kind:N})&&(I="[redacted]");let F={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(F.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(F.selected=P.ax.selected),P.ax.expanded!==void 0&&(F.expanded=P.ax.expanded);let _;P.dom?.testId?_=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(_=`#${P.dom.id}`);let U={id:H,role:j,label:J8($),kind:N,value:I,state:F,bbox:M};return _!==void 0&&(U.selector=_),U}),D="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?D="loading":P==="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 E=V8(f),O=`obs_${t.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:O,url:g,title:h,textSummary:E,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 GI,zI,JI=R(()=>{"use strict";Om();GI=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);zI="a[href], button, input, select, textarea, [role], [tabindex], label"});async function YI(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 JS(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>YI(e,i)))).filter(o=>o!==null)}async function e5(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 YS(e,t,n){switch(t.kind){case"element_id":return t5(e,t,n);case"selector":return n5(e,t);case"semantic":return r5(e,t)}}async function t5(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 JS(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function n5(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 JS(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function r5(e,t){return t.role!==void 0?o5(e,t.text,t.role):i5(e,t.text,t)}async function o5(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 JS(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function i5(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 e5(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 YI(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let T=0;T<w.length;T++)S=S*31+w.charCodeAt(T)>>>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 VI=R(()=>{"use strict"});async function VS(e,t,n,r){let o=e.url();if(o===n)return null;let i=Cm(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var XI=R(()=>{"use strict";_m()});import{randomBytes as s5}from"crypto";import{mkdir as a5,stat as l5,writeFile as c5}from"fs/promises";import{join as XS}from"path";import{gzip as d5}from"zlib";import{promisify as u5}from"util";function p5(e){return XS(Zo(e),"browser")}function m5(e){return XS(p5(e),"screenshots")}function f5(){return new Date().toISOString().replace(/[:.]/g,"-")}function g5(){return s5(3).toString("hex")}async function QS(e,t,n){if(t.length>QI)throw new Error(`writeScreenshotSidecar: buffer exceeds ${QI} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=m5(e);await a5(r,{recursive:!0});let o=`${f5()}-${g5()}-${n}.png`,i=XS(r,o);await c5(i,t);let{size:s}=await l5(i);return{path:i,bytes:s}}var UAe,QI,ZI=R(()=>{"use strict";z();Om();UAe=u5(d5);QI=5*1024*1024});var tP={};ep(tP,{PlaywrightProvider:()=>ZS});function eP(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 ZS,nP=R(()=>{"use strict";UI();JI();VI();_m();XI();ZI();ZS=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Mm(t)}async open(t){let n=Cm(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(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await VS(o,this.config,t.url,()=>this.close({sessionId:r}));if(u!==null)return u}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let d=await $m(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,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}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 $m(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 YS(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${eP(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":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=await VS(r,this.config,i,()=>this.close({sessionId:n}));if(u!==null)return u;let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await $m(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 YS(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${eP(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 QS(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 QS(n,o,r);return i}catch{return null}}}});var Ti={};ep(Ti,{__resetBrowserRegistryForTests:()=>S5,browserProviderActive:()=>b5,closeBrowserProvider:()=>ev,getBrowserProvider:()=>y5,peekBrowserProvider:()=>w5});function rP(){Promise.resolve(ev()).then(()=>{process.exit(130)})}function oP(){Promise.resolve(ev()).then(()=>{process.exit(143)})}function iP(){rr=null}function h5(){Dm||(process.on("SIGINT",rP),process.on("SIGTERM",oP),process.on("exit",iP),Dm=!0)}function sP(){Dm&&(process.removeListener("SIGINT",rP),process.removeListener("SIGTERM",oP),process.removeListener("exit",iP),Dm=!1)}async function y5(e){return rr!==null?rr:(ki!==null||(ki=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(nP(),tP)),n=FI(e),r=new t(n);return h5(),rr=r,ki=null,r})()),ki)}async function ev(){if(rr===null)return;let e=rr;rr=null,ki=null,sP(),await e.shutdown()}function b5(){return rr!==null}function w5(){return rr}function S5(){rr=null,ki=null,sP()}var rr,ki,Dm,Ei=R(()=>{"use strict";_m();rr=null,ki=null,Dm=!1});async function aP(e,t){try{return await II(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function R5(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Ei(),Ti));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function lP(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??R5,o=null,i=e,s=null,a=null;try{let c=await Am(n,e,{headers:x5,redirect:"follow",signal:t.signal});s=c.status,i=c.url||e;let d=c.headers.get("content-type")??"";if(c.ok){if(E5.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(T5.test(d)&&!k5.test(d))return{title:"",markdown:u.trim(),finalUrl:i,usedRender:!1};if(o=await aP(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 aP(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 k5,T5,E5,x5,cP=R(()=>{"use strict";PI();qS();ye();k5=/(text\/html|application\/xhtml\+xml)/i,T5=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,E5=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,x5={"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 _5(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(A5,{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),C5),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Ir(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 dP(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?_5({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 uP(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
874
874
|
|
|
875
875
|
(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(`
|
|
876
876
|
`).trimEnd()}var A5,C5,pP=R(()=>{"use strict";fo();A5="https://api.exa.ai/search",C5=10});function Fm(e){if(e instanceof Error&&e.name==="TimeoutError")return"timeout";let t=e instanceof Error?e.message:String(e);return/Timeout\s+\d+\s*ms exceeded/i.test(t)?"timeout":void 0}var xi=R(()=>{"use strict";Im()});function D5(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=I5;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,P5)}let a=M5;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,O5)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function tv(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:Cr(e,t),truncated:!0}}function F5(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=D5(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 Am(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=tv(m,i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let u=await lP(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=tv(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=Nt(u)&&!zS(m)?` (the render fallback needs the optional Playwright browser \u2014 run \`${qc()}\`)`:"";return{content:`web_scrape markdown error: ${m}${f}`,isError:!0}}let d=dP({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:$5,timeoutMs:i.timeoutMs,signal:s.signal}),m=tv(uP(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 I5,P5,M5,O5,$5,mP,fP=R(()=>{"use strict";cP();pP();qS();ta();xi();I5=3e4,P5=12e4,M5=1e5,O5=1e6,$5=10;mP=F5()});import{existsSync as hP,mkdirSync as L5,readFileSync as N5,renameSync as B5,unlinkSync as U5,writeFileSync as j5}from"node:fs";import{dirname as gP,join as H5}from"node:path";import{randomBytes as W5}from"node:crypto";function pn(e){let t=e??Jb();if(!hP(t))return[];try{let n=N5(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 Ri(e,t){let n=t??Jb();L5(gP(n),{recursive:!0});let r=H5(gP(n),`.schedules.json.${process.pid}.${W5(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{j5(r,o,"utf-8"),B5(r,n)}catch(i){try{hP(r)&&U5(r)}catch{}throw i}}function Lm(e,t){let n=pn(t),r=n.map(l=>l.id),o=K5(e.name),i=G5(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),Ri(n,t),a}function Nm(e,t){let n=pn(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(Ri(o,t),!0)}function Jc(e,t){return pn(t).find(n=>n.id===e)}function K5(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function G5(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function yP(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 Bm=R(()=>{"use strict";z()});import{existsSync as q5,readFileSync as z5}from"node:fs";import{join as J5}from"node:path";async function In(e,t,n){let r;try{let o=J5(cp("default"),"port");if(!q5(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=z5(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 yo,nv=R(()=>{"use strict";z();yo="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 Y5}from"node:fs";import{readFile as V5}from"node:fs/promises";var bP,wP,SP,vP,kP=R(()=>{"use strict";Bm();z();nv();bP=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=Lm({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 In("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 In("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:yo}})}},wP=async(e,t)=>{let n=pn();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})))}},SP=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=Wn();if(!Y5(i))return{content:JSON.stringify([])};let s;try{let c=await V5(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
|
|
@@ -1762,7 +1762,7 @@ ${T}
|
|
|
1762
1762
|
${k}`})}return{fileBlocks:l,warnings:c}}async function qH(e,t,n,r,o="summary",i,s){let a=RU(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),ul(process.stdout,Qd(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,T=[],k=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 H of $)(i??{fn:console.log}).fn(p.dim(` \u2192 subagent backgrounded as ${H.jobId}: ${H.label}`))}).catch(()=>{})},E=r.getCompositor?r.getCompositor():null,O=()=>new _l({out:Il(i),thinkingMode:o,...C?{activeSkillName:C}:{},onCancel:()=>{t.interrupt().catch(j=>{qe()&&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}:{},...E?{compositor:E}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),A=O(),P=async()=>{if(!m){m=!0;try{await A.dispose()}catch{}}},B=async()=>{await A.arm();let j=A.getCompositor();if(i&&j){let $=j;i.fn=H=>$.commitAbove(H),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(j),r.setInterruptNotifier?.($=>A.setInterrupting($)),r.rearmStatus?.()};try{E?E.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{h=!0,A.setSoftStopping(!0),t.interrupt().catch(F=>{qe()&&console.error(" "+p.error("soft-stop session.interrupt() failed:"),F)});let I=r.subagentControl;I?.hasActiveForeground()&&I.cancelActiveForeground().catch(F=>{qe()&&console.error(" "+p.error("soft-stop cancelActiveForeground() failed:"),F)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{y=!0,t.interrupt().catch(I=>{qe()&&console.error(" "+p.error("pause-interrupt session.interrupt() failed:"),I)})}),await B(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(D);let{fileBlocks:j,warnings:$}=GH(e.text,{rootDir:process.cwd()});for(let I of $)(i??{fn:console.log}).fn(p.dim(` @-file: ${I}`));let H=j.length>0||e.attachments.length>0?KH(e.text,e.attachments,void 0,j):e.text,M=t.sendMessageStream(H);if(await Qs((I,F)=>{A.process(I,F)},async()=>{for await(let I of M){if(h||y)break;if(I.type==="chunk"&&I.chunk.type==="content"?(l+=I.chunk.content,d=!0):I.type==="message"&&!d&&(l=I.message.content),I.type==="stream_retry"&&(l=l.slice(0,c)),I.type==="chunk"&&I.chunk.type==="tool_use_detail"){let F=I.chunk,_={toolName:F.toolName,toolUseId:F.toolUseId,input:F.toolInput,...F.toolInputRaw!==void 0&&{inputRaw:F.toolInputRaw}};k.set(F.toolUseId,_),T.push(_)}else if(I.type==="chunk"&&I.chunk.type==="tool_result"){let F=I.chunk;c=l.length;let _=k.get(F.toolUseId);if(_&&(_.result=F.content,_.isError=F.isError,k.delete(F.toolUseId)),r.onContextProgress){let U=Date.now();if(U-w>=S){w=U;try{let K=r.onContextProgress();K instanceof Promise&&await K}catch(K){qe()&&console.error(" "+p.error("onContextProgress (status refresh) failed:"),K)}}}}if(I.type==="paused"){if(r.setPausedState?.(!0),await P(),E&&I.autoResume===!0){let F=new AbortController;b.abort=F;let _=I.resetsAt?I.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,U=_?`Keep waiting \u2014 auto-resumes at ${_}`:"Keep waiting \u2014 auto-resume in progress",K="Switch model / provider (type /model after)",ee="Stop waiting",Q=[p.warning(" \u23F3 Usage limit reached.")+(_?p.dim(` Auto-resumes at ${_}.`):""),p.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];mr(E,{header:Q,options:[U,K,ee],signal:F.signal,initialIndex:0}).then(se=>{if(b.abort=null,!se)return;let q=se[0];q===void 0||q===U||(y=!0,q===K&&(i??{fn:console.log}).fn(p.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(ce=>{qe()&&console.error(" "+p.error("picker pause-interrupt session.interrupt() failed:"),ce)}))}).catch(se=>{qe()&&console.error(" "+p.error("picker promise rejected:"),se)})}else(i??{fn:console.log}).fn(FA({reason:I.reason,...I.resetsAt!==void 0?{resetsAt:I.resetsAt}:{},...I.accountId!==void 0?{accountId:I.accountId}:{},...I.autoResume!==void 0?{autoResume:I.autoResume}:{}}));continue}if(I.type==="resumed"){r.setPausedState?.(!1),b.abort?.abort(),b.abort=null;let F=I.hotSwapped&&I.accountId?`\u25B6 Resumed on ${I.accountId}`:"\u25B6 Resumed";l="",c=0,d=!1,T.length=0,k.clear(),f=!1,g=void 0,u=!1,A=O(),m=!1,await B(),(i??{fn:console.log}).fn(p.success(F));continue}if(I.type==="error"){await P(),$s(Cs(I.error)),u=!0;continue}A.process(I),I.type==="done"&&(f=!0,g=I.metadata)}}),await P(),h){let I=i?i.fn:console.log,F=E?E.getPendingCount():0,_=F>0?` \xB7 ${F} queued`:"";I(p.warning(`\u23F8 Stopped${_} \u2014 work so far kept.`)+p.dim(" Send a message to continue.")),I("")}if(y){let I=i?i.fn:console.log;I(p.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),I("")}if(f&&!h&&!y){Hi(n,a,l,g,T),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),dl(process.stdout),mN(process.stdout,"afk: turn complete");let I=_=>{i?i.fn(_):console.log(_)},F=Jy(l);if(F){I(WH(F)),I("");let _=NN(T);if(r.onTerminalState)try{r.onTerminalState(F,{doneHasCorroboratingEvidence:_})}catch{}if(n.permissionMode==="autonomous"){let U=F.kind==="done"&&Cc().verifyDone===!0&&!_;UN(F,void 0,{unverified:U})}}if(zde(g,n,I),r.onAfterTurn){let _=r.onAfterTurn();_ instanceof Promise&&await _.catch(()=>{})}}}catch(j){await P(),u||$s(Cs(j))}finally{await P(),ul(process.stdout,Qd(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 qde(e,t){let n=Math.round(e*100),r=pe(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${pe(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 zde(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(xe(e.durationMs)),e.totalCostUsd!==void 0&&r.push(dt(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(pe(o+i)+" tok"),r.length>0&&n(p.dim(" \u25E6 "+r.join(" \xB7 ")));let s=HT(t),a=Vt(t.model),l=qde(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 Jde=5e3,Yde=3,Vde="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function Xde(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 zH(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=>{qe()&&(f=Rh(D)),await Ru(e.session.current),qe()&&(g=ZE())}).catch(()=>{});let h=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,y,b=!1,w=!1,S,T,k,C=0;for(m.onInjectable=()=>{C>=Yde||!o.isAwaitingInput()||!o.bufferIsEmpty()||(C++,dl(process.stdout),h={text:Vde,attachments:[]},o.abortPendingRead())};;){if(f&&(e.replRenderer.writeLine(f),e.replRenderer.writeLine(""),f=null),g.length>0){for(let M of g)e.replRenderer.writeLine(M);e.replRenderer.writeLine(""),g=[]}let D=u.drainNotifications();for(let{job:M,result:N}of D){let I=N.errorReason===void 0?"\u2713":"\u2717",F=N.errorReason==="abort"?"killed":N.errorReason==="timeout"?"timed out":N.errorReason==="signal-killed"?"killed by signal":`exit ${N.exitCode??0}`,_=Math.max(0,Math.round(N.durationMs/100)/10);e.replRenderer.writeLine(p.dim(` ${I} [${M.id}] ${F} \xB7 ${_}s \xB7 `)+M.command)}let E=m.drainNotifications();for(let{job:M}of E){let N=M.status==="completed"?"\u2713":M.status==="failed"?"\u2717":"\u2298",I=M.endedAt!==void 0?Math.max(0,Math.round((M.endedAt-M.startedAt)/100)/10):0,F=M.label.length>60?`${M.label.slice(0,60)}\u2026`:M.label;e.replRenderer.writeLine(p.dim(` ${N} [${M.jobId}] subagent ${M.status} \xB7 ${I}s \xB7 `)+F)}let O=l.renderIfChanged(e.stats.sessionId);if(O.length>0){for(let M of O)e.replRenderer.writeLine(M);e.replRenderer.writeLine("")}let A,P;if(h===void 0){let M=await e.session.current.takePendingPlanExitSeed();M!==void 0&&(e.stats.permissionMode=M.mode,h={text:M.message,attachments:[]})}if(h!==void 0){let M=h;h=void 0;let N=$l(e.stats.permissionMode),I=Xi({buffer:M.text,promptText:N,isTTY:!!process.stdout.isTTY,attachmentSummary:Sl([...M.attachments])});e.replRenderer.writeLine(I),A=M.text.trim(),P=M.attachments}else{let M=y;y=void 0;let N=await o.readLine({promptFn:()=>$l(e.stats.permissionMode),...M!==void 0?{initialBuffer:M}:{},onSigint:r,onShiftTab:()=>{Ky(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});A=N.text.trim(),P=N.attachments}if(!A&&P.length===0)continue;if(A.startsWith("!")){let M=/^(0|false|off|no)$/i.test(v.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!M&&(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 B=!1;if(A.startsWith("/")){let M=await xN(A,e.slashCtx,P);if(M.handled){if(M.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),M.result!==null&&typeof M.result=="object"&&"kind"in M.result&&M.result.kind==="submit"){h={text:M.result.message,attachments:P??[]},e.statusLine.rearm();continue}if(M.result!==null&&typeof M.result=="object"&&"kind"in M.result&&M.result.kind==="prefill"){y=M.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}B=!0}a.push(A),await Xde(e,A);let j=A;if(B){let M=jT(A);if(M){let N=M.name.replace(/^\//,"").split(":").pop()??"";if(N&&YE(N)){let I={skillName:N,rawArgs:M.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},F=e.session.current.sessionId,_=as(F),U=Date.now();W(`[afk trace] preflight.start commandName=${N}`);let K=!1,ee=await ss(I,{cwd:e.stats.cwd??process.cwd(),artifactDir:_},Q=>{qe()&&e.replRenderer.writeLine(p.warning(`\u26A0 preflight(${N}) failed: `)+(Q instanceof Error?Q.message:String(Q)))});K=ee!==null,W(`[afk trace] preflight.end commandName=${N} durationMs=${Date.now()-U} success=${K}`),j=XE(ee?.manifestBlock,A)}}}let $=u.drainInjections();$.length>0&&(j=$+j);let H=m.drainInjections();if(H.length>0&&(j=H+j),S!==void 0&&(j=S+`
|
|
1763
1763
|
|
|
1764
1764
|
`+j,S=void 0),e.hookRegistry)try{let M={event:"UserPromptSubmit",prompt:j,sessionId:e.stats.sessionId},N=await e.hookRegistry.dispatch(M);N.injectContext&&(j=N.injectContext+j)}catch(M){if(M instanceof ve){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+(M.reason?p.dim(`: ${Ir(M.reason)}`):"")),e.statusLine.rearm();continue}if(M instanceof Vn){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+p.dim(`: handler timed out after ${M.timeoutMs}ms`)),e.statusLine.rearm();continue}throw M}if(T=void 0,k=void 0,await qH({text:j,attachments:P},e.session.current,e.stats,{setInFlight(M){n.turnInFlight=M},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(M){await t.appendUser(M)},async onTurnComplete(M,N){if(await t.appendTurn(M,N),e.stats.sessionId)try{Oo(e.stats)}catch(I){w||(w=!0,e.replRenderer.writeLine(p.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(I instanceof Error?I.message:String(I))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(M,N)=>{d?.push(M),T=M.kind,k=N?.doneHasCorroboratingEvidence},setActiveCompositor:M=>{n.activeCompositor=M},setInterruptNotifier:M=>{n.notifyInterrupting=M},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:M=>o.setBackgroundHandler(M),setSoftStopHandler:i,setPausedState:M=>o.setPausedState(M),setPauseInterruptHandler:M=>o.setPauseInterruptHandler(M),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(Nn(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:M=>c.repaint(M)}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs($l(e.stats.permissionMode))),e.hookRegistry)try{let M=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...T!==void 0?{terminalState:T}:{},...k!==void 0?{doneHasCorroboratingEvidence:k}:{}},void 0,Jde);M.injectContext&&M.injectContext.trim().length>0&&(S=M.injectContext)}catch(M){if(M instanceof mt)throw M;M instanceof Vn?(W("[stop hook] handler timed out"),e.completionWriter.fn(p.dim(" [stop hook] timed out"))):M instanceof ve?e.completionWriter.fn(p.dim(` [stop hook] blocked: ${Ir(M.reason??"no reason given")}`)):W("[stop hook] unexpected error: "+String(M))}}}function Qde(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 JH(e,t,n,r){let o=await AH(),i=new Wy({rl:e.rl,history:o,statusLine:e.statusLine}),s=Qde(v.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await MH(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar});a=HH(e,n),await zH(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)}}Ec();ca();import{execFile as Zde}from"node:child_process";import{dirname as eue,isAbsolute as tue,resolve as nue}from"node:path";import{promisify as rue}from"node:util";var YH=rue(Zde),oue=3e3,iue=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function sue(){let t=(await YH("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=tue(t)?t:nue(process.cwd(),t);return eue(n)}async function VH(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await sue()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),oue)});try{let o=mn({execFile:YH,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=>iue.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}_p();Ec();import{promises as aue}from"node:fs";import{dirname as lue,join as ZH}from"node:path";import{randomBytes as cue}from"node:crypto";var due=["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(`
|
|
1765
|
-
`),XH=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Tx=30,uue=1024,pue=8e3,mue="haiku";async function fue(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=bue(n,uue),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??pue),s=t.signal?wue([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await js({token:t.token,model:t.model??mue,system:due,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=gue(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=lue(t.worktreePath);return await hue(l,c)}function gue(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(XH.test(t)&&t.length<=Tx)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>Tx)break;o=s}return XH.test(o)?o:null}async function hue(e,t){if(!await yue(ZH(t,e)))return e;let n=cue(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Tx-5)}-${n}`}async function yue(e){try{return await aue.access(e),!0}catch{return!1}}function bue(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 wue(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 eW(e){let t,n,r=ZH(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await fue(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=`${jp(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return QH(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 QH(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 QH(e,t){e&&e.setCwd(t),Sue(t)}function Sue(e){try{process.chdir(e)}catch{}}Kt();z();import{spawn as nW}from"child_process";import{existsSync as rW,mkdirSync as xue,readFileSync as oW,unlinkSync as tW,writeFileSync as iW}from"fs";import{get as Rue}from"https";import{join as sW}from"path";import{readFileSync as vue}from"fs";import{dirname as kue,join as Tue}from"path";import{fileURLToPath as Eue}from"url";function br(){try{return"5.82.
|
|
1765
|
+
`),XH=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Tx=30,uue=1024,pue=8e3,mue="haiku";async function fue(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=bue(n,uue),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??pue),s=t.signal?wue([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await js({token:t.token,model:t.model??mue,system:due,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=gue(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=lue(t.worktreePath);return await hue(l,c)}function gue(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(XH.test(t)&&t.length<=Tx)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>Tx)break;o=s}return XH.test(o)?o:null}async function hue(e,t){if(!await yue(ZH(t,e)))return e;let n=cue(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Tx-5)}-${n}`}async function yue(e){try{return await aue.access(e),!0}catch{return!1}}function bue(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 wue(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 eW(e){let t,n,r=ZH(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await fue(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=`${jp(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return QH(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 QH(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 QH(e,t){e&&e.setCwd(t),Sue(t)}function Sue(e){try{process.chdir(e)}catch{}}Kt();z();import{spawn as nW}from"child_process";import{existsSync as rW,mkdirSync as xue,readFileSync as oW,unlinkSync as tW,writeFileSync as iW}from"fs";import{get as Rue}from"https";import{join as sW}from"path";import{readFileSync as vue}from"fs";import{dirname as kue,join as Tue}from"path";import{fileURLToPath as Eue}from"url";function br(){try{return"5.82.12"}catch{}try{let e=kue(Eue(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(vue(Tue(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}G();var Aue=64*1024,Cue=10800*1e3,_ue=800,Iue=3600*1e3,Pue="update-check.json",Mue="pending-update.json";function Ex(){return sW(xs(),Pue)}function Mu(){return sW(xs(),Mue)}function xx(){let e=xs();rW(e)||xue(e,{recursive:!0})}function aW(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 lW(){try{let e=oW(Ex(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function cW(){try{xx();let e=`
|
|
1766
1766
|
const https = require('https');
|
|
1767
1767
|
const fs = require('fs');
|
|
1768
1768
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var Xb=Object.defineProperty;var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var Kc=(t,e)=>{for(var n in e)Xb(t,n,{get:e[n],enumerable:!0})};function no(t){return to.find(e=>e.name===t)}function Vi(t){return process.env[t]!==void 0}var to,b,N=be(()=>{"use strict";to=[{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-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-5",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 on every AFK surface \u2014 the CLI entrypoint reports surface `afk`, which is in the headless set \u2014 so watching the agent work in a visible window is opt-in via `AFK_BROWSER_HEADLESS=0`, not implied by running the REPL. Note headed and headless use different chromium downloads (`chromium-*` vs `chromium_headless_shell-*`).",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, and that the bash-restriction hook refuses to let a shell command reference on interactive surfaces (REPL, Telegram) \u2014 on headless surfaces (afk chat, daemon) bash fails open regardless of this list. A leading ~/ is expanded (~user/ is not \u2014 spell those absolutely). Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed. One built-in exception exists: ~/.afk/config/mcp.json (the MCP registry) IS readable \u2014 paths listed here outrank that carve-out, so set this to ~/.afk/config/mcp.json if your registry holds inline secrets rather than ${VAR} placeholders.",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 to){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(b,e.name);n&&Object.defineProperty(b,e.name,{...n,enumerable:!1})}})()});function Qb(){return b.AFK_DEBUG==="1"||b.DEBUG==="1"}function C(...t){Qb()&&console.log(...t)}var re=be(()=>{"use strict";N()});import{existsSync as Ad,mkdirSync as kw,renameSync as _w,cpSync as Aw,rmSync as Ew}from"fs";import{join as W,dirname as da,basename as Tw,isAbsolute as Td}from"path";import{homedir as xd}from"os";import{fileURLToPath as xw}from"url";function oe(){let t=b.AFK_HOME;if(t!==void 0&&t!==""){if(!Td(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return W(xd(),".afk")}function $e(){return W(oe(),"agent-framework")}function go(){return W($e(),"forge-telemetry.jsonl")}function Rd(){return W($e(),"briefs")}function Id(){return W($e(),"facets")}function $n(){return W(oe(),"skills")}function Qt(){return W(oe(),"plugins")}function Cd(t=process.cwd()){return W(t,".afk")}function Pd(t=process.cwd()){return W(Cd(t),"skills")}function Md(t=process.cwd()){return W(Cd(t),"plugins")}function Od(t=process.cwd()){return W(t,".afk","plans")}function ho(){return W(Qt(),".index.json")}function ua(){return W(Bn(),"schedules.json")}function Dd(){let t=xw(import.meta.url),e=da(t);return W(e,"bundled-plugins")}function Bn(){return W(oe(),"config")}function he(){let t=b.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Td(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return W(oe(),"state")}function Se(){return W(he(),"sessions")}function yo(){return W(he(),"presence")}function bo(){return W(he(),"memory")}function wo(){return W(he(),"session-grants.jsonl")}function Fd(){return W(oe(),"farms")}function Ld(t){return W(Fd(),t)}function So(t){if(!Rw.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function Nd(t){return So(t),W(he(),"witness",t)}function Ud(t){return!t||t.startsWith("in-memory:")?null:Tw(da(t))}function $d(t="default"){return W(he(),"daemon",`agent-afk@${t}`)}function Bd(){return W(he(),"worktree-sweep.lock")}function pa(){return W(Bn(),"afk.env")}function Zt(){return W(Bn(),"afk.config.json")}function vo(){return W(xd(),".afk.config.json")}function Iw(){return W(oe(),"sessions")}function Cw(t,e){if(t!==e&&Ad(t)&&!Ad(e))try{kw(da(e),{recursive:!0});try{_w(t,e)}catch(n){if(n.code==="EXDEV")try{Aw(t,e,{recursive:!0}),Ew(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
|
|
2
2
|
`)}}}catch{}}function Hd(){Cw(Iw(),Se())}function fa(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>Ed)throw new Error(`Invalid browser profile: exceeds ${Ed} chars`);if(!Pw.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function Mw(){return W(he(),"browser")}function Ow(t){return fa(t),W(Mw(),t)}function ma(t){return W(Ow(t),"storageState.json")}function Hn(t){return typeof t=="string"&&t.length>0&&t.length<=Fw&&Dw.test(t)}function jn(t){if(!Hn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return W(Se(),t)}function ko(t){return W(jn(t),"events.jsonl")}function jd(t){return W(jn(t),"session.key")}var Rw,Pw,Ed,Dw,Fw,H=be(()=>{"use strict";N();Rw=/^[a-zA-Z0-9_-]+$/;Pw=/^[A-Za-z0-9_-]+$/,Ed=128;Dw=/^[A-Za-z0-9_-]+$/,Fw=128});import{readFileSync as Q_}from"node:fs";import{join as Z_}from"path";function eA(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Hp(t,e){return eA(e).test(t)}function rA(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(tA.has(e))return!0;if(nA.has(e))return!1}return!1}function jp(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function oA(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 Kp(t){let e=t===void 0||t.trim()===""?"default":t.trim();return fa(e),e}function sA(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function iA(t){try{return Q_(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function aA(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=Kp(e.defaultProfile)),n}function Wp(t){let e=t?.env??b,n=t?.readFileSync??iA,r=t?.surface??e.AGENT_SURFACE,o=rA(e.AFK_BROWSER_HEADLESS,r),s=jp(e.AFK_BROWSER_ALLOWED_DOMAINS),i=jp(e.AFK_BROWSER_BLOCKED_DOMAINS),a=sA(e.AFK_BROWSER_DOM_SNAPSHOTS),l=oA(e.AFK_BROWSER_BACKEND),c=Kp(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():Z_(Bn(),"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=aA(d,m);return g.configPath=p,g}function os(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(Hp(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Hp(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var tA,nA,ss=be(()=>{"use strict";N();H();tA=new Set(["daemon","subagent","telegram","afk"]),nA=new Set(["repl","interactive","cli"])});import{existsSync as lA,readFileSync as cA}from"node:fs";import{createRequire as dA}from"node:module";import{dirname as uA,join as pA}from"node:path";function zp(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<mA&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function ye(t){let e=zp(t);return qp.some(n=>e.includes(n))}function gA(){try{let e=dA(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(cA(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=pA(uA(e),o);return lA(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function pr(){return Gp??=gA()??fA,Gp}function Qa(t){return t.includes("install chromium")}function Ce(t,e){let n=zp(t),r=e?.latched===!0?` ${hA}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${pr()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${pr()}). Or pick a different tool.${r}`}function Za(t,e,n=!1){if(!ye(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
3
3
|
|
|
4
|
-
${Ce(t,{headless:e,latched:n})}`,{cause:t})}var qp,fA,mA,Gp,hA,el=be(()=>{"use strict";qp=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],fA="pnpm exec playwright install chromium",mA=4;hA="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Dt from"node:fs";import is from"node:path";import{randomBytes as yA}from"node:crypto";import{chromium as bA}from"playwright";function wA(){try{return"5.82.11"}catch{}try{let t=is.resolve(import.meta.dirname,"../../../package.json"),e=Dt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var SA,as,Jp=be(()=>{"use strict";el();H();re();SA=wA(),as=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=bA.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Za(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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){this.clearLaunchFailure();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.clearLaunchFailure(),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/${SA}`}}loadStorageState(e){let n=ma(e);try{if(!Dt.existsSync(n))return;let r=JSON.parse(Dt.readFileSync(n,"utf8"));return C("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){C("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=ma(e);if(!Dt.existsSync(r))return;let o=await n.storageState(),s=is.join(is.dirname(r),`.${is.basename(r)}.${process.pid}.${yA(4).toString("hex")}.tmp`);Dt.writeFileSync(s,JSON.stringify(o),{mode:384}),Dt.chmodSync(s,384),Dt.renameSync(s,r),C("[browser/vault] saved session",{profile:e,file:r})}catch(r){C("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as vA}from"crypto";function Yp(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&kA.test(t.label))}function Vp(t){return vA("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Xp(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var kA,ls=be(()=>{"use strict";kA=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as _A}from"node:crypto";function AA(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function EA(t,e,n){return`el_${_A("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function TA(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Qp(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ef(t,e){let n=t.role??"",r=t.name??"";Zp.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ef(s,e)}async function xA(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},tf).catch(()=>[])}async function RA(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},tf).catch(()=>[])}function IA(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function cs(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=IA(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=xA(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=[],ef(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await RA(t)).filter(z=>Zp.has(z.role??"")));let w=new Map;for(let R of p){let z=Qp(R.name),J=w.get(z);(!J||J.bbox.w===0&&R.bbox.w>0)&&w.set(z,R)}let E=h.map(R=>({ax:R,dom:w.get(Qp(R.name??""))})),v=r?E:E.filter(R=>R.dom?R.dom.bbox.w>0||R.dom.bbox.h>0:!0);v.sort((R,z)=>{let J=R.dom?.bbox.y??0,_=z.dom?.bbox.y??0;if(J!==_)return J-_;let O=R.dom?.bbox.x??0,P=z.dom?.bbox.x??0;return O-P}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=v.slice(0,n).map((R,z)=>{let J=R.ax.role??"generic",_=R.ax.name??"",O=EA(J,_,z),P=R.dom?.bbox??{x:0,y:0,w:0,h:0},x=R.dom?.type??null,B=null;R.ax.value!==void 0&&R.ax.value!==null&&(B=String(R.ax.value)),R.ax.checked!==void 0&&(B=String(R.ax.checked)),Yp({role:J,kind:x})&&(B="[redacted]");let L={disabled:R.ax.disabled??!1};R.ax.checked!==void 0&&(L.checked=R.ax.checked===!0||R.ax.checked==="mixed"),R.ax.selected!==void 0&&(L.selected=R.ax.selected),R.ax.expanded!==void 0&&(L.expanded=R.ax.expanded);let D;R.dom?.testId?D=`[data-testid="${R.dom.testId}"]`:R.dom?.id&&(D=`#${R.dom.id}`);let F={id:O,role:J,label:AA(_),kind:x,value:B,state:L,bbox:P};return D!==void 0&&(F.selector=D),F}),I="idle";try{let R=await t.evaluate(()=>document.readyState);R==="loading"?I="loading":R==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="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 S=TA(f),M=`obs_${e.observationCounter.toString(36)}`,j=new Date().toISOString();return{observationId:M,url:m,title:g,textSummary:S,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:j}}var Zp,tf,nf=be(()=>{"use strict";ls();Zp=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);tf="a[href], button, input, select, textarea, [role], [tabindex], label"});async function rf(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 tl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>rf(t,s)))).filter(o=>o!==null)}async function CA(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 nl(t,e,n){switch(e.kind){case"element_id":return PA(t,e,n);case"selector":return MA(t,e);case"semantic":return OA(t,e)}}async function PA(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 tl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function MA(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 tl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function OA(t,e){return e.role!==void 0?DA(t,e.text,e.role):FA(t,e.text,e)}async function DA(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 tl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function FA(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 CA(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 rf(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,E=0;for(let v=0;v<w.length;v++)E=E*31+w.charCodeAt(v)>>>0;f.push({...y,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var of=be(()=>{"use strict"});async function rl(t,e,n,r){let o=t.url();if(o===n)return null;let s=os(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var sf=be(()=>{"use strict";ss()});import{randomBytes as LA}from"crypto";import{mkdir as NA,stat as UA,writeFile as $A}from"fs/promises";import{join as ol}from"path";import{gzip as BA}from"zlib";import{promisify as HA}from"util";function jA(t){return ol(Nd(t),"browser")}function KA(t){return ol(jA(t),"screenshots")}function WA(){return new Date().toISOString().replace(/[:.]/g,"-")}function GA(){return LA(3).toString("hex")}async function sl(t,e,n){if(e.length>af)throw new Error(`writeScreenshotSidecar: buffer exceeds ${af} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=KA(t);await NA(r,{recursive:!0});let o=`${WA()}-${GA()}-${n}.png`,s=ol(r,o);await $A(s,e);let{size:i}=await UA(s);return{path:s,bytes:i}}var ZU,af,lf=be(()=>{"use strict";H();ls();ZU=HA(BA);af=5*1024*1024});var df={};Kc(df,{PlaywrightProvider:()=>il});function cf(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 il,uf=be(()=>{"use strict";Jp();nf();of();ss();sf();lf();il=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new as(e)}async open(e){let n=os(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(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await rl(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await cs(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,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}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 cs(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 nl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${cf(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":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=await rl(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await cs(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 nl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${cf(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 sl(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 sl(n,o,r);return s}catch{return null}}}});var Lt={};Kc(Lt,{__resetBrowserRegistryForTests:()=>VA,browserProviderActive:()=>JA,closeBrowserProvider:()=>al,getBrowserProvider:()=>zA,peekBrowserProvider:()=>YA});function pf(){Promise.resolve(al()).then(()=>{process.exit(130)})}function ff(){Promise.resolve(al()).then(()=>{process.exit(143)})}function mf(){je=null}function qA(){ds||(process.on("SIGINT",pf),process.on("SIGTERM",ff),process.on("exit",mf),ds=!0)}function gf(){ds&&(process.removeListener("SIGINT",pf),process.removeListener("SIGTERM",ff),process.removeListener("exit",mf),ds=!1)}async function zA(t){return je!==null?je:(Ft!==null||(Ft=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(uf(),df)),n=Wp(t),r=new e(n);return qA(),je=r,Ft=null,r})()),Ft)}async function al(){if(je===null)return;let t=je;je=null,Ft=null,gf(),await t.shutdown()}function JA(){return je!==null}function YA(){return je}function VA(){je=null,Ft=null,gf()}var je,Ft,ds,Nt=be(()=>{"use strict";ss();je=null,Ft=null,ds=!1});re();var Ee=class extends Error{constructor(e){super(e),this.name="AbortError"}},Te=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},ro=class extends Te{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},q=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},Ne=class extends Error{constructor(e){super(e),this.name="StreamIncompleteError"}},st=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},qt=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}};re();async function zt(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){C(`trace.emit tool_call failed: ${Ge(n)}`)}}async function it(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){C(`trace.emit hook_decision failed: ${Ge(n)}`)}}async function kt(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){C(`trace.emit subagent_lifecycle failed: ${Ge(n)}`)}}async function Wc(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){C(`trace.emit budget failed: ${Ge(n)}`)}}async function Gc(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){C(`trace.emit abort failed: ${Ge(n)}`)}}async function oo(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){C(`trace.emit compaction failed: ${Ge(n)}`)}}async function qc(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){C(`trace.emit closure failed: ${Ge(n)}`)}}async function ce(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){C(`trace.emit browser_event failed: ${Ge(n)}`)}}async function G(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){C(`trace.emit session_phase failed: ${Ge(n)}`)}}function Ge(t){return t instanceof Error?t.message:String(t)}import py from"@anthropic-ai/sdk";var Jc="extended-cache-ttl-2025-04-11",zc=`claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,${Jc}`,Zb="effort-2025-11-24",ew="claude-cli/1.0.0 (external, cli)",tw="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function so(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function On(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 at(t,e,n,r,o){return t!=="oauth"?o===!0?{"anthropic-beta":Jc}:{}:{"anthropic-beta":r?`${zc},${Zb}`:zc,"x-app":"cli","User-Agent":ew,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Yc(t){return t!=="oauth"?null:[{type:"text",text:tw}]}import sw from"@anthropic-ai/sdk";N();var Dn=["local","small","medium","large"],Xc="claude-haiku-4-5-20251001",Qi="claude-sonnet-5",Zi="claude-opus-5",ta="claude-fable-5",_t={local:{id:""},small:{id:Xc},medium:{id:Qi},large:{id:Zi}},Qc="auto",na={opus:Zi,opus_1m:Zi,sonnet:Qi,sonnet_1m:Qi,haiku:Xc,fable:ta},Yt=[...Dn,...Object.keys(na)],ea;function ra(t){ea=t}function Xi(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function io(t,e,n){let r={},o=Xi(t);o&&(r.id=o);let s=Xi(e);s&&(r.baseUrl=s);let i=Xi(n);return i&&(r.apiKey=i),r}function nw(){return{local:io(b.AFK_MODEL_LOCAL,b.AFK_MODEL_LOCAL_BASE_URL,b.AFK_MODEL_LOCAL_API_KEY),small:io(b.AFK_MODEL_SMALL,b.AFK_MODEL_SMALL_BASE_URL,b.AFK_MODEL_SMALL_API_KEY),medium:io(b.AFK_MODEL_MEDIUM,b.AFK_MODEL_MEDIUM_BASE_URL,b.AFK_MODEL_MEDIUM_API_KEY),large:io(b.AFK_MODEL_LARGE,b.AFK_MODEL_LARGE_BASE_URL,b.AFK_MODEL_LARGE_API_KEY)}}function Zc(t){let e=nw(),n={};for(let r of Dn){let o=_t[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 Vt(t){return t||ea||Zc()}function Xt(t,e=Vt()){let n=t.trim().toLowerCase();if(!(!n||n===Qc)){for(let r of Dn){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 At(t,e=Vt()){if(t===void 0)return{id:""};let n=Xt(t,e);if(n)return e[n];let r=na[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function lt(t,e=Vt()){if(t!==void 0)return At(t,e).id}function ed(t,e=Vt()){if(t===void 0)return;let n=Xt(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function td(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Dn){let o=ow(n[r]);o&&(e[r]=o)}return e}function nd(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 Jt(t){return typeof t=="string"?t.trim():""}function Vc(t){return/[\x00-\x1f\x7f]/.test(t)}var rw=new Set([...Dn,Qc,...Object.keys(na)]);function ow(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=Jt(e.id);if(!n)return;let r={id:n},o=Jt(e.name);o&&(r.name=o);let s=nd(e.provider);s&&(r.provider=s);let i=Jt(e.baseUrl);i&&(r.baseUrl=i);let a=Jt(e.apiKey);return a&&(r.apiKey=a),r}}function rd(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=Jt(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(Vc(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=Jt(e.name);if(o){if(Vc(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(rw.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=nd(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 oa={opus:_t.large.id,opus_1m:_t.large.id,sonnet:_t.medium.id,sonnet_1m:_t.medium.id,haiku:_t.small.id,fable:ta};function ao(t){return t in oa}function me(t){return lt(t)}import{randomUUID as od}from"node:crypto";async function sd(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=so(e),c=On(e,l),d=a?a(c):new sw(c),u=od(),p=od(),f=at(l,u,p),m=me(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 E of h.content)E.type==="text"&&y.push(E.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 id}from"child_process";import{existsSync as iw,readFileSync as aw,writeFileSync as lw}from"fs";import{homedir as ad,userInfo as ld}from"os";import{join as cd}from"path";var cw="9d1c250a-e61b-44d9-88ed-5944d1962f5e",dw="https://platform.claude.com/v1/oauth/token",uw=300*1e3;function we(){let t=dd();if(t===void 0)return;let e=ud(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 sa(){let t=dd();if(t===void 0)return;let e=ud(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+uw)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 pw(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}:{}},fw(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
4
|
+
${Ce(t,{headless:e,latched:n})}`,{cause:t})}var qp,fA,mA,Gp,hA,el=be(()=>{"use strict";qp=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],fA="pnpm exec playwright install chromium",mA=4;hA="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Dt from"node:fs";import is from"node:path";import{randomBytes as yA}from"node:crypto";import{chromium as bA}from"playwright";function wA(){try{return"5.82.12"}catch{}try{let t=is.resolve(import.meta.dirname,"../../../package.json"),e=Dt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var SA,as,Jp=be(()=>{"use strict";el();H();re();SA=wA(),as=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=bA.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Za(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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){this.clearLaunchFailure();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.clearLaunchFailure(),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/${SA}`}}loadStorageState(e){let n=ma(e);try{if(!Dt.existsSync(n))return;let r=JSON.parse(Dt.readFileSync(n,"utf8"));return C("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){C("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=ma(e);if(!Dt.existsSync(r))return;let o=await n.storageState(),s=is.join(is.dirname(r),`.${is.basename(r)}.${process.pid}.${yA(4).toString("hex")}.tmp`);Dt.writeFileSync(s,JSON.stringify(o),{mode:384}),Dt.chmodSync(s,384),Dt.renameSync(s,r),C("[browser/vault] saved session",{profile:e,file:r})}catch(r){C("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as vA}from"crypto";function Yp(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&kA.test(t.label))}function Vp(t){return vA("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Xp(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var kA,ls=be(()=>{"use strict";kA=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as _A}from"node:crypto";function AA(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function EA(t,e,n){return`el_${_A("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function TA(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Qp(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ef(t,e){let n=t.role??"",r=t.name??"";Zp.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ef(s,e)}async function xA(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},tf).catch(()=>[])}async function RA(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},tf).catch(()=>[])}function IA(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function cs(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=IA(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=xA(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=[],ef(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await RA(t)).filter(z=>Zp.has(z.role??"")));let w=new Map;for(let R of p){let z=Qp(R.name),J=w.get(z);(!J||J.bbox.w===0&&R.bbox.w>0)&&w.set(z,R)}let E=h.map(R=>({ax:R,dom:w.get(Qp(R.name??""))})),v=r?E:E.filter(R=>R.dom?R.dom.bbox.w>0||R.dom.bbox.h>0:!0);v.sort((R,z)=>{let J=R.dom?.bbox.y??0,_=z.dom?.bbox.y??0;if(J!==_)return J-_;let O=R.dom?.bbox.x??0,P=z.dom?.bbox.x??0;return O-P}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=v.slice(0,n).map((R,z)=>{let J=R.ax.role??"generic",_=R.ax.name??"",O=EA(J,_,z),P=R.dom?.bbox??{x:0,y:0,w:0,h:0},x=R.dom?.type??null,B=null;R.ax.value!==void 0&&R.ax.value!==null&&(B=String(R.ax.value)),R.ax.checked!==void 0&&(B=String(R.ax.checked)),Yp({role:J,kind:x})&&(B="[redacted]");let L={disabled:R.ax.disabled??!1};R.ax.checked!==void 0&&(L.checked=R.ax.checked===!0||R.ax.checked==="mixed"),R.ax.selected!==void 0&&(L.selected=R.ax.selected),R.ax.expanded!==void 0&&(L.expanded=R.ax.expanded);let D;R.dom?.testId?D=`[data-testid="${R.dom.testId}"]`:R.dom?.id&&(D=`#${R.dom.id}`);let F={id:O,role:J,label:AA(_),kind:x,value:B,state:L,bbox:P};return D!==void 0&&(F.selector=D),F}),I="idle";try{let R=await t.evaluate(()=>document.readyState);R==="loading"?I="loading":R==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="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 S=TA(f),M=`obs_${e.observationCounter.toString(36)}`,j=new Date().toISOString();return{observationId:M,url:m,title:g,textSummary:S,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:j}}var Zp,tf,nf=be(()=>{"use strict";ls();Zp=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);tf="a[href], button, input, select, textarea, [role], [tabindex], label"});async function rf(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 tl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>rf(t,s)))).filter(o=>o!==null)}async function CA(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 nl(t,e,n){switch(e.kind){case"element_id":return PA(t,e,n);case"selector":return MA(t,e);case"semantic":return OA(t,e)}}async function PA(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 tl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function MA(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 tl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function OA(t,e){return e.role!==void 0?DA(t,e.text,e.role):FA(t,e.text,e)}async function DA(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 tl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function FA(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 CA(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 rf(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,E=0;for(let v=0;v<w.length;v++)E=E*31+w.charCodeAt(v)>>>0;f.push({...y,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var of=be(()=>{"use strict"});async function rl(t,e,n,r){let o=t.url();if(o===n)return null;let s=os(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var sf=be(()=>{"use strict";ss()});import{randomBytes as LA}from"crypto";import{mkdir as NA,stat as UA,writeFile as $A}from"fs/promises";import{join as ol}from"path";import{gzip as BA}from"zlib";import{promisify as HA}from"util";function jA(t){return ol(Nd(t),"browser")}function KA(t){return ol(jA(t),"screenshots")}function WA(){return new Date().toISOString().replace(/[:.]/g,"-")}function GA(){return LA(3).toString("hex")}async function sl(t,e,n){if(e.length>af)throw new Error(`writeScreenshotSidecar: buffer exceeds ${af} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=KA(t);await NA(r,{recursive:!0});let o=`${WA()}-${GA()}-${n}.png`,s=ol(r,o);await $A(s,e);let{size:i}=await UA(s);return{path:s,bytes:i}}var ZU,af,lf=be(()=>{"use strict";H();ls();ZU=HA(BA);af=5*1024*1024});var df={};Kc(df,{PlaywrightProvider:()=>il});function cf(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 il,uf=be(()=>{"use strict";Jp();nf();of();ss();sf();lf();il=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new as(e)}async open(e){let n=os(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(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await rl(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await cs(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,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}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 cs(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 nl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${cf(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":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=await rl(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await cs(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 nl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${cf(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 sl(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 sl(n,o,r);return s}catch{return null}}}});var Lt={};Kc(Lt,{__resetBrowserRegistryForTests:()=>VA,browserProviderActive:()=>JA,closeBrowserProvider:()=>al,getBrowserProvider:()=>zA,peekBrowserProvider:()=>YA});function pf(){Promise.resolve(al()).then(()=>{process.exit(130)})}function ff(){Promise.resolve(al()).then(()=>{process.exit(143)})}function mf(){je=null}function qA(){ds||(process.on("SIGINT",pf),process.on("SIGTERM",ff),process.on("exit",mf),ds=!0)}function gf(){ds&&(process.removeListener("SIGINT",pf),process.removeListener("SIGTERM",ff),process.removeListener("exit",mf),ds=!1)}async function zA(t){return je!==null?je:(Ft!==null||(Ft=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(uf(),df)),n=Wp(t),r=new e(n);return qA(),je=r,Ft=null,r})()),Ft)}async function al(){if(je===null)return;let t=je;je=null,Ft=null,gf(),await t.shutdown()}function JA(){return je!==null}function YA(){return je}function VA(){je=null,Ft=null,gf()}var je,Ft,ds,Nt=be(()=>{"use strict";ss();je=null,Ft=null,ds=!1});re();var Ee=class extends Error{constructor(e){super(e),this.name="AbortError"}},Te=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},ro=class extends Te{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},q=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},Ne=class extends Error{constructor(e){super(e),this.name="StreamIncompleteError"}},st=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},qt=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}};re();async function zt(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){C(`trace.emit tool_call failed: ${Ge(n)}`)}}async function it(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){C(`trace.emit hook_decision failed: ${Ge(n)}`)}}async function kt(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){C(`trace.emit subagent_lifecycle failed: ${Ge(n)}`)}}async function Wc(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){C(`trace.emit budget failed: ${Ge(n)}`)}}async function Gc(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){C(`trace.emit abort failed: ${Ge(n)}`)}}async function oo(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){C(`trace.emit compaction failed: ${Ge(n)}`)}}async function qc(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){C(`trace.emit closure failed: ${Ge(n)}`)}}async function ce(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){C(`trace.emit browser_event failed: ${Ge(n)}`)}}async function G(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){C(`trace.emit session_phase failed: ${Ge(n)}`)}}function Ge(t){return t instanceof Error?t.message:String(t)}import py from"@anthropic-ai/sdk";var Jc="extended-cache-ttl-2025-04-11",zc=`claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,${Jc}`,Zb="effort-2025-11-24",ew="claude-cli/1.0.0 (external, cli)",tw="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function so(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function On(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 at(t,e,n,r,o){return t!=="oauth"?o===!0?{"anthropic-beta":Jc}:{}:{"anthropic-beta":r?`${zc},${Zb}`:zc,"x-app":"cli","User-Agent":ew,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Yc(t){return t!=="oauth"?null:[{type:"text",text:tw}]}import sw from"@anthropic-ai/sdk";N();var Dn=["local","small","medium","large"],Xc="claude-haiku-4-5-20251001",Qi="claude-sonnet-5",Zi="claude-opus-5",ta="claude-fable-5",_t={local:{id:""},small:{id:Xc},medium:{id:Qi},large:{id:Zi}},Qc="auto",na={opus:Zi,opus_1m:Zi,sonnet:Qi,sonnet_1m:Qi,haiku:Xc,fable:ta},Yt=[...Dn,...Object.keys(na)],ea;function ra(t){ea=t}function Xi(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function io(t,e,n){let r={},o=Xi(t);o&&(r.id=o);let s=Xi(e);s&&(r.baseUrl=s);let i=Xi(n);return i&&(r.apiKey=i),r}function nw(){return{local:io(b.AFK_MODEL_LOCAL,b.AFK_MODEL_LOCAL_BASE_URL,b.AFK_MODEL_LOCAL_API_KEY),small:io(b.AFK_MODEL_SMALL,b.AFK_MODEL_SMALL_BASE_URL,b.AFK_MODEL_SMALL_API_KEY),medium:io(b.AFK_MODEL_MEDIUM,b.AFK_MODEL_MEDIUM_BASE_URL,b.AFK_MODEL_MEDIUM_API_KEY),large:io(b.AFK_MODEL_LARGE,b.AFK_MODEL_LARGE_BASE_URL,b.AFK_MODEL_LARGE_API_KEY)}}function Zc(t){let e=nw(),n={};for(let r of Dn){let o=_t[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 Vt(t){return t||ea||Zc()}function Xt(t,e=Vt()){let n=t.trim().toLowerCase();if(!(!n||n===Qc)){for(let r of Dn){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 At(t,e=Vt()){if(t===void 0)return{id:""};let n=Xt(t,e);if(n)return e[n];let r=na[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function lt(t,e=Vt()){if(t!==void 0)return At(t,e).id}function ed(t,e=Vt()){if(t===void 0)return;let n=Xt(t,e);if(n&&e[n].id.trim()===""){let r=n.toUpperCase();return`The "${n}" model tier is not configured (no model id). Set AFK_MODEL_${r}=<id> (optionally AFK_MODEL_${r}_BASE_URL / AFK_MODEL_${r}_API_KEY) or "models.${n}" in afk.config.json, then retry.`}}function td(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of Dn){let o=ow(n[r]);o&&(e[r]=o)}return e}function nd(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 Jt(t){return typeof t=="string"?t.trim():""}function Vc(t){return/[\x00-\x1f\x7f]/.test(t)}var rw=new Set([...Dn,Qc,...Object.keys(na)]);function ow(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=Jt(e.id);if(!n)return;let r={id:n},o=Jt(e.name);o&&(r.name=o);let s=nd(e.provider);s&&(r.provider=s);let i=Jt(e.baseUrl);i&&(r.baseUrl=i);let a=Jt(e.apiKey);return a&&(r.apiKey=a),r}}function rd(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=Jt(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(Vc(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=Jt(e.name);if(o){if(Vc(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(rw.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=nd(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 oa={opus:_t.large.id,opus_1m:_t.large.id,sonnet:_t.medium.id,sonnet_1m:_t.medium.id,haiku:_t.small.id,fable:ta};function ao(t){return t in oa}function me(t){return lt(t)}import{randomUUID as od}from"node:crypto";async function sd(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=so(e),c=On(e,l),d=a?a(c):new sw(c),u=od(),p=od(),f=at(l,u,p),m=me(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 E of h.content)E.type==="text"&&y.push(E.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 id}from"child_process";import{existsSync as iw,readFileSync as aw,writeFileSync as lw}from"fs";import{homedir as ad,userInfo as ld}from"os";import{join as cd}from"path";var cw="9d1c250a-e61b-44d9-88ed-5944d1962f5e",dw="https://platform.claude.com/v1/oauth/token",uw=300*1e3;function we(){let t=dd();if(t===void 0)return;let e=ud(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 sa(){let t=dd();if(t===void 0)return;let e=ud(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+uw)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 pw(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}:{}},fw(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
5
5
|
`)}return n.accessToken}function dd(){if(process.platform==="darwin")try{return id("security",["find-generic-password","-s","Claude Code-credentials","-a",ld().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=cd(ad(),".claude",".credentials.json");if(!iw(t))return;try{return aw(t,"utf-8")}catch{return}}}function ud(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 pw(t){try{let e=await fetch(dw,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:cw})});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 Fn(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 fw(t){if(process.platform==="darwin")id("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",ld().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=cd(ad(),".claude",".credentials.json");mw(e,t)}}function mw(t,e){lw(t,e,{encoding:"utf-8",mode:384})}function fe(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 Et(t){let e=fe(t,"retry-after-ms");if(e!==void 0){let r=Number(e);if(Number.isFinite(r)&&r>=0)return r}let n=fe(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 gw=300*1e3;var hw=864e13;function pd(t){if(!Number.isFinite(t)||t<=0)return;let e=t*1e3;if(!(e>hw))return new Date(e)}function lo(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=pd(parseInt(n[1].trim(),10));if(l!==void 0)return{kind:"oauth-limit",resetsAt:l}}let r=fe(t,"anthropic-ratelimit-unified-representative-claim"),o=fe(t,"anthropic-ratelimit-unified-overage-status"),s=fe(t,"anthropic-ratelimit-unified-status");if(r!==void 0||o!==void 0||s==="rejected"){let l=fe(t,"anthropic-ratelimit-unified-reset");if(l!==void 0){let c=pd(Number(l));if(c!==void 0)return{kind:"oauth-limit",resetsAt:c}}return{kind:"oauth-limit-no-ts"}}if(fe(t,"anthropic-ratelimit-requests-remaining")!==void 0||fe(t,"anthropic-ratelimit-requests-limit")!==void 0||fe(t,"anthropic-ratelimit-requests-reset")!==void 0||fe(t,"anthropic-ratelimit-input-tokens-remaining")!==void 0||fe(t,"anthropic-ratelimit-input-tokens-limit")!==void 0||fe(t,"anthropic-ratelimit-input-tokens-reset")!==void 0||fe(t,"anthropic-ratelimit-output-tokens-remaining")!==void 0||fe(t,"anthropic-ratelimit-output-tokens-limit")!==void 0||fe(t,"anthropic-ratelimit-output-tokens-reset")!==void 0)return{kind:"rate-limit-transient",retryAfterMs:Et(t)};let a=Et(t);return a!==void 0&&a<=gw?{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 fd(t){let{resetsAt:e,signal:n,readToken:r=we}=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 md(t){let{signal:e,readToken:n=we,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 yw=new Set([429,503,529]);function ia(t,e=fetch,n,r){return!t&&!n&&!r?e:async(o,s)=>{let i=await e(o,s);if(r)try{r(i.headers)}catch{}if(yw.has(i.status)){let a=Et({headers:i.headers});if(n)try{n({status:i.status,...a!==void 0?{retryAfterMs:a}:{}})}catch{}if(t){let l={status:i.status,reason:i.status===429?"rate-limit":"overloaded",source:"sdk-fetch"};a!==void 0&&(l.retryAfterMs=a),G(t,{phase:"rate_limit",...a!==void 0?{durationMs:a}:{},metadata:l})}}return i}}var co=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}};function gd(t){if(t===null)return;let e=Number(t);if(Number.isFinite(e))return Math.min(1,Math.max(0,e))}var bw=Date.UTC(2100,0,1)/1e3;function hd(t){if(t===null)return;let e=Number(t);if(!(!Number.isFinite(e)||e<0||e>bw))return new Date(e*1e3)}function bd(t){try{let e=gd(t.get("anthropic-ratelimit-unified-5h-utilization")),n=hd(t.get("anthropic-ratelimit-unified-5h-reset")),r=gd(t.get("anthropic-ratelimit-unified-7d-utilization")),o=hd(t.get("anthropic-ratelimit-unified-7d-reset"));return e===void 0&&r===void 0?void 0:{...e!==void 0?{fiveHourUtilization:e}:{},...n!==void 0?{fiveHourResetsAt:n}:{},...r!==void 0?{sevenDayUtilization:r}:{},...o!==void 0?{sevenDayResetsAt:o}:{},observedAt:new Date}}catch{return}}var yd,ww=new Set;function uo(t){return t===void 0?void 0:Math.round(t*100)}function wd(t){let e=yd,n=e===void 0||uo(e.fiveHourUtilization)!==uo(t.fiveHourUtilization)||uo(e.sevenDayUtilization)!==uo(t.sevenDayUtilization);if(yd=t,!!n)for(let r of ww)try{r()}catch{}}import{randomUUID as ay}from"node:crypto";function Ue(t){return t==="bypassPermissions"||t==="autonomous"}N();var Sw="1h";function Ln(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 Nn(){let t=b.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":Sw}function po(t){return Ln(t)&&Nn()==="1h"}function Sd(t,e){if(t.length===0)return t;let n=t[t.length-1],r=kd(n,e);return r===n?t:[...t.slice(0,-1),r]}function vd(t,e){if(t.length===0)return t;let n=t[t.length-1],r=vw(n,e);return r===n?t:[...t.slice(0,-1),r]}function vw(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=kd(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function kd(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var fo=["## 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(`
|
|
6
6
|
`);function aa(t){return t!=="plan"?null:{type:"text",text:fo}}var mo=["## 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(`
|
|
7
7
|
`);function la(t){return t!=="autonomous"?null:{type:"text",text:mo}}function Un(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 _d(t,e){return e.has(t)}function ca(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 P0}from"dotenv";H();N();function _o(){return b.ANTHROPIC_API_KEY||b.CLAUDE_CODE_OAUTH_TOKEN||we()}function ga(){return b.OPENAI_API_KEY||b.CODEX_API_KEY||void 0}function se(t){let e=X(t);return e==="openai-compatible"||e==="openai-codex"?ga():_o()}N();import{readFileSync as Hw,existsSync as jw}from"fs";import{join as Kw}from"path";H();N();import{execFile as Lw}from"node:child_process";import{promisify as Nw}from"node:util";N();H();N();var Z0=Nw(Lw);var Uw=/^[A-Za-z0-9_\-./]*$/,Kd=64;function Wd(t,e){if(t.length>Kd)throw new Error(`Invalid branch prefix from ${e}: length ${t.length} exceeds ${Kd}.`);if(!Uw.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 Gd(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.`)}H();import{existsSync as Wn,readdirSync as nD,readFileSync as qd,realpathSync as rD,statSync as oD}from"fs";import{homedir as zd}from"os";import{join as qe}from"path";var Jd=["claude-code","codex"],Kn=new Map,Ao={"claude-code":{label:"Claude Code",pluginRoots:t=>[qe(t,".claude","plugins")],skillRoots:t=>[qe(t,".claude","skills")],mcpConfigCandidates:t=>[qe(t,".claude","mcp.json"),qe(t,".claude",".mcp.json"),qe(t,".claude","claude-code","mcp.json")],mcpFormat:"json",pluginEnabledState:t=>Bw(t)},codex:{label:"Codex",pluginRoots:t=>[qe(t,".codex","plugins")],skillRoots:t=>[qe(t,".codex","skills")],mcpConfigCandidates:t=>[qe(t,".codex","config.toml")],mcpFormat:"toml",pluginEnabledState:()=>Kn}},lD={"claude-code":Ao["claude-code"].label,codex:Ao.codex.label};function ha(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of Jd){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 ya(){return[Zt(),vo()]}function ba(t=ya()){for(let e of t)if(Wn(e))try{let n=JSON.parse(qd(e,"utf-8")),r=ha(n.importFrom);if(r!==void 0)return r}catch{}}function wa(t,e=zd()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!t)return n;for(let r of Jd){let o=t[r];if(!o)continue;let s=Ao[r];if(o.plugins)for(let i of s.pluginRoots(e))Wn(i)&&n.pluginRoots.push({dir:i,binary:r});if(o.skills){let i=`imported:${r}`;for(let a of s.skillRoots(e))Wn(a)&&n.skillRoots.push({dir:a,origin:i})}if(o.mcp){let i=$w(s.mcpConfigCandidates(e));i&&n.mcpConfigs.push({source:i,format:s.mcpFormat})}}return n}function Yd(t,e=zd()){return Ao[t].pluginEnabledState(e)}function $w(t){for(let e of t)if(Wn(e))return e;return null}function Bw(t){let e=qe(t,".claude","settings.json");if(!Wn(e))return Kn;let n;try{n=JSON.parse(qd(e,"utf-8"))}catch{return Kn}if(!n||typeof n!="object")return Kn;let r=n.enabledPlugins;if(!r||typeof r!="object"||Array.isArray(r))return Kn;let o=new Map;for(let[s,i]of Object.entries(r))typeof i=="boolean"&&o.set(s,i);return o}var Eo;function Vd(){if(Eo!==void 0)return Eo;let t=[Kw(process.cwd(),"afk.config.json"),Zt(),vo()],e=!1;for(let r of t)if(jw(r))try{let o=Hw(r,"utf-8"),s=JSON.parse(o),i={},a=td(s.models);if(typeof s.model=="string"&&s.model.length>0){let c=s.model.toLowerCase();i.model=ao(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),ya().includes(r)){let c=ha(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=Wd(s.interactive.worktreeBranchPrefix,`${r}#/interactive/worktreeBranchPrefix`)),typeof s.interactive.worktreeBase=="string"&&s.interactive.worktreeBase.trim().length>0&&(Gd(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||(Eo=l),l}catch(o){console.error(`Warning: Failed to parse ${r}:`,o),e=!0}let n={config:{},sourcePath:void 0,modelsPartial:{}};return e||(Eo=n),n}H();function Sa(){return Vd().config.telegram??{}}N();function Gw(t,e){return e!==void 0&&Number.isFinite(e)&&e!==0?e:t.find(r=>r>0)??t[0]}function qw(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=Gw(n,e.primaryChatId);return o!==void 0?[o]:[]}function Xd(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=Qd(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 Qd(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 zw(t){if(!t)return;let e=t.trim().toLowerCase();return e==="primary"||e==="broadcast"||e==="custom"?e:void 0}function Jw(){let t=Sa().notify??{},e=t.mode??zw(b.AFK_TELEGRAM_NOTIFY_MODE),n=t.primaryChatId??Qd(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 To(){let t=Un(b.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return qw(t,Jw())}function Zd(){return Sa().chatAliases??{}}function ke(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
|
@@ -857,7 +857,7 @@ Remedy: these paths are outside the fork's granted read roots. Re-dispatch with
|
|
|
857
857
|
|
|
858
858
|
`).trim()}function MO(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}async function Kb(t,e){let{JSDOM:n,Readability:r,turndown:o}=await PO(),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=Wb(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=Wb(o.turndown(d));return{title:a,markdown:u,textLength:MO(c),usedFallback:!0}}var Tu,Gb=b(()=>{"use strict";Tu=null});function DO(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 qb(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function FO(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 ba(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??DO,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(!OO.has(u.status)||d===o)return u;let p=FO(u,i)??qb(d,s,i);$("[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=qb(d,s,i);$("[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 OO,xu=b(()=>{"use strict";me();OO=new Set([429,502,503,504])});import{readFileSync as LO}from"node:fs";import{join as NO}from"path";function $O(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function zb(t,e){return $O(e).test(t)}function HO(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(UO.has(e))return!0;if(BO.has(e))return!1}return!1}function Jb(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function jO(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 Vb(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Hc(e),e}function WO(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function KO(t){try{return LO(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function GO(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=Vb(e.defaultProfile)),n}function Yb(t){let e=t?.env??_,n=t?.readFileSync??KO,r=t?.surface??e.AGENT_SURFACE,o=HO(e.AFK_BROWSER_HEADLESS,r),s=Jb(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Jb(e.AFK_BROWSER_BLOCKED_DOMAINS),a=WO(e.AFK_BROWSER_DOM_SNAPSHOTS),l=jO(e.AFK_BROWSER_BACKEND),c=Vb(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():NO(kt(),"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=GO(d,m);return g.configPath=p,g}function wa(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(zb(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>zb(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var UO,BO,Sa=b(()=>{"use strict";j();K();UO=new Set(["daemon","subagent","telegram","afk"]),BO=new Set(["repl","interactive","cli"])});import{existsSync as qO,readFileSync as zO}from"node:fs";import{createRequire as JO}from"node:module";import{dirname as VO,join as YO}from"node:path";function Zb(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<QO&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function Me(t){let e=Zb(t);return Qb.some(n=>e.includes(n))}function ZO(){try{let e=JO(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(zO(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=YO(VO(e),o);return qO(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function Po(){return Xb??=ZO()??XO,Xb}function Ru(t){return t.includes("install chromium")}function Xe(t,e){let n=Zb(t),r=e?.latched===!0?` ${e0}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${Po()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Po()}). Or pick a different tool.${r}`}function Cu(t,e,n=!1){if(!Me(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
859
859
|
|
|
860
|
-
${Xe(t,{headless:e,latched:n})}`,{cause:t})}var Qb,XO,QO,Xb,e0,Iu=b(()=>{"use strict";Qb=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],XO="pnpm exec playwright install chromium",QO=4;e0="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Pn from"node:fs";import va from"node:path";import{randomBytes as t0}from"node:crypto";import{chromium as n0}from"playwright";function r0(){try{return"5.82.11"}catch{}try{let t=va.resolve(import.meta.dirname,"../../../package.json"),e=Pn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var o0,ka,ew=b(()=>{"use strict";Iu();K();me();o0=r0(),ka=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=n0.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Cu(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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){this.clearLaunchFailure();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.clearLaunchFailure(),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/${o0}`}}loadStorageState(e){let n=jc(e);try{if(!Pn.existsSync(n))return;let r=JSON.parse(Pn.readFileSync(n,"utf8"));return $("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){$("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=jc(e);if(!Pn.existsSync(r))return;let o=await n.storageState(),s=va.join(va.dirname(r),`.${va.basename(r)}.${process.pid}.${t0(4).toString("hex")}.tmp`);Pn.writeFileSync(s,JSON.stringify(o),{mode:384}),Pn.chmodSync(s,384),Pn.renameSync(s,r),$("[browser/vault] saved session",{profile:e,file:r})}catch(r){$("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as s0}from"crypto";function tw(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&i0.test(t.label))}function nw(t){return s0("sha256").update(t,"utf8").digest("hex").slice(0,8)}function rw(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var i0,_a=b(()=>{"use strict";i0=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as a0}from"node:crypto";function l0(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function c0(t,e,n){return`el_${a0("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function d0(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function ow(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function iw(t,e){let n=t.role??"",r=t.name??"";sw.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])iw(s,e)}async function u0(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},aw).catch(()=>[])}async function p0(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},aw).catch(()=>[])}function f0(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Aa(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=f0(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=u0(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=[],iw(u,h)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,h=(await p0(t)).filter(L=>sw.has(L.role??"")));let v=new Map;for(let I of p){let L=ow(I.name),z=v.get(L);(!z||z.bbox.w===0&&I.bbox.w>0)&&v.set(L,I)}let E=h.map(I=>({ax:I,dom:v.get(ow(I.name??""))})),k=r?E:E.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,L)=>{let z=I.dom?.bbox.y??0,P=L.dom?.bbox.y??0;if(z!==P)return z-P;let B=I.dom?.bbox.x??0,N=L.dom?.bbox.x??0;return B-N}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,L)=>{let z=I.ax.role??"generic",P=I.ax.name??"",B=c0(z,P,L),N=I.dom?.bbox??{x:0,y:0,w:0,h:0},M=I.dom?.type??null,O=null;I.ax.value!==void 0&&I.ax.value!==null&&(O=String(I.ax.value)),I.ax.checked!==void 0&&(O=String(I.ax.checked)),tw({role:z,kind:M})&&(O="[redacted]");let H={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(H.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(H.selected=I.ax.selected),I.ax.expanded!==void 0&&(H.expanded=I.ax.expanded);let F;I.dom?.testId?F=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(F=`#${I.dom.id}`);let U={id:B,role:z,label:l0(P),kind:M,value:O,state:H,bbox:N};return F!==void 0&&(U.selector=F),U}),R="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?R="loading":I==="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=d0(f),x=`obs_${e.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:x,url:m,title:g,textSummary:S,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:C}}var sw,aw,lw=b(()=>{"use strict";_a();sw=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);aw="a[href], button, input, select, textarea, [role], [tabindex], label"});async function cw(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 Pu(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>cw(t,s)))).filter(o=>o!==null)}async function m0(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 Mu(t,e,n){switch(e.kind){case"element_id":return g0(t,e,n);case"selector":return h0(t,e);case"semantic":return y0(t,e)}}async function g0(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 Pu(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function h0(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 Pu(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function y0(t,e){return e.role!==void 0?b0(t,e.text,e.role):w0(t,e.text,e)}async function b0(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 Pu(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function w0(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 m0(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 cw(h.locator,h.index);if(w!==null){let v=`${w.role}:${w.label}:${g}`,E=0;for(let k=0;k<v.length;k++)E=E*31+v.charCodeAt(k)>>>0;f.push({...w,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var dw=b(()=>{"use strict"});async function Ou(t,e,n,r){let o=t.url();if(o===n)return null;let s=wa(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var uw=b(()=>{"use strict";Sa()});import{randomBytes as S0}from"crypto";import{mkdir as v0,stat as k0,writeFile as _0}from"fs/promises";import{join as Du}from"path";import{gzip as A0}from"zlib";import{promisify as E0}from"util";function T0(t){return Du(zs(t),"browser")}function x0(t){return Du(T0(t),"screenshots")}function R0(){return new Date().toISOString().replace(/[:.]/g,"-")}function C0(){return S0(3).toString("hex")}async function Fu(t,e,n){if(e.length>pw)throw new Error(`writeScreenshotSidecar: buffer exceeds ${pw} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=x0(t);await v0(r,{recursive:!0});let o=`${R0()}-${C0()}-${n}.png`,s=Du(r,o);await _0(s,e);let{size:i}=await k0(s);return{path:s,bytes:i}}var m4,pw,fw=b(()=>{"use strict";K();_a();m4=E0(A0);pw=5*1024*1024});var gw={};Dc(gw,{PlaywrightProvider:()=>Lu});function mw(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 Lu,hw=b(()=>{"use strict";ew();lw();dw();Sa();uw();fw();Lu=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new ka(e)}async open(e){let n=wa(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(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Ou(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await Aa(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,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}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 Aa(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 Mu(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${mw(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":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=await Ou(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Aa(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 Mu(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${mw(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 Fu(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 Fu(n,o,r);return s}catch{return null}}}});var On={};Dc(On,{__resetBrowserRegistryForTests:()=>D0,browserProviderActive:()=>M0,closeBrowserProvider:()=>Nu,getBrowserProvider:()=>P0,peekBrowserProvider:()=>O0});function yw(){Promise.resolve(Nu()).then(()=>{process.exit(130)})}function bw(){Promise.resolve(Nu()).then(()=>{process.exit(143)})}function ww(){yt=null}function I0(){Ea||(process.on("SIGINT",yw),process.on("SIGTERM",bw),process.on("exit",ww),Ea=!0)}function Sw(){Ea&&(process.removeListener("SIGINT",yw),process.removeListener("SIGTERM",bw),process.removeListener("exit",ww),Ea=!1)}async function P0(t){return yt!==null?yt:(Mn!==null||(Mn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(hw(),gw)),n=Yb(t),r=new e(n);return I0(),yt=r,Mn=null,r})()),Mn)}async function Nu(){if(yt===null)return;let t=yt;yt=null,Mn=null,Sw(),await t.shutdown()}function M0(){return yt!==null}function O0(){return yt}function D0(){yt=null,Mn=null,Sw()}var yt,Mn,Ea,Dn=b(()=>{"use strict";Sa();yt=null,Mn=null,Ea=!1});async function vw(t,e){try{return await Kb(t,e)}catch(n){return $("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function B0(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Dn(),On));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function kw(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??B0,o=null,s=t,i=null,a=null;try{let c=await ba(n,t,{headers:U0,redirect:"follow",signal:e.signal});i=c.status,s=c.url||t;let d=c.headers.get("content-type")??"";if(c.ok){if($0.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(N0.test(d)&&!L0.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};if(o=await vw(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 vw(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 L0,N0,$0,U0,_w=b(()=>{"use strict";Gb();xu();me();L0=/(text\/html|application\/xhtml\+xml)/i,N0=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,$0=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,U0={"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 W0(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(H0,{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),j0),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=cr(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 Aw(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?W0({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 Ew(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
860
|
+
${Xe(t,{headless:e,latched:n})}`,{cause:t})}var Qb,XO,QO,Xb,e0,Iu=b(()=>{"use strict";Qb=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],XO="pnpm exec playwright install chromium",QO=4;e0="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Pn from"node:fs";import va from"node:path";import{randomBytes as t0}from"node:crypto";import{chromium as n0}from"playwright";function r0(){try{return"5.82.12"}catch{}try{let t=va.resolve(import.meta.dirname,"../../../package.json"),e=Pn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var o0,ka,ew=b(()=>{"use strict";Iu();K();me();o0=r0(),ka=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=n0.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Cu(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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){this.clearLaunchFailure();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.clearLaunchFailure(),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/${o0}`}}loadStorageState(e){let n=jc(e);try{if(!Pn.existsSync(n))return;let r=JSON.parse(Pn.readFileSync(n,"utf8"));return $("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){$("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=jc(e);if(!Pn.existsSync(r))return;let o=await n.storageState(),s=va.join(va.dirname(r),`.${va.basename(r)}.${process.pid}.${t0(4).toString("hex")}.tmp`);Pn.writeFileSync(s,JSON.stringify(o),{mode:384}),Pn.chmodSync(s,384),Pn.renameSync(s,r),$("[browser/vault] saved session",{profile:e,file:r})}catch(r){$("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as s0}from"crypto";function tw(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&i0.test(t.label))}function nw(t){return s0("sha256").update(t,"utf8").digest("hex").slice(0,8)}function rw(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var i0,_a=b(()=>{"use strict";i0=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as a0}from"node:crypto";function l0(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function c0(t,e,n){return`el_${a0("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function d0(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function ow(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function iw(t,e){let n=t.role??"",r=t.name??"";sw.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])iw(s,e)}async function u0(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},aw).catch(()=>[])}async function p0(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},aw).catch(()=>[])}function f0(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Aa(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=f0(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=u0(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=[],iw(u,h)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,h=(await p0(t)).filter(L=>sw.has(L.role??"")));let v=new Map;for(let I of p){let L=ow(I.name),z=v.get(L);(!z||z.bbox.w===0&&I.bbox.w>0)&&v.set(L,I)}let E=h.map(I=>({ax:I,dom:v.get(ow(I.name??""))})),k=r?E:E.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,L)=>{let z=I.dom?.bbox.y??0,P=L.dom?.bbox.y??0;if(z!==P)return z-P;let B=I.dom?.bbox.x??0,N=L.dom?.bbox.x??0;return B-N}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,L)=>{let z=I.ax.role??"generic",P=I.ax.name??"",B=c0(z,P,L),N=I.dom?.bbox??{x:0,y:0,w:0,h:0},M=I.dom?.type??null,O=null;I.ax.value!==void 0&&I.ax.value!==null&&(O=String(I.ax.value)),I.ax.checked!==void 0&&(O=String(I.ax.checked)),tw({role:z,kind:M})&&(O="[redacted]");let H={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(H.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(H.selected=I.ax.selected),I.ax.expanded!==void 0&&(H.expanded=I.ax.expanded);let F;I.dom?.testId?F=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(F=`#${I.dom.id}`);let U={id:B,role:z,label:l0(P),kind:M,value:O,state:H,bbox:N};return F!==void 0&&(U.selector=F),U}),R="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?R="loading":I==="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=d0(f),x=`obs_${e.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:x,url:m,title:g,textSummary:S,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:C}}var sw,aw,lw=b(()=>{"use strict";_a();sw=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);aw="a[href], button, input, select, textarea, [role], [tabindex], label"});async function cw(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 Pu(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>cw(t,s)))).filter(o=>o!==null)}async function m0(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 Mu(t,e,n){switch(e.kind){case"element_id":return g0(t,e,n);case"selector":return h0(t,e);case"semantic":return y0(t,e)}}async function g0(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 Pu(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function h0(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 Pu(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function y0(t,e){return e.role!==void 0?b0(t,e.text,e.role):w0(t,e.text,e)}async function b0(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 Pu(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function w0(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 m0(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 cw(h.locator,h.index);if(w!==null){let v=`${w.role}:${w.label}:${g}`,E=0;for(let k=0;k<v.length;k++)E=E*31+v.charCodeAt(k)>>>0;f.push({...w,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var dw=b(()=>{"use strict"});async function Ou(t,e,n,r){let o=t.url();if(o===n)return null;let s=wa(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var uw=b(()=>{"use strict";Sa()});import{randomBytes as S0}from"crypto";import{mkdir as v0,stat as k0,writeFile as _0}from"fs/promises";import{join as Du}from"path";import{gzip as A0}from"zlib";import{promisify as E0}from"util";function T0(t){return Du(zs(t),"browser")}function x0(t){return Du(T0(t),"screenshots")}function R0(){return new Date().toISOString().replace(/[:.]/g,"-")}function C0(){return S0(3).toString("hex")}async function Fu(t,e,n){if(e.length>pw)throw new Error(`writeScreenshotSidecar: buffer exceeds ${pw} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=x0(t);await v0(r,{recursive:!0});let o=`${R0()}-${C0()}-${n}.png`,s=Du(r,o);await _0(s,e);let{size:i}=await k0(s);return{path:s,bytes:i}}var m4,pw,fw=b(()=>{"use strict";K();_a();m4=E0(A0);pw=5*1024*1024});var gw={};Dc(gw,{PlaywrightProvider:()=>Lu});function mw(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 Lu,hw=b(()=>{"use strict";ew();lw();dw();Sa();uw();fw();Lu=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new ka(e)}async open(e){let n=wa(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(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Ou(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await Aa(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,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}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 Aa(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 Mu(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${mw(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":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=await Ou(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Aa(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 Mu(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${mw(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 Fu(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 Fu(n,o,r);return s}catch{return null}}}});var On={};Dc(On,{__resetBrowserRegistryForTests:()=>D0,browserProviderActive:()=>M0,closeBrowserProvider:()=>Nu,getBrowserProvider:()=>P0,peekBrowserProvider:()=>O0});function yw(){Promise.resolve(Nu()).then(()=>{process.exit(130)})}function bw(){Promise.resolve(Nu()).then(()=>{process.exit(143)})}function ww(){yt=null}function I0(){Ea||(process.on("SIGINT",yw),process.on("SIGTERM",bw),process.on("exit",ww),Ea=!0)}function Sw(){Ea&&(process.removeListener("SIGINT",yw),process.removeListener("SIGTERM",bw),process.removeListener("exit",ww),Ea=!1)}async function P0(t){return yt!==null?yt:(Mn!==null||(Mn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(hw(),gw)),n=Yb(t),r=new e(n);return I0(),yt=r,Mn=null,r})()),Mn)}async function Nu(){if(yt===null)return;let t=yt;yt=null,Mn=null,Sw(),await t.shutdown()}function M0(){return yt!==null}function O0(){return yt}function D0(){yt=null,Mn=null,Sw()}var yt,Mn,Ea,Dn=b(()=>{"use strict";Sa();yt=null,Mn=null,Ea=!1});async function vw(t,e){try{return await Kb(t,e)}catch(n){return $("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function B0(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Dn(),On));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function kw(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??B0,o=null,s=t,i=null,a=null;try{let c=await ba(n,t,{headers:U0,redirect:"follow",signal:e.signal});i=c.status,s=c.url||t;let d=c.headers.get("content-type")??"";if(c.ok){if($0.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(N0.test(d)&&!L0.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};if(o=await vw(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 vw(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 L0,N0,$0,U0,_w=b(()=>{"use strict";Gb();xu();me();L0=/(text\/html|application\/xhtml\+xml)/i,N0=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,$0=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,U0={"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 W0(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(H0,{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),j0),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=cr(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 Aw(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?W0({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 Ew(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
861
861
|
|
|
862
862
|
(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(`
|
|
863
863
|
`).trimEnd()}var H0,j0,Tw=b(()=>{"use strict";bn();H0="https://api.exa.ai/search",j0=10});function Ta(t){if(t instanceof Error&&t.name==="TimeoutError")return"timeout";let e=t instanceof Error?t.message:String(t);return/Timeout\s+\d+\s*ms exceeded/i.test(e)?"timeout":void 0}var Fn=b(()=>{"use strict";Iu()});function V0(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=K0;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,G0)}let a=q0;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,z0)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function $u(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:Rt(t,e),truncated:!0}}function Y0(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=V0(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 ba(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=$u(p,s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let u=await kw(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=$u(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=Me(u)&&!Ru(p)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Po()}\`)`:"";return{content:`web_scrape markdown error: ${p}${f}`,isError:!0}}let d=Aw({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:J0,timeoutMs:s.timeoutMs,signal:i.signal}),p=$u(Ew(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 K0,G0,q0,z0,J0,xw,Rw=b(()=>{"use strict";_w();Tw();xu();pr();Fn();K0=3e4,G0=12e4,q0=1e5,z0=1e6,J0=10;xw=Y0()});import{existsSync as Iw,mkdirSync as X0,readFileSync as Q0,renameSync as Z0,unlinkSync as eD,writeFileSync as tD}from"node:fs";import{dirname as Cw,join as nD}from"node:path";import{randomBytes as rD}from"node:crypto";function yr(t){let e=t??$c();if(!Iw(e))return[];try{let n=Q0(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 xa(t,e){let n=e??$c();X0(Cw(n),{recursive:!0});let r=nD(Cw(n),`.schedules.json.${process.pid}.${rD(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{tD(r,o,"utf-8"),Z0(r,n)}catch(s){try{Iw(r)&&eD(r)}catch{}throw s}}function Pw(t,e){let n=yr(e),r=n.map(l=>l.id),o=oD(t.name),s=sD(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),xa(n,e),a}function Mw(t,e){let n=yr(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(xa(o,e),!0)}function Ow(t,e){return yr(e).find(n=>n.id===t)}function oD(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function sD(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}var Dw=b(()=>{"use strict";K()});import{existsSync as iD,readFileSync as aD}from"node:fs";import{join as lD}from"node:path";async function Mo(t,e,n){let r;try{let o=lD(Mm("default"),"port");if(!iD(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let s=aD(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 Uu,Fw=b(()=>{"use strict";K();Uu="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 cD}from"node:fs";import{readFile as dD}from"node:fs/promises";var Lw,Nw,$w,Uw,Bw=b(()=>{"use strict";Dw();K();Fw();Lw=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=Pw({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 Mo("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 Mo("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:Uu}})}},Nw=async(t,e)=>{let n=yr();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})))}},$w=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=Bs();if(!cD(s))return{content:JSON.stringify([])};let i;try{let c=await dD(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.82.
|
|
3
|
+
"version": "5.82.12",
|
|
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",
|