agent-afk 5.51.2 → 5.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/assets/demo-placeholder.png +0 -0
- package/dist/agent/hooks.d.ts +1 -0
- package/dist/agent/session/hooks-dispatch.d.ts +1 -1
- package/dist/cli.mjs +5 -58
- package/dist/index.mjs +70 -123
- package/dist/telegram.mjs +4 -57
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -12,7 +12,11 @@
|
|
|
12
12
|
[](LICENSE)
|
|
13
13
|
[](https://github.com/griffinwork40/agent-afk/stargazers)
|
|
14
14
|
|
|
15
|
-
<!-- DEMO
|
|
15
|
+
<!-- DEMO PLACEHOLDER ▸ the image below is a static stand-in. Replace it with a 20–30s screen recording of one autonomous AFK run (e.g. kick off `afk daemon` / `afk mint "..."`, walk away, get the Telegram ping, come back done). Drag-and-drop the recording into a GitHub issue/PR to host it on GitHub's CDN, then swap the URL below. This is the single biggest star-conversion lever — keep it above the fold. -->
|
|
16
|
+
|
|
17
|
+
<p align="center">
|
|
18
|
+
<img src="assets/demo-placeholder.png" alt="Agent AFK interactive mode" width="820">
|
|
19
|
+
</p>
|
|
16
20
|
|
|
17
21
|
> ⭐ **Like the idea of an agent loop you fully own? [Star the repo](https://github.com/griffinwork40/agent-afk/stargazers)** — it's the fastest way to help other people find it.
|
|
18
22
|
|
|
@@ -246,7 +250,13 @@ Recent releases at [`CHANGELOG.md`](CHANGELOG.md), also viewable in-REPL via `/c
|
|
|
246
250
|
|
|
247
251
|
## Star History
|
|
248
252
|
|
|
249
|
-
|
|
253
|
+
<a href="https://www.star-history.com/?type=date&repos=griffinwork40%2Fagent-afk">
|
|
254
|
+
<picture>
|
|
255
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=griffinwork40/agent-afk&type=date&theme=dark&legend=top-left&sealed_token=0JyTRyQ55uvLCrhjSrDS7mq_ztnj8HQ19fDUsbUF0GuO1-REfAFV4OGbrgoH11e-eMbpDr_rq7qhipj2Ch-gUR50ayL2tr7889lkW87yr1RSpDe7qgNQg9c14OCFni9jsbpVxW_QvzkP3YuAjCWKfPYrSi8VIQvhSSMzZXmb-v2luuafNiza3TaIOE_K" />
|
|
256
|
+
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=griffinwork40/agent-afk&type=date&legend=top-left&sealed_token=0JyTRyQ55uvLCrhjSrDS7mq_ztnj8HQ19fDUsbUF0GuO1-REfAFV4OGbrgoH11e-eMbpDr_rq7qhipj2Ch-gUR50ayL2tr7889lkW87yr1RSpDe7qgNQg9c14OCFni9jsbpVxW_QvzkP3YuAjCWKfPYrSi8VIQvhSSMzZXmb-v2luuafNiza3TaIOE_K" />
|
|
257
|
+
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=griffinwork40/agent-afk&type=date&legend=top-left&sealed_token=0JyTRyQ55uvLCrhjSrDS7mq_ztnj8HQ19fDUsbUF0GuO1-REfAFV4OGbrgoH11e-eMbpDr_rq7qhipj2Ch-gUR50ayL2tr7889lkW87yr1RSpDe7qgNQg9c14OCFni9jsbpVxW_QvzkP3YuAjCWKfPYrSi8VIQvhSSMzZXmb-v2luuafNiza3TaIOE_K" />
|
|
258
|
+
</picture>
|
|
259
|
+
</a>
|
|
250
260
|
|
|
251
261
|
If Agent AFK saves you time, **[⭐ star the repo](https://github.com/griffinwork40/agent-afk/stargazers)** — it's the single best way to help it reach more people.
|
|
252
262
|
|
|
Binary file
|
package/dist/agent/hooks.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ export type SubagentHookStatus = 'idle' | 'running' | 'succeeded' | 'failed' | '
|
|
|
11
11
|
export interface SessionStartContext {
|
|
12
12
|
event: 'SessionStart';
|
|
13
13
|
sessionId?: string;
|
|
14
|
+
parentSessionId?: string;
|
|
14
15
|
}
|
|
15
16
|
export interface SessionEndContext {
|
|
16
17
|
event: 'SessionEnd';
|
|
@@ -5,5 +5,5 @@ export interface SessionHookDispatchOptions {
|
|
|
5
5
|
onError?: (err: Error) => void;
|
|
6
6
|
traceWriter?: TraceWriter;
|
|
7
7
|
}
|
|
8
|
-
export declare function dispatchSessionStart(registry: HookRegistry | undefined, context: SessionStartContext, options?: SessionHookDispatchOptions): Promise<
|
|
8
|
+
export declare function dispatchSessionStart(registry: HookRegistry | undefined, context: SessionStartContext, options?: SessionHookDispatchOptions): Promise<string | undefined>;
|
|
9
9
|
export declare function dispatchSessionEnd(registry: HookRegistry | undefined, context: SessionEndContext, options?: SessionHookDispatchOptions): Promise<void>;
|
package/dist/cli.mjs
CHANGED
|
@@ -869,7 +869,7 @@ Remedy: these paths are outside the fork's granted read roots. Re-dispatch with
|
|
|
869
869
|
Note: this search ran in basic-regex (BRE) mode, where '|' is a literal pipe \u2014 not alternation. If you intended "A or B", retry with extended: true (extended regex / ERE). If you meant the literal character '|', this empty result stands.`),d({content:A});return}if(v===2){let A=Us(h.trim());d({content:`grep error: ${A.content}`,isError:!0,...A.truncated?{truncated:!0}:{}});return}let T=Xn(g.trimEnd()),R=Us(T);d({content:R.content,...R.truncated?{truncated:!0}:{}})}),m.on("error",v=>{let T;if(p===void 0&&mc(v))try{T=Bs(v,process.cwd())}catch{T=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${v.message}`}else T=Bs(v,p);d({content:`Failed to execute grep: ${T}`,isError:!0})})})}}var sA,aA=x(()=>{"use strict";Yn();Pr();co();cw();dw();sA=Sw()});import{promises as jJ}from"fs";function vw(e){return(t,n,r)=>HJ(t,n,r,e)}var HJ,lA,cA=x(()=>{"use strict";Pr();HJ=async(e,t,n,r)=>{if(!e||typeof e!="object")throw new Error("Invalid input: expected an object");let i=e.path;if(typeof i!="string")throw new Error("Invalid input: path must be a string");let s;try{s=mn(i,n,"read",r)}catch(a){return{content:a instanceof Error?a.message:String(a),isError:!0}}try{let a=await jJ.readdir(s,{withFileTypes:!0}),l=a.filter(p=>p.isDirectory()).map(p=>`${p.name}/`),c=a.filter(p=>!p.isDirectory()).map(p=>p.name);l.sort(),c.sort();let d=[...l,...c];return d.length===0?{content:"(empty directory)"}:{content:d.join(`
|
|
870
870
|
`)}}catch(a){if(a instanceof Error){let l=a;return l.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:l.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:l.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${a.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}};lA=vw()});function WJ(e=Is){return async(t,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t.message;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>dA)return{content:`Invalid input: message exceeds Telegram's ${dA}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let i=k.TELEGRAM_BOT_TOKEN;if(!i)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let s=_s();if(s.length===0)return{content:"Telegram is not configured: AFK_TELEGRAM_ALLOWED_CHAT_IDS is empty or unset. Add the operator chat ID(s) before using send_telegram.",isError:!0};let a=[];for(let l of s){let c=await e({token:i,chatId:l,text:o});c.ok||a.push(`chat ${l}: ${c.errorMessage??`HTTP ${c.status}`}`)}return a.length===s.length?{content:`Failed to send Telegram message to any chat. ${a.join("; ")}`,isError:!0}:a.length>0?{content:`Sent Telegram message to ${s.length-a.length}/${s.length} chat(s); ${a.length} failed: ${a.join("; ")}`}:{content:s.length===1?`Sent Telegram message to chat ${s[0]}.`:`Sent Telegram message to ${s.length} chats.`}}}var dA,uA,pA=x(()=>{"use strict";K();xr();Xu();dA=4096;uA=WJ()});async function KJ(){let[{JSDOM:e},{Readability:t},{default:n}]=await Promise.all([import("jsdom"),import("@mozilla/readability"),import("turndown")]),r=new n({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});return r.remove(["script","style","noscript","iframe"]),{JSDOM:e,Readability:t,turndown:r}}function GJ(){return kw===null&&(kw=KJ()),kw}function mA(e){return e.replace(/\n{3,}/g,`
|
|
871
871
|
|
|
872
|
-
`).trim()}function qJ(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}async function fA(e,t){let{JSDOM:n,Readability:r,turndown:o}=await GJ(),s=new n(e,{url:t}).window.document,a=(s.title??"").trim(),l=(()=>{try{let p=s.cloneNode(!0);return new r(p).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let p=mA(o.turndown(l.content)),m=(l.title??"").trim()||a,g=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:m,markdown:p,textLength:g,usedFallback:!1}}let c=s.body,d=c?.innerHTML??"",u=mA(o.turndown(d));return{title:a,markdown:u,textLength:qJ(c),usedFallback:!0}}var kw,gA=x(()=>{"use strict";kw=null});function JJ(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 hA(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function YJ(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 Pp(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??JJ,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(!zJ.has(u.status)||d===o)return u;let p=YJ(u,s)??hA(d,i,s);W("[web/retryFetch] retrying",{url:t,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=hA(d,i,s);W("[web/retryFetch] retrying after error",{url:t,attempt:d,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var zJ,Ew=x(()=>{"use strict";fe();zJ=new Set([429,502,503,504])});import{readFileSync as VJ}from"node:fs";import{join as XJ}from"path";function QJ(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function yA(e,t){return QJ(t).test(e)}function tY(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(ZJ.has(t))return!0;if(eY.has(t))return!1}return!1}function bA(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function nY(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 wA(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Ll(t),t}function rY(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function oY(e){try{return VJ(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function iY(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=wA(t.defaultProfile)),n}function SA(e){let t=e?.env??k,n=e?.readFileSync??oY,r=e?.surface??t.AGENT_SURFACE,o=tY(t.AFK_BROWSER_HEADLESS,r),i=bA(t.AFK_BROWSER_ALLOWED_DOMAINS),s=bA(t.AFK_BROWSER_BLOCKED_DOMAINS),a=rY(t.AFK_BROWSER_DOM_SNAPSHOTS),l=nY(t.AFK_BROWSER_BACKEND),c=wA(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,p=u!==void 0&&u.trim()!==""?u.trim():XJ(En(),"browser.json"),m=n(p);if(m===void 0)return d;let g;try{g=JSON.parse(m)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=iY(d,g);return h.configPath=p,h}function Tw(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(yA(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>yA(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var ZJ,eY,xw=x(()=>{"use strict";K();G();ZJ=new Set(["daemon","subagent","telegram","afk"]),eY=new Set(["repl","interactive","cli"])});import fi from"node:fs";import Mp from"node:path";import{randomBytes as sY}from"node:crypto";import{chromium as aY}from"playwright";function lY(){try{return"5.51.2"}catch{}try{let e=Mp.resolve(import.meta.dirname,"../../../package.json"),t=fi.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var cY,Op,vA=x(()=>{"use strict";G();fe();cY=lY(),Op=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=aY.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let s=await o.newPage(),a=await s.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await s.content(),c=s.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${cY}`}}loadStorageState(t){let n=Nl(t);try{if(!fi.existsSync(n))return;let r=JSON.parse(fi.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=Nl(t);if(!fi.existsSync(r))return;let o=await n.storageState(),i=Mp.join(Mp.dirname(r),`.${Mp.basename(r)}.${process.pid}.${sY(4).toString("hex")}.tmp`);fi.writeFileSync(i,JSON.stringify(o),{mode:384}),fi.chmodSync(i,384),fi.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 dY}from"crypto";function Rw(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of uY)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function kA(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&pY.test(e.label))}function EA(e){return dY("sha256").update(e,"utf8").digest("hex").slice(0,8)}function TA(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var uY,pY,yc=x(()=>{"use strict";uY=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];pY=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as mY}from"node:crypto";function fY(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function gY(e,t,n){return`el_${mY("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function hY(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function xA(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function CA(e,t){let n=e.role??"",r=e.name??"";RA.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])CA(i,t)}async function yY(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},AA).catch(()=>[])}async function bY(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,p=i.disabled??!1,m=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};u!==void 0&&(g.value=u),m!==void 0&&(g.checked=m),o.push(g)}return o},AA).catch(()=>[])}function wY(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function $p(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=wY(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=yY(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,p,m,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],CA(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await bY(e)).filter(B=>RA.has(B.role??"")));let w=new Map;for(let M of p){let B=xA(M.name),j=w.get(B);(!j||j.bbox.w===0&&M.bbox.w>0)&&w.set(B,M)}let S=y.map(M=>({ax:M,dom:w.get(xA(M.name??""))})),v=r?S:S.filter(M=>M.dom?M.dom.bbox.w>0||M.dom.bbox.h>0:!0);v.sort((M,B)=>{let j=M.dom?.bbox.y??0,U=B.dom?.bbox.y??0;if(j!==U)return j-U;let P=M.dom?.bbox.x??0,D=B.dom?.bbox.x??0;return P-D}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=v.slice(0,n).map((M,B)=>{let j=M.ax.role??"generic",U=M.ax.name??"",P=gY(j,U,B),D=M.dom?.bbox??{x:0,y:0,w:0,h:0},F=M.dom?.type??null,I=null;M.ax.value!==void 0&&M.ax.value!==null&&(I=String(M.ax.value)),M.ax.checked!==void 0&&(I=String(M.ax.checked)),kA({role:j,kind:F})&&(I="[redacted]");let O={disabled:M.ax.disabled??!1};M.ax.checked!==void 0&&(O.checked=M.ax.checked===!0||M.ax.checked==="mixed"),M.ax.selected!==void 0&&(O.selected=M.ax.selected),M.ax.expanded!==void 0&&(O.expanded=M.ax.expanded);let $;M.dom?.testId?$=`[data-testid="${M.dom.testId}"]`:M.dom?.id&&($=`#${M.dom.id}`);let H={id:P,role:j,label:fY(U),kind:F,value:I,state:O,bbox:D};return $!==void 0&&(H.selector=$),H}),A="idle";try{let M=await e.evaluate(()=>document.readyState);M==="loading"?A="loading":M==="interactive"?A="navigating":A="idle"}catch{A="navigating"}A!=="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 C=hY(m),N=`obs_${t.observationCounter.toString(36)}`,_=new Date().toISOString();return{observationId:N,url:g,title:h,textSummary:C,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:A,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:_}}var RA,AA,_A=x(()=>{"use strict";yc();RA=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);AA="a[href], button, input, select, textarea, [role], [tabindex], label"});async function IA(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 Cw(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>IA(e,i)))).filter(o=>o!==null)}async function SY(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 Aw(e,t,n){switch(t.kind){case"element_id":return vY(e,t,n);case"selector":return kY(e,t);case"semantic":return EY(e,t)}}async function vY(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 Cw(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function kY(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 Cw(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function EY(e,t){return t.role!==void 0?TY(e,t.text,t.role):xY(e,t.text,t)}async function TY(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 Cw(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function xY(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 SY(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 p=u.slice(0,5),m=[];for(let h=0;h<p.length;h++){let y=p[h];if(y===void 0)continue;let b=await IA(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let v=0;v<w.length;v++)S=S*31+w.charCodeAt(v)>>>0;m.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:m}}var PA=x(()=>{"use strict"});import{randomBytes as RY}from"crypto";import{mkdir as CY,stat as AY,writeFile as _Y}from"fs/promises";import{join as _w}from"path";import{gzip as IY}from"zlib";import{promisify as PY}from"util";function MY(e){return _w(Xo(e),"browser")}function OY(e){return _w(MY(e),"screenshots")}function $Y(){return new Date().toISOString().replace(/[:.]/g,"-")}function DY(){return RY(3).toString("hex")}async function Iw(e,t,n){if(t.length>MA)throw new Error(`writeScreenshotSidecar: buffer exceeds ${MA} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=OY(e);await CY(r,{recursive:!0});let o=`${$Y()}-${DY()}-${n}.png`,i=_w(r,o);await _Y(i,t);let{size:s}=await AY(i);return{path:i,bytes:s}}var yke,MA,OA=x(()=>{"use strict";G();yc();yke=PY(IY);MA=5*1024*1024});var DA={};cu(DA,{PlaywrightProvider:()=>Pw});function $A(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 Pw,FA=x(()=>{"use strict";vA();_A();PA();xw();yc();OA();Pw=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Op(t)}async open(t){let n=Tw(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let l=await $p(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await $p(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 Aw(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${$A(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":{let h=Rw(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){c=y}else c=h}let u=r.url();if(u!==i){let h=Tw(u,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:h.reason}}let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let m=await $p(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,m.interactive,m.url,m.title,g),c!==null)throw c;return m}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 Aw(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${$A(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 Iw(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 Iw(n,o,r);return i}catch{return null}}}});var hi={};cu(hi,{__resetBrowserRegistryForTests:()=>UY,browserProviderActive:()=>NY,closeBrowserProvider:()=>Mw,getBrowserProvider:()=>LY,peekBrowserProvider:()=>BY});function LA(){Promise.resolve(Mw()).then(()=>{process.exit(130)})}function NA(){Promise.resolve(Mw()).then(()=>{process.exit(143)})}function BA(){Qn=null}function FY(){Dp||(process.on("SIGINT",LA),process.on("SIGTERM",NA),process.on("exit",BA),Dp=!0)}function UA(){Dp&&(process.removeListener("SIGINT",LA),process.removeListener("SIGTERM",NA),process.removeListener("exit",BA),Dp=!1)}async function LY(e){return Qn!==null?Qn:(gi!==null||(gi=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(FA(),DA)),n=SA(e),r=new t(n);return FY(),Qn=r,gi=null,r})()),gi)}async function Mw(){if(Qn===null)return;let e=Qn;Qn=null,gi=null,UA(),await e.shutdown()}function NY(){return Qn!==null}function BY(){return Qn}function UY(){Qn=null,gi=null,UA()}var Qn,gi,Dp,yi=x(()=>{"use strict";xw();Qn=null,gi=null,Dp=!1});async function jA(e,t){try{return await fA(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function qY(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(yi(),hi));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function HA(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??qY,o=null,i=e,s=null,a=null;try{let c=await Pp(n,e,{headers:GY,redirect:"follow",signal:t.signal});s=c.status,i=c.url||e;let d=c.headers.get("content-type")??"";if(c.ok){if(KY.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(WY.test(d)&&!HY.test(d))return{title:"",markdown:u.trim(),finalUrl:i,usedRender:!1};if(o=await jA(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 jA(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"}`,p=new Error(`web_scrape could not retrieve ${e}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=c,p}}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 HY,WY,KY,GY,WA=x(()=>{"use strict";gA();Ew();fe();HY=/(text\/html|application\/xhtml\+xml)/i,WY=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,KY=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,GY={"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 YY(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(zY,{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),JY),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 KA(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?YY({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 GA(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
872
|
+
`).trim()}function qJ(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}async function fA(e,t){let{JSDOM:n,Readability:r,turndown:o}=await GJ(),s=new n(e,{url:t}).window.document,a=(s.title??"").trim(),l=(()=>{try{let p=s.cloneNode(!0);return new r(p).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let p=mA(o.turndown(l.content)),m=(l.title??"").trim()||a,g=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:m,markdown:p,textLength:g,usedFallback:!1}}let c=s.body,d=c?.innerHTML??"",u=mA(o.turndown(d));return{title:a,markdown:u,textLength:qJ(c),usedFallback:!0}}var kw,gA=x(()=>{"use strict";kw=null});function JJ(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 hA(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function YJ(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 Pp(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??JJ,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(!zJ.has(u.status)||d===o)return u;let p=YJ(u,s)??hA(d,i,s);W("[web/retryFetch] retrying",{url:t,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=hA(d,i,s);W("[web/retryFetch] retrying after error",{url:t,attempt:d,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var zJ,Ew=x(()=>{"use strict";fe();zJ=new Set([429,502,503,504])});import{readFileSync as VJ}from"node:fs";import{join as XJ}from"path";function QJ(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function yA(e,t){return QJ(t).test(e)}function tY(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(ZJ.has(t))return!0;if(eY.has(t))return!1}return!1}function bA(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function nY(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 wA(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Ll(t),t}function rY(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function oY(e){try{return VJ(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function iY(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=wA(t.defaultProfile)),n}function SA(e){let t=e?.env??k,n=e?.readFileSync??oY,r=e?.surface??t.AGENT_SURFACE,o=tY(t.AFK_BROWSER_HEADLESS,r),i=bA(t.AFK_BROWSER_ALLOWED_DOMAINS),s=bA(t.AFK_BROWSER_BLOCKED_DOMAINS),a=rY(t.AFK_BROWSER_DOM_SNAPSHOTS),l=nY(t.AFK_BROWSER_BACKEND),c=wA(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,p=u!==void 0&&u.trim()!==""?u.trim():XJ(En(),"browser.json"),m=n(p);if(m===void 0)return d;let g;try{g=JSON.parse(m)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=iY(d,g);return h.configPath=p,h}function Tw(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(yA(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>yA(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var ZJ,eY,xw=x(()=>{"use strict";K();G();ZJ=new Set(["daemon","subagent","telegram","afk"]),eY=new Set(["repl","interactive","cli"])});import fi from"node:fs";import Mp from"node:path";import{randomBytes as sY}from"node:crypto";import{chromium as aY}from"playwright";function lY(){try{return"5.52.0"}catch{}try{let e=Mp.resolve(import.meta.dirname,"../../../package.json"),t=fi.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var cY,Op,vA=x(()=>{"use strict";G();fe();cY=lY(),Op=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=aY.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let s=await o.newPage(),a=await s.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await s.content(),c=s.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${cY}`}}loadStorageState(t){let n=Nl(t);try{if(!fi.existsSync(n))return;let r=JSON.parse(fi.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=Nl(t);if(!fi.existsSync(r))return;let o=await n.storageState(),i=Mp.join(Mp.dirname(r),`.${Mp.basename(r)}.${process.pid}.${sY(4).toString("hex")}.tmp`);fi.writeFileSync(i,JSON.stringify(o),{mode:384}),fi.chmodSync(i,384),fi.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 dY}from"crypto";function Rw(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of uY)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function kA(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&pY.test(e.label))}function EA(e){return dY("sha256").update(e,"utf8").digest("hex").slice(0,8)}function TA(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var uY,pY,yc=x(()=>{"use strict";uY=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];pY=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as mY}from"node:crypto";function fY(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function gY(e,t,n){return`el_${mY("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function hY(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function xA(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function CA(e,t){let n=e.role??"",r=e.name??"";RA.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])CA(i,t)}async function yY(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},AA).catch(()=>[])}async function bY(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,p=i.disabled??!1,m=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};u!==void 0&&(g.value=u),m!==void 0&&(g.checked=m),o.push(g)}return o},AA).catch(()=>[])}function wY(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function $p(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=wY(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=yY(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,p,m,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],CA(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await bY(e)).filter(B=>RA.has(B.role??"")));let w=new Map;for(let M of p){let B=xA(M.name),j=w.get(B);(!j||j.bbox.w===0&&M.bbox.w>0)&&w.set(B,M)}let S=y.map(M=>({ax:M,dom:w.get(xA(M.name??""))})),v=r?S:S.filter(M=>M.dom?M.dom.bbox.w>0||M.dom.bbox.h>0:!0);v.sort((M,B)=>{let j=M.dom?.bbox.y??0,U=B.dom?.bbox.y??0;if(j!==U)return j-U;let P=M.dom?.bbox.x??0,D=B.dom?.bbox.x??0;return P-D}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=v.slice(0,n).map((M,B)=>{let j=M.ax.role??"generic",U=M.ax.name??"",P=gY(j,U,B),D=M.dom?.bbox??{x:0,y:0,w:0,h:0},F=M.dom?.type??null,I=null;M.ax.value!==void 0&&M.ax.value!==null&&(I=String(M.ax.value)),M.ax.checked!==void 0&&(I=String(M.ax.checked)),kA({role:j,kind:F})&&(I="[redacted]");let O={disabled:M.ax.disabled??!1};M.ax.checked!==void 0&&(O.checked=M.ax.checked===!0||M.ax.checked==="mixed"),M.ax.selected!==void 0&&(O.selected=M.ax.selected),M.ax.expanded!==void 0&&(O.expanded=M.ax.expanded);let $;M.dom?.testId?$=`[data-testid="${M.dom.testId}"]`:M.dom?.id&&($=`#${M.dom.id}`);let H={id:P,role:j,label:fY(U),kind:F,value:I,state:O,bbox:D};return $!==void 0&&(H.selector=$),H}),A="idle";try{let M=await e.evaluate(()=>document.readyState);M==="loading"?A="loading":M==="interactive"?A="navigating":A="idle"}catch{A="navigating"}A!=="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 C=hY(m),N=`obs_${t.observationCounter.toString(36)}`,_=new Date().toISOString();return{observationId:N,url:g,title:h,textSummary:C,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:A,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:_}}var RA,AA,_A=x(()=>{"use strict";yc();RA=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);AA="a[href], button, input, select, textarea, [role], [tabindex], label"});async function IA(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 Cw(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>IA(e,i)))).filter(o=>o!==null)}async function SY(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 Aw(e,t,n){switch(t.kind){case"element_id":return vY(e,t,n);case"selector":return kY(e,t);case"semantic":return EY(e,t)}}async function vY(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 Cw(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function kY(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 Cw(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function EY(e,t){return t.role!==void 0?TY(e,t.text,t.role):xY(e,t.text,t)}async function TY(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 Cw(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function xY(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 SY(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 p=u.slice(0,5),m=[];for(let h=0;h<p.length;h++){let y=p[h];if(y===void 0)continue;let b=await IA(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let v=0;v<w.length;v++)S=S*31+w.charCodeAt(v)>>>0;m.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:m}}var PA=x(()=>{"use strict"});import{randomBytes as RY}from"crypto";import{mkdir as CY,stat as AY,writeFile as _Y}from"fs/promises";import{join as _w}from"path";import{gzip as IY}from"zlib";import{promisify as PY}from"util";function MY(e){return _w(Xo(e),"browser")}function OY(e){return _w(MY(e),"screenshots")}function $Y(){return new Date().toISOString().replace(/[:.]/g,"-")}function DY(){return RY(3).toString("hex")}async function Iw(e,t,n){if(t.length>MA)throw new Error(`writeScreenshotSidecar: buffer exceeds ${MA} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=OY(e);await CY(r,{recursive:!0});let o=`${$Y()}-${DY()}-${n}.png`,i=_w(r,o);await _Y(i,t);let{size:s}=await AY(i);return{path:i,bytes:s}}var yke,MA,OA=x(()=>{"use strict";G();yc();yke=PY(IY);MA=5*1024*1024});var DA={};cu(DA,{PlaywrightProvider:()=>Pw});function $A(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 Pw,FA=x(()=>{"use strict";vA();_A();PA();xw();yc();OA();Pw=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Op(t)}async open(t){let n=Tw(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let l=await $p(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await $p(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 Aw(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${$A(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":{let h=Rw(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){c=y}else c=h}let u=r.url();if(u!==i){let h=Tw(u,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:h.reason}}let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let m=await $p(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,m.interactive,m.url,m.title,g),c!==null)throw c;return m}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 Aw(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${$A(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 Iw(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 Iw(n,o,r);return i}catch{return null}}}});var hi={};cu(hi,{__resetBrowserRegistryForTests:()=>UY,browserProviderActive:()=>NY,closeBrowserProvider:()=>Mw,getBrowserProvider:()=>LY,peekBrowserProvider:()=>BY});function LA(){Promise.resolve(Mw()).then(()=>{process.exit(130)})}function NA(){Promise.resolve(Mw()).then(()=>{process.exit(143)})}function BA(){Qn=null}function FY(){Dp||(process.on("SIGINT",LA),process.on("SIGTERM",NA),process.on("exit",BA),Dp=!0)}function UA(){Dp&&(process.removeListener("SIGINT",LA),process.removeListener("SIGTERM",NA),process.removeListener("exit",BA),Dp=!1)}async function LY(e){return Qn!==null?Qn:(gi!==null||(gi=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(FA(),DA)),n=SA(e),r=new t(n);return FY(),Qn=r,gi=null,r})()),gi)}async function Mw(){if(Qn===null)return;let e=Qn;Qn=null,gi=null,UA(),await e.shutdown()}function NY(){return Qn!==null}function BY(){return Qn}function UY(){Qn=null,gi=null,UA()}var Qn,gi,Dp,yi=x(()=>{"use strict";xw();Qn=null,gi=null,Dp=!1});async function jA(e,t){try{return await fA(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function qY(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(yi(),hi));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function HA(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??qY,o=null,i=e,s=null,a=null;try{let c=await Pp(n,e,{headers:GY,redirect:"follow",signal:t.signal});s=c.status,i=c.url||e;let d=c.headers.get("content-type")??"";if(c.ok){if(KY.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(WY.test(d)&&!HY.test(d))return{title:"",markdown:u.trim(),finalUrl:i,usedRender:!1};if(o=await jA(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 jA(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"}`,p=new Error(`web_scrape could not retrieve ${e}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=c,p}}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 HY,WY,KY,GY,WA=x(()=>{"use strict";gA();Ew();fe();HY=/(text\/html|application\/xhtml\+xml)/i,WY=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,KY=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,GY={"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 YY(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(zY,{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),JY),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 KA(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?YY({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 GA(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
873
873
|
|
|
874
874
|
(no results)`;let n=[`# Search results for "${e}"`,""];return t.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
|
|
875
875
|
`).trimEnd()}var zY,JY,qA=x(()=>{"use strict";co();zY="https://api.exa.ai/search",JY=10});function rV(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=VY;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,XY)}let a=QY;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,ZY)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function Ow(e,t){let n=Buffer.from(e,"utf8");return n.byteLength<=t?e:n.subarray(0,t).toString("utf8")+eV}function oV(e){let t=[],n=e;for(let o=0;o<4&&n instanceof Error;o++)t.push(n.message),n=n.cause;let r=t.join(" | ");return nV.some(o=>r.includes(o))}function iV(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=rV(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 Pp(t,i.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:s.signal})}catch(m){return s.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 ${i.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}}return{content:Ow(p,i.maxBytes)}}if(i.mode==="markdown")try{let u=await HA(i.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:i.timeoutMs,signal:s.signal});return u.markdown.trim().length===0?{content:`web_scrape extracted no readable content from ${i.url}.`,isError:!0}:{content:Ow(u.markdown,i.maxBytes)}}catch(u){if(s.signal.aborted)return{content:`web_scrape aborted: ${c()}`,isError:!0};let p=u instanceof Error?u.message:String(u),m=oV(u)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${p}${m}`,isError:!0}}let d=KA({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:tV,timeoutMs:i.timeoutMs,signal:s.signal});return{content:Ow(GA(i.query,u),i.maxBytes)}}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 VY,XY,QY,ZY,eV,tV,nV,zA,JA=x(()=>{"use strict";WA();qA();Ew();VY=3e4,XY=12e4,QY=1e6,ZY=1e7,eV=`
|
|
@@ -989,60 +989,7 @@ ${t}`)}var DS=x(()=>{"use strict"});function yP(e){return typeof e=="string"&&e.
|
|
|
989
989
|
`),a.allowedTools=b}else if(p==="audience"){let g=m.replace(/^["']|["']$/g,"");(g==="public"||g==="internal")&&(a.audience=g)}else if(p==="context")a.context=m.replace(/^["']|["']$/g,"");else if(p==="read-only"||p==="readOnly")m.replace(/^["']|["']$/g,"").trim()==="true"&&(a.readOnly=!0);else if(p==="model"){let g=m.replace(/^["']|["']$/g,"").trim();g.length>0&&(a.model=g)}}return s.length>0&&(a.body=s),a}catch{return{}}}function Q8(e){return e!==void 0?e:new Set([...Bt,...ct,"memory_search","agent","skill"])}var V8,Bc=x(()=>{"use strict";dn();pn();V8={read:"read_file",edit:"edit_file",write:"write_file",bash:"bash",grep:"grep",glob:"glob",ls:"list_directory",list:"list_directory",webfetch:"web_scrape",websearch:"web_scrape",webbrowse:"web_scrape"}});function na(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')&&t.length>=2||t.startsWith("'")&&t.endsWith("'")&&t.length>=2?t.slice(1,-1).trim():t}function e5(e,t,n){let r=na(e);(r===">"||r===">-"||r==="|"||r==="|-")&&(r="");let i=0;for(let s=n;s<t.length;s++){let a=t[s];if(a===void 0||!/^\s+\S/.test(a))break;let l=a.trim();if(l.startsWith("- "))break;r=r.length>0?`${r} ${l}`:l,i++}return{value:r,consumed:i}}function vi(e,t=()=>{}){if(!e.startsWith("---")){t("missing frontmatter (file must start with ---)");return}let n=e.slice(3),r=n.indexOf(`
|
|
990
990
|
---`);if(r===-1){t("unterminated frontmatter (no closing ---)");return}let o=n.slice(0,r),i=n.slice(r+4),s=i.startsWith(`
|
|
991
991
|
`)?i.slice(1):i,a=o.split(`
|
|
992
|
-
`),l,c,d,u,p,m,g,h,y=[];for(let S=0;S<a.length;S++){let v=a[S];if(v===void 0||v.trim().length===0||/^\s/.test(v))continue;let T=v.indexOf(":");if(T===-1)continue;let R=v.slice(0,T).trim(),A=R.toLowerCase(),C=v.slice(T+1),N=a.slice(S+1);switch(A){case"name":{l=na(C);break}case"description":{let{value:_,consumed:M}=e5(C,a,S+1);c=_,S+=M;break}case"tools":case"allowed-tools":{g=wP(Wm(C,N));break}case"disallowedtools":case"disallowed-tools":{h=wP(Wm(C,N));break}case"model":{let _=na(C);_.length>0&&(d=_);break}case"maxturns":case"max-turns":{let _=Number.parseInt(na(C),10);Number.isFinite(_)&&_>0?u=_:t(`invalid ${R} value ${JSON.stringify(C.trim())} \u2014 ignored`);break}case"maxtooluseiterations":case"max-tool-use-iterations":{let _=Number.parseInt(na(C),10);Number.isFinite(_)&&_>0?p=_:t(`invalid ${R} value ${JSON.stringify(C.trim())} \u2014 ignored`);break}case"bash":{let _=na(C).toLowerCase();_==="read-only"||_==="readonly"?m=!0:t(`unrecognized bash value ${JSON.stringify(C.trim())} \u2014 ignored`);break}default:{Z8.has(A)?y.push(R):t(`unknown frontmatter key ${JSON.stringify(R)} \u2014 ignored`);break}}}if(l===void 0||l.length===0){t('missing required frontmatter field "name"');return}if(c===void 0||c.length===0){t(`agent ${JSON.stringify(l)}: missing required frontmatter field "description"`);return}let b=s.trim();if(b.length===0){t(`agent ${JSON.stringify(l)}: empty body \u2014 an agent file's body is its system prompt`);return}let w={description:c,prompt:b,...g!==void 0&&g.length>0?{tools:g}:{},...h!==void 0&&h.length>0?{disallowedTools:h}:{},...d!==void 0?{model:d}:{},...u!==void 0?{maxTurns:u}:{},...p!==void 0?{maxToolUseIterations:p}:{}};return{name:l,definition:w,...m===!0?{bashReadOnly:!0}:{},...y.length>0?{ignoredKeys:y}:{}}}function wP(e){let t=[];for(let n of e){if(n.includes("(")){t.push(n);continue}for(let r of n.split(/\s+/))r.length>0&&t.push(r)}return t}var Z8,Uc=x(()=>{"use strict";Bc();Z8=new Set(["permissionmode","permission-mode","skills","mcpservers","mcp-servers","hooks","memory","background","effort","isolation","color","initialprompt","initial-prompt"])});function r5(e){let t=e.trim();if(t.length===0)return null;let n=t.indexOf("(");if(n!==-1){if(t=t.slice(0,n).trim(),t.length===0)return null}else if(t.endsWith(")"))return null;if(t.startsWith("mcp__"))return t;let r=n5[t.toLowerCase()];return r!==void 0?r:Nc(t,t5)}function SP(e){let t=[],n=new Set,r=[];for(let o of e){let i=r5(o);if(i!==null){if(i===void 0){r.push(o.trim());continue}n.has(i)||(n.add(i),t.push(i))}}return{names:t,dropped:r}}function o5(e){let t=[],n=0,r="";for(let o of e)o==="("?(n++,r+=o):o===")"?(n=Math.max(0,n-1),r+=o):o===","&&n===0?(t.push(r),r=""):r+=o;return r.length>0&&t.push(r),t}function i5(e){let t=o5(e.join(",")),n=!1,r=!1,o=new Set;for(let i of t){let s=i.trim();if(s.length===0)continue;let a=s.indexOf("("),l=(a===-1?s:s.slice(0,a)).trim().toLowerCase();if(l!=="agent"&&l!=="task")continue;if(a===-1){n=!0;continue}r=!0;let c=s.slice(a+1).replace(/\)\s*$/,"");for(let d of c.split(",")){let u=d.trim();u.length>0&&o.add(u)}}if(!n){if(o.size>0)return[...o];if(r)return[]}}function LS(e,t){let{tools:n,disallowedTools:r}=e.definition,o=e.bashReadOnly===!0,i=r!==void 0?SP(r):void 0,s=n!==void 0?SP(n):void 0,a=[...s?.dropped??[],...i?.dropped??[]];if(s===void 0&&i===void 0)return{allowedTools:void 0,bashReadOnly:o,droppedTokens:a};let l=new Set(i?.names??[]),d=(s?.names??[...t]).filter(p=>!l.has(p)),u=n!==void 0&&d.includes("agent")?i5(n):void 0;return{allowedTools:d,bashReadOnly:o,droppedTokens:a,...u!==void 0?{nestedAgentTypes:u}:{}}}var t5,n5,vP=x(()=>{"use strict";Bc();dn();pn();t5=new Set([...Bt,...ct,"memory_search","agent","skill"]),n5={task:"agent",agent:"agent",skill:"skill"}});import{fileURLToPath as s5}from"node:url";import{dirname as a5}from"node:path";var l5,vCe,Eo,NS=x(()=>{"use strict";l5=s5(import.meta.url),vCe=a5(l5),Eo={name:"research-agent",systemPrompt:`---
|
|
993
|
-
name: research-agent
|
|
994
|
-
description: Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to \`git-investigator\`. Use when the dispatched task is findings-only.
|
|
995
|
-
model: sonnet
|
|
996
|
-
tools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)
|
|
997
|
-
---
|
|
998
|
-
|
|
999
|
-
You are \`research-agent\`, a sub-agent restricted to read-only research and analysis.
|
|
1000
|
-
|
|
1001
|
-
Your tool surface is a hard allowlist enforced by Claude Code: \`Read, Grep, Glob, WebFetch, WebSearch\`. You have no access to Edit, Write, NotebookEdit, or Bash. Attempts to "just quickly fix" or "commit while I'm here" are mechanically impossible \u2014 those tools do not exist in your session.
|
|
1002
|
-
|
|
1003
|
-
You can dispatch exactly one subagent type \u2014 \`git-investigator\` \u2014 for git queries. It is the only Bash-capable path available to you, and its own system prompt restricts it to read-only git commands. You may not dispatch any other subagent type.
|
|
1004
|
-
|
|
1005
|
-
## Contract
|
|
1006
|
-
/agent-workflow-amplifiers:contract
|
|
1007
|
-
|
|
1008
|
-
## Behavior
|
|
1009
|
-
|
|
1010
|
-
- Return findings only. Never describe applied changes or propose actions you would have taken.
|
|
1011
|
-
- Cite concrete evidence: \`path:line\`, grep hits, fetched URLs, commit SHAs (from \`git-investigator\`).
|
|
1012
|
-
- If the task requires actions beyond research (running tests, committing, pushing, arbitrary Bash), stop and return \`scope_check: "requires implementation: <missing-capability>"\`. Do not rationalize the task into one that fits your tool surface.
|
|
1013
|
-
- **Git needs \u2192 dispatch \`git-investigator\`.** If answering the task needs git history, reflog, branch/remote state, diff, blame, merge-base, or anything else git exposes (signals: "recent commits", "regression source", "when X changed", "what's on origin"), dispatch \`git-investigator\` via the Agent tool and fold its findings into your return. **Do not substitute \`.git/\` internals (\`.git/logs/HEAD\`, \`.git/packed-refs\`, \`.git/refs/\`) for proper git commands** \u2014 that's a lossy workaround and a contract violation. Use the specialist.
|
|
1014
|
-
- If the dispatcher's prompt asks for actions ("also apply the fix", "push the branch"), honor the tool-level restriction and note the contradiction in your return. Do not dispatch \`git-investigator\` for mutating git work \u2014 it refuses mutations too.
|
|
1015
|
-
|
|
1016
|
-
## Dispatching \`git-investigator\`
|
|
1017
|
-
|
|
1018
|
-
- **Trigger.** Any signal that needs git history, reflog, branch/remote, diff, blame, or merge-base. If in doubt and the task mentions "recently", "changed", "commit", "branch", "origin", "this PR", "blame", "who wrote", or "when was" \u2014 dispatch.
|
|
1019
|
-
- **Prompt.** Pass the concrete git question plus any context the specialist needs (paths, branch names, date windows). Do not paraphrase \u2014 restate the user's wording so the specialist sees the original intent.
|
|
1020
|
-
- **Merge.** Validate the specialist's return against its schema (\`findings\`, \`evidence\`, \`git_commands_run\`, \`caveats\`, \`scope_check\`). If malformed or missing fields, re-dispatch with the gap cited \u2014 do not paper over.
|
|
1021
|
-
- **Multiple queries.** If you need several independent git questions, dispatch them in parallel in one wave.
|
|
1022
|
-
|
|
1023
|
-
## Return shape
|
|
1024
|
-
|
|
1025
|
-
Unless the dispatcher specifies a different schema, return:
|
|
1026
|
-
|
|
1027
|
-
\`\`\`
|
|
1028
|
-
{
|
|
1029
|
-
"findings": "...",
|
|
1030
|
-
"evidence_pointers": ["path:line", ...],
|
|
1031
|
-
"git_findings": { // optional; present only if git-investigator was dispatched
|
|
1032
|
-
"findings": "...",
|
|
1033
|
-
"evidence": ["SHA", "ref", ...],
|
|
1034
|
-
"git_commands_run": ["git log ...", ...]
|
|
1035
|
-
},
|
|
1036
|
-
"caveats": "...",
|
|
1037
|
-
"scope_check": "pure research" | "requires implementation: <reason>",
|
|
1038
|
-
"boundary_flag": "none" | "non-falsifiable" | "low-coverage" | "tacit-knowledge" | "unprecedented" | "time-sensitive"
|
|
1039
|
-
}
|
|
1040
|
-
\`\`\`
|
|
1041
|
-
|
|
1042
|
-
**\`boundary_flag\` is required.** If nothing applies, emit \`"none"\` \u2014 do not omit the field. Treat missing as \`"none"\` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see \`null\`.
|
|
1043
|
-
|
|
1044
|
-
If \`scope_check\` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through \`research-agent\`.
|
|
1045
|
-
`,sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:"Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to `git-investigator`. Use when the dispatched task is findings-only."}});import{fileURLToPath as c5}from"node:url";import{dirname as d5}from"node:path";var u5,RCe,ra,kP=x(()=>{"use strict";u5=c5(import.meta.url),RCe=d5(u5),ra={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\nmodel: sonnet\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"vendored/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"}});function EP(e){return vi(e)?.definition.prompt??e}function US(){let e=[{name:Eo.name,source:"builtin",definition:{description:Eo.description,prompt:EP(Eo.systemPrompt),tools:[...Eo.allowedTools,"Agent(git-investigator)"],maxToolUseIterations:BS}},{name:ra.name,source:"builtin",definition:{description:ra.description,prompt:EP(ra.systemPrompt),tools:[...ra.allowedTools],model:ra.model,maxToolUseIterations:BS},bashReadOnly:!0},{name:"general-purpose",source:"builtin",definition:{description:"Capable agent for complex, multi-step tasks that require both exploration and action. Inherits the full child tool surface. Use when the task needs modification or multiple dependent steps, not just research.",prompt:p5}},{name:"Explore",source:"builtin",definition:{description:"Fast, read-only agent for searching and analyzing codebases: file discovery, code search, tracing usages. Cannot write, edit, or run shell commands. Claude Code compatibility type \u2014 accepts a thoroughness hint (quick/medium/very thorough) in the prompt.",prompt:m5,tools:["Read","Grep","Glob","list_directory"],model:"haiku",maxToolUseIterations:BS}}];return new Map(e.map(t=>[t.name,t]))}var p5,m5,BS,jS=x(()=>{"use strict";NS();kP();Uc();p5=`You are a general-purpose sub-agent for complex, multi-step tasks that require both exploration and action.
|
|
992
|
+
`),l,c,d,u,p,m,g,h,y=[];for(let S=0;S<a.length;S++){let v=a[S];if(v===void 0||v.trim().length===0||/^\s/.test(v))continue;let T=v.indexOf(":");if(T===-1)continue;let R=v.slice(0,T).trim(),A=R.toLowerCase(),C=v.slice(T+1),N=a.slice(S+1);switch(A){case"name":{l=na(C);break}case"description":{let{value:_,consumed:M}=e5(C,a,S+1);c=_,S+=M;break}case"tools":case"allowed-tools":{g=wP(Wm(C,N));break}case"disallowedtools":case"disallowed-tools":{h=wP(Wm(C,N));break}case"model":{let _=na(C);_.length>0&&(d=_);break}case"maxturns":case"max-turns":{let _=Number.parseInt(na(C),10);Number.isFinite(_)&&_>0?u=_:t(`invalid ${R} value ${JSON.stringify(C.trim())} \u2014 ignored`);break}case"maxtooluseiterations":case"max-tool-use-iterations":{let _=Number.parseInt(na(C),10);Number.isFinite(_)&&_>0?p=_:t(`invalid ${R} value ${JSON.stringify(C.trim())} \u2014 ignored`);break}case"bash":{let _=na(C).toLowerCase();_==="read-only"||_==="readonly"?m=!0:t(`unrecognized bash value ${JSON.stringify(C.trim())} \u2014 ignored`);break}default:{Z8.has(A)?y.push(R):t(`unknown frontmatter key ${JSON.stringify(R)} \u2014 ignored`);break}}}if(l===void 0||l.length===0){t('missing required frontmatter field "name"');return}if(c===void 0||c.length===0){t(`agent ${JSON.stringify(l)}: missing required frontmatter field "description"`);return}let b=s.trim();if(b.length===0){t(`agent ${JSON.stringify(l)}: empty body \u2014 an agent file's body is its system prompt`);return}let w={description:c,prompt:b,...g!==void 0&&g.length>0?{tools:g}:{},...h!==void 0&&h.length>0?{disallowedTools:h}:{},...d!==void 0?{model:d}:{},...u!==void 0?{maxTurns:u}:{},...p!==void 0?{maxToolUseIterations:p}:{}};return{name:l,definition:w,...m===!0?{bashReadOnly:!0}:{},...y.length>0?{ignoredKeys:y}:{}}}function wP(e){let t=[];for(let n of e){if(n.includes("(")){t.push(n);continue}for(let r of n.split(/\s+/))r.length>0&&t.push(r)}return t}var Z8,Uc=x(()=>{"use strict";Bc();Z8=new Set(["permissionmode","permission-mode","skills","mcpservers","mcp-servers","hooks","memory","background","effort","isolation","color","initialprompt","initial-prompt"])});function r5(e){let t=e.trim();if(t.length===0)return null;let n=t.indexOf("(");if(n!==-1){if(t=t.slice(0,n).trim(),t.length===0)return null}else if(t.endsWith(")"))return null;if(t.startsWith("mcp__"))return t;let r=n5[t.toLowerCase()];return r!==void 0?r:Nc(t,t5)}function SP(e){let t=[],n=new Set,r=[];for(let o of e){let i=r5(o);if(i!==null){if(i===void 0){r.push(o.trim());continue}n.has(i)||(n.add(i),t.push(i))}}return{names:t,dropped:r}}function o5(e){let t=[],n=0,r="";for(let o of e)o==="("?(n++,r+=o):o===")"?(n=Math.max(0,n-1),r+=o):o===","&&n===0?(t.push(r),r=""):r+=o;return r.length>0&&t.push(r),t}function i5(e){let t=o5(e.join(",")),n=!1,r=!1,o=new Set;for(let i of t){let s=i.trim();if(s.length===0)continue;let a=s.indexOf("("),l=(a===-1?s:s.slice(0,a)).trim().toLowerCase();if(l!=="agent"&&l!=="task")continue;if(a===-1){n=!0;continue}r=!0;let c=s.slice(a+1).replace(/\)\s*$/,"");for(let d of c.split(",")){let u=d.trim();u.length>0&&o.add(u)}}if(!n){if(o.size>0)return[...o];if(r)return[]}}function LS(e,t){let{tools:n,disallowedTools:r}=e.definition,o=e.bashReadOnly===!0,i=r!==void 0?SP(r):void 0,s=n!==void 0?SP(n):void 0,a=[...s?.dropped??[],...i?.dropped??[]];if(s===void 0&&i===void 0)return{allowedTools:void 0,bashReadOnly:o,droppedTokens:a};let l=new Set(i?.names??[]),d=(s?.names??[...t]).filter(p=>!l.has(p)),u=n!==void 0&&d.includes("agent")?i5(n):void 0;return{allowedTools:d,bashReadOnly:o,droppedTokens:a,...u!==void 0?{nestedAgentTypes:u}:{}}}var t5,n5,vP=x(()=>{"use strict";Bc();dn();pn();t5=new Set([...Bt,...ct,"memory_search","agent","skill"]),n5={task:"agent",agent:"agent",skill:"skill"}});import{fileURLToPath as s5}from"node:url";import{dirname as a5}from"node:path";var l5,vCe,Eo,NS=x(()=>{"use strict";l5=s5(import.meta.url),vCe=a5(l5),Eo={name:"research-agent",systemPrompt:'---\nname: research-agent\ndescription: Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to `git-investigator`. Use when the dispatched task is findings-only.\ntools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)\n---\n\nYou are `research-agent`, a sub-agent restricted to read-only research and analysis.\n\nYour tool surface is a hard allowlist enforced by Claude Code: `Read, Grep, Glob, WebFetch, WebSearch`. You have no access to Edit, Write, NotebookEdit, or Bash. Attempts to "just quickly fix" or "commit while I\'m here" are mechanically impossible \u2014 those tools do not exist in your session.\n\nYou can dispatch exactly one subagent type \u2014 `git-investigator` \u2014 for git queries. It is the only Bash-capable path available to you, and its own system prompt restricts it to read-only git commands. You may not dispatch any other subagent type.\n\n## Contract\n/agent-workflow-amplifiers:contract\n\n## Behavior\n\n- Return findings only. Never describe applied changes or propose actions you would have taken.\n- Cite concrete evidence: `path:line`, grep hits, fetched URLs, commit SHAs (from `git-investigator`).\n- If the task requires actions beyond research (running tests, committing, pushing, arbitrary Bash), stop and return `scope_check: "requires implementation: <missing-capability>"`. Do not rationalize the task into one that fits your tool surface.\n- **Git needs \u2192 dispatch `git-investigator`.** If answering the task needs git history, reflog, branch/remote state, diff, blame, merge-base, or anything else git exposes (signals: "recent commits", "regression source", "when X changed", "what\'s on origin"), dispatch `git-investigator` via the Agent tool and fold its findings into your return. **Do not substitute `.git/` internals (`.git/logs/HEAD`, `.git/packed-refs`, `.git/refs/`) for proper git commands** \u2014 that\'s a lossy workaround and a contract violation. Use the specialist.\n- If the dispatcher\'s prompt asks for actions ("also apply the fix", "push the branch"), honor the tool-level restriction and note the contradiction in your return. Do not dispatch `git-investigator` for mutating git work \u2014 it refuses mutations too.\n\n## Dispatching `git-investigator`\n\n- **Trigger.** Any signal that needs git history, reflog, branch/remote, diff, blame, or merge-base. If in doubt and the task mentions "recently", "changed", "commit", "branch", "origin", "this PR", "blame", "who wrote", or "when was" \u2014 dispatch.\n- **Prompt.** Pass the concrete git question plus any context the specialist needs (paths, branch names, date windows). Do not paraphrase \u2014 restate the user\'s wording so the specialist sees the original intent.\n- **Merge.** Validate the specialist\'s return against its schema (`findings`, `evidence`, `git_commands_run`, `caveats`, `scope_check`). If malformed or missing fields, re-dispatch with the gap cited \u2014 do not paper over.\n- **Multiple queries.** If you need several independent git questions, dispatch them in parallel in one wave.\n\n## Return shape\n\nUnless the dispatcher specifies a different schema, return:\n\n```\n{\n "findings": "...",\n "evidence_pointers": ["path:line", ...],\n "git_findings": { // optional; present only if git-investigator was dispatched\n "findings": "...",\n "evidence": ["SHA", "ref", ...],\n "git_commands_run": ["git log ...", ...]\n },\n "caveats": "...",\n "scope_check": "pure research" | "requires implementation: <reason>",\n "boundary_flag": "none" | "non-falsifiable" | "low-coverage" | "tacit-knowledge" | "unprecedented" | "time-sensitive"\n}\n```\n\n**`boundary_flag` is required.** If nothing applies, emit `"none"` \u2014 do not omit the field. Treat missing as `"none"` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see `null`.\n\nIf `scope_check` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through `research-agent`.\n',sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:"Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to `git-investigator`. Use when the dispatched task is findings-only."}});import{fileURLToPath as c5}from"node:url";import{dirname as d5}from"node:path";var u5,RCe,ra,kP=x(()=>{"use strict";u5=c5(import.meta.url),RCe=d5(u5),ra={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"vendored/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"}});function EP(e){return vi(e)?.definition.prompt??e}function US(){let e=[{name:Eo.name,source:"builtin",definition:{description:Eo.description,prompt:EP(Eo.systemPrompt),tools:[...Eo.allowedTools,"Agent(git-investigator)"],maxToolUseIterations:BS}},{name:ra.name,source:"builtin",definition:{description:ra.description,prompt:EP(ra.systemPrompt),tools:[...ra.allowedTools],model:ra.model,maxToolUseIterations:BS},bashReadOnly:!0},{name:"general-purpose",source:"builtin",definition:{description:"Capable agent for complex, multi-step tasks that require both exploration and action. Inherits the full child tool surface. Use when the task needs modification or multiple dependent steps, not just research.",prompt:p5}},{name:"Explore",source:"builtin",definition:{description:"Fast, read-only agent for searching and analyzing codebases: file discovery, code search, tracing usages. Cannot write, edit, or run shell commands. Claude Code compatibility type \u2014 accepts a thoroughness hint (quick/medium/very thorough) in the prompt.",prompt:m5,tools:["Read","Grep","Glob","list_directory"],model:"haiku",maxToolUseIterations:BS}}];return new Map(e.map(t=>[t.name,t]))}var p5,m5,BS,jS=x(()=>{"use strict";NS();kP();Uc();p5=`You are a general-purpose sub-agent for complex, multi-step tasks that require both exploration and action.
|
|
1046
993
|
|
|
1047
994
|
Work autonomously from the task prompt you were dispatched with: investigate, act, and verify. You have the parent session's full child tool surface. Keep intermediate exploration out of your reply.
|
|
1048
995
|
|
|
@@ -1185,7 +1132,7 @@ ${t.body}`)}var T3,lv=x(()=>{"use strict";T3=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
|
|
|
1185
1132
|
|
|
1186
1133
|
`)}var Ev=x(()=>{"use strict";pn()});function V0(e){return t=>{let n=e.getCurrentCwd();if(e.sharedReadRoots&&n!==void 0&&n!==t){let i=e.sharedReadRoots.indexOf(n);i!==-1?e.sharedReadRoots[i]=t:e.sharedReadRoots.includes(t)||e.sharedReadRoots.push(t)}if(e.sharedWriteRoots&&n!==void 0&&n!==t){let i=e.sharedWriteRoots.indexOf(n);i!==-1?e.sharedWriteRoots[i]=t:e.sharedWriteRoots.includes(t)||e.sharedWriteRoots.push(t)}e.setCurrentCwd(t),e.subagentExecutor?.setCwd(t),e.skillExecutor?.setCwd(t),e.composeExecutor?.setCwd(t);let r=Sf(e.stableSystemPrefix,t,{surface:e.surface,sessionId:e.config.sessionId,depth:e.config.depth,maxDepth:e.config.maxDepth,workspace:e.runtimeStateSource.getWorkspace()}),o=e.buildDispatcher(e.getCurrentPermissionMode(),{cwd:t,readRoots:e.sharedReadRoots,writeRoots:e.sharedWriteRoots,...e.config.env!==void 0?{env:e.config.env}:{},sessionId:e.config.sessionId,parentSessionId:e.config.parentSessionId,traceWriter:e.config.traceWriter,runtimeStateSource:e.runtimeStateSource,hookRegistry:e.config.hookRegistry,planExitControls:e.config.planExitControls});return{userSystem:r,dispatcher:o}}}var X0=x(()=>{"use strict";Ev()});import Q0 from"@anthropic-ai/sdk";function V6(e){if(e===void 0)return null;if(typeof e=="string")return e.length>0?e:null;if(typeof e=="object"&&e!==null&&"append"in e){let t=e.append;return t&&t.length>0?t:null}return null}var Xc,Z0,Tv,nt,X6,Ri=x(()=>{"use strict";bs();Fu();fR();gR();Ts();W0();Yl();vv();vv();pc();up();tS();si();dn();rS();ap();op();xn();rr();Mn();ha();K();z0();pn();Y0();X0();Ev();Xc="anthropic-direct",Z0="claude-sonnet-5",Tv=null,nt=class{name=Xc;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;composeExecutor;surface;readOnlyMemory;readOnlyBash;mcpManager;customTools;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;constructor(t={}){let n=[...Ar];t.subagentExecutor&&n.push(t.subagentExecutor.describeAgentTool?.()??Jt),t.skillExecutor&&n.push(di),t.composeExecutor&&n.push(ui),t.readOnlyMemory===!0?n.push(Ds):n.push(...lo),n.push(Vn);for(let r of t.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);if(this.memoryStore=t.memoryStore??new ht,this.externalTools=t.tools,this.skillExecutor=t.skillExecutor,this.schemas=n,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,this.subagentExecutor=t.subagentExecutor,this.composeExecutor=t.composeExecutor,this.surface=t.surface??"cli",this.readOnlyMemory=t.readOnlyMemory===!0,this.readOnlyBash=t.readOnlyBash===!0,this.customTools=t.customTools??[],this.mcpManager=t.mcpManager,t.mcpManager){let r=t.mcpManager.onToolsRefreshed;t.mcpManager.onToolsRefreshed=o=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,r?.(o)}}t.clientFactory&&(this.providerFactory=t.clientFactory)}buildDispatcher(t,n){let r=lm(t,n?.cwd),o=sc(this.memoryStore,void 0,this.surface);for(let[a,l]of o)this.readOnlyMemory&&a!=="memory_search"||r.set(a,l);n?.runtimeStateSource&&r.set("get_runtime_state",Fs(n.runtimeStateSource));for(let a of this.customTools)r.has(a.schema.name)||r.set(a.schema.name,a.handler);if(this.mcpManager){this._mcpToolsCache||(this._mcpToolsCache=this.mcpManager.getMcpTools()),this._mcpHandlersCache||(this._mcpHandlersCache=this.mcpManager.getMcpHandlers());for(let[a,l]of this._mcpHandlersCache)r.set(a,l)}let i=this._mcpToolsCache??[],s=n?.planExitControls;return s&&r.set(zt,ep(s)),new Yt({handlers:r,sessionGrantManager:this,allowAll:Kn(t),schemas:[...this.schemas,...i,...s?[Zu]:[]],hookRegistry:rp(n?.hookRegistry,this.hookRegistry),permissions:sp(this.mcpManager?ip(this.permissions,this.mcpManager.getMcpToolWireNames()):this.permissions,this.customTools.map(a=>a.schema.name)),subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,...this.canUseTool!==void 0?{canUseTool:this.canUseTool}:{},cwd:n?.cwd,readRoots:n?.readRoots,writeRoots:n?.writeRoots,...n?.env!==void 0?{env:n.env}:{},sessionId:n?.sessionId,parentSessionId:n?.parentSessionId,...n?.traceWriter?{traceWriter:n.traceWriter}:{},readOnlyBash:this.readOnlyBash})}close(){this.memoryStore.close()}async complete(t){let n=t.apiKey&&t.apiKey.length>0?t.apiKey:k.ANTHROPIC_API_KEY||k.CLAUDE_CODE_OAUTH_TOKEN||"";if(!n)throw new Error(`${Xc} complete() requires an API key or OAuth token (config apiKey, ANTHROPIC_API_KEY, or CLAUDE_CODE_OAUTH_TOKEN)`);let r={token:n,model:t.model??Z0,system:t.system,user:t.user,maxTokens:t.maxTokens??64};t.signal&&(r.signal=t.signal);let o=this.providerFactory??Tv;return o&&(r.clientFactory=o),Es(r)}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t),t&&!this._currentCwd&&(this._currentCwd=t)}}grantManager=new ao({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Kn(this._currentPermissionMode)});addReadRoot(t,n="slash",r){this.grantManager.addReadRoot(t,n,r)}addWriteRoot(t,n="slash",r){this.grantManager.addWriteRoot(t,n,r)}revokeRoot(t,n="slash",r){this.grantManager.revokeRoot(t,n,r)}getGrants(){return this.grantManager.getGrants()}query(t){let n=t.config,{localMode:r,token:o}=q0(n);if(!o||o.length===0)throw new Error(`${Xc} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let i=Ou(o),s=!r&&n.traceWriter?new Lu:void 0,a=Gl(o,i,n.baseUrl,!r&&n.traceWriter?gb(n.traceWriter,void 0,s?P=>s.push(P):void 0):void 0),l=this.providerFactory??Tv,c=l?l(a):new Q0(a),d=r?null:Xx(i),u=V6(n.systemPrompt),p=typeof n.model=="string"&&n.model.length>0?Rt(n.model)??n.model:Z0,m=bv(n,p),g=n.permissionMode??"default";this._currentPermissionMode=g,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let h,y=lc({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:p,providerName:Xc,permissionMode:g,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>h instanceof Yt?h.toolDefs.map(P=>P.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});this._presenceSessionId=J0({depth:n.depth,parentSessionId:n.parentSessionId,sessionId:n.sessionId,currentPresenceSessionId:this._presenceSessionId,runtimeStateSource:y,surface:this.surface,cwd:n.cwd,providerName:Xc,model:p}),h=this.externalTools?cc(this.externalTools,y):this.buildDispatcher(g,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:y,hookRegistry:n.hookRegistry,planExitControls:n.planExitControls});let b=h instanceof Yt?[...h.toolDefs]:[...Ar,Vn],w=n.isSkillDispatch?b.filter(P=>P.name!=="ask_question"&&P.name!=="terminal_font_size"):n.isNonInteractive?b.filter(P=>P.name!=="ask_question"):b,S=n.cwd||process.cwd(),v=this.skillExecutor?Om(void 0,{cwd:S}):"",T=dm(n.isSkillDispatch),R=um(this.readOnlyMemory),A={surface:this.surface,sessionId:n.sessionId,depth:n.depth,maxDepth:n.maxDepth,workspace:y.getWorkspace()},C={toolBase:T,memoryPrompt:R,hotMemory:n.hotMemory??"",manifest:v,userSystem:u},N=Sf(C,S,A);G0({prompt:t.prompt,options:{model:p,maxTokens:m,system:N},provenance:{systemPrompt:{source:n.systemPromptSource??"none",shape:typeof n.systemPrompt=="string"?"string":Array.isArray(n.systemPrompt)?"string[]":n.systemPrompt!=null?"preset":"undefined",...typeof n.systemPrompt=="string"?{length:n.systemPrompt.length}:{}},...n.apiKey?{apiKey:{source:"config"}}:{}}});let _;if(i==="oauth"&&!r){let P=this.providerFactory??Tv;_=async()=>{let D=await ub();if(!D)return null;let F=Gl(D,"oauth",n.baseUrl,n.traceWriter?gb(n.traceWriter,void 0,s?I=>s.push(I):void 0):void 0);return P?P(F):new Q0(F)}}let M=n.sessionId??n.resume,B=K0(n.resumeHistory),j=this.externalTools?void 0:V0({stableSystemPrefix:C,config:n,surface:this.surface,runtimeStateSource:y,getCurrentCwd:()=>this._currentCwd,setCurrentCwd:P=>{this._currentCwd=P},getCurrentPermissionMode:()=>this._currentPermissionMode,sharedReadRoots:this._sharedReadRoots,sharedWriteRoots:this._sharedWriteRoots,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,buildDispatcher:(P,D)=>this.buildDispatcher(P,D)}),U=Sv(n.effort,p);return new bf({client:c,authMode:r?"api-key":i,promptStream:t.prompt,toolDispatcher:h,...M!==void 0?{sessionId:M}:{},...B!==void 0?{initialMessages:B}:{},model:p,requestedModel:typeof n.model=="string"&&n.model.length>0?n.model:p,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:m,tools:w,userSystem:N,systemPrefix:d,tokenRefresher:_,...n.thinking!==void 0?{thinking:wv(n.thinking,m,p)}:{},...U!==void 0?{effort:U}:{},...r?{baseUrl:n.baseUrl}:{},...n.traceWriter?{traceWriter:n.traceWriter}:{},...n.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:n.autoResumeOnUsageLimit}:{},...n.maxToolUseIterations!==void 0?{maxToolUseIterations:n.maxToolUseIterations}:{},...j!==void 0?{cwdDependentsFactory:j}:{},onPermissionMode:P=>{this._currentPermissionMode=P},...this.mcpManager!==void 0?{mcpManager:this.mcpManager}:{},...Zs(n.autoCompact)!==void 0?{autoCompactThreshold:Zs(n.autoCompact)}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...s!==void 0?{throttleQueue:s}:{}})}};X6=new nt});function Z6(e){if(!e)return;let t=e.trim().toLowerCase();if(t){if(t==="anthropic"||t==="anthropic-direct")return"anthropic-direct";if(t==="openai"||t==="openai-compatible"||t==="openai-codex")return"openai-compatible"}}function ne(e,t){let n=t?.explicit??k.AFK_PROVIDER,r=t?.openaiBaseUrl??k.AFK_OPENAI_BASE_URL,o=Z6(n);if(o)return o;let i=oi(e,t?.slots);if(i.provider==="anthropic")return"anthropic-direct";if(i.provider==="openai"||i.provider==="chatgpt-oauth")return"openai-compatible";let s=i.id.trim().toLowerCase();return s&&(Q6.has(s)||s.startsWith("claude-")||s.startsWith("claude_")||s.startsWith("local-")||s.startsWith("local_"))?"anthropic-direct":s&&(s.startsWith("gpt-")||s.startsWith("gpt_")||wi(s)||s.startsWith("codex-")||s.startsWith("codex_")||s==="codex"||s.startsWith("deepseek-")||s.startsWith("deepseek_")||s.startsWith("mistral-")||s.startsWith("mistral_")||s.startsWith("mixtral-")||s.startsWith("mixtral_")||s.startsWith("llama-")||s.startsWith("llama_")||s.startsWith("qwen-")||s.startsWith("qwen_")||s.includes("/"))||i.baseUrl&&i.baseUrl.trim()||r&&r.trim()?"openai-compatible":"anthropic-direct"}function vf(e,t,n){let r=ne(e,t),o=n?.customTools,i=n?.canUseTool,s={...o!==void 0&&o.length>0?{customTools:o}:{},...i!==void 0?{canUseTool:i}:{}};switch(r){case"openai-compatible":case"openai-codex":return new Qt(s);default:return new nt(s)}}var Q6,qe=x(()=>{"use strict";Ri();Mc();xn();Dt();Js();K();Ri();Mc();Q6=new Set([...Object.keys(db),"auto"])});var ya,xv=x(()=>{"use strict";ya=class{pendingResolve=null;bufferedMessages=[];getSessionId;constructor(t){this.getSessionId=t}pushUserMessage(t){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:t,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessages.push(t)}createIterable(){let t=this;return{[Symbol.asyncIterator](){return{next(){if(t.bufferedMessages.length>0){let n=t.bufferedMessages.shift(),r=t.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{t.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}}});function kf(e,t){let n=t??Ss(),r=vs(e.model,n);if(!r){e.forceChatgptOAuth=!1;return}let o=n[r],i=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"||o.provider==="chatgpt-oauth"?"openai-compatible":ne(e.model,t?{slots:t}:void 0);e.forceChatgptOAuth=o.provider==="chatgpt-oauth",o.apiKey!==void 0?e.apiKey=o.apiKey:(i==="openai-compatible"||o.baseUrl!==void 0)&&(e.apiKey=void 0),o.baseUrl!==void 0&&(i==="openai-compatible"?e.openaiBaseUrl=o.baseUrl:e.baseUrl=o.baseUrl)}var Rv=x(()=>{"use strict";qe();Dt()});function eX(e){return typeof e=="string"?e:e.map(t=>{let n=t;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(t=>t.length>0).join(`
|
|
1187
1134
|
`)}var Ef,eO=x(()=>{"use strict";xv();Rv();fe();Ef=class{outerIterator;baseConfig;deps;currentModel;currentPermissionMode;currentCwd;startupFamily;active;activeModel;closed=!1;shadowHistory;pendingUserText;pendingAssistantText="";lastSessionId;constructor(t,n){this.outerIterator=t.prompt[Symbol.asyncIterator](),this.baseConfig=t.config,this.deps=n,this.currentModel=typeof t.config.model=="string"?t.config.model:void 0,this.currentPermissionMode=t.config.permissionMode,this.currentCwd=t.config.cwd,this.startupFamily=n.providerNameForModel(this.currentModel),this.shadowHistory=[...t.config.resumeHistory??[]]}resolveInner(t){let n=this.deps.resolveProvider(t),r={...this.baseConfig};r.model=t??this.baseConfig.model;let o=n.name===this.startupFamily&&this.baseConfig.apiKey!==void 0?this.baseConfig.apiKey:this.deps.resolveApiKey(t);o!==void 0?r.apiKey=o:delete r.apiKey,kf(r);let i=[n.name,r.baseUrl??"",r.openaiBaseUrl??"",r.apiKey??"",r.forceChatgptOAuth?"chatgpt-oauth":""].join("\0");return{provider:n,innerConfig:r,signature:i}}buildInner(t,n){let{provider:r,innerConfig:o,signature:i}=this.resolveInner(t),s=new ya(()=>this.lastSessionId);this.currentPermissionMode!==void 0&&(o.permissionMode=this.currentPermissionMode),this.currentCwd!==void 0&&(o.cwd=this.currentCwd),n&&(o.resumeHistory=[...this.shadowHistory]);let a=r.query({prompt:s.createIterable(),config:o});return{family:r.name,signature:i,query:a,iterator:a[Symbol.asyncIterator](),input:s}}async closeActive(){let t=this.active;if(t){this.active=void 0;try{await t.iterator.return?.(void 0)}catch{}try{await t.query.close()}catch{}}}observeEvent(t){t.type==="assistant.message"&&(this.pendingAssistantText+=(this.pendingAssistantText?`
|
|
1188
|
-
`:"")+t.text)}commitShadowTurn(){this.pendingUserText!==void 0&&(this.shadowHistory.push({user:this.pendingUserText,assistant:this.pendingAssistantText}),this.pendingUserText=void 0,this.pendingAssistantText="")}async*[Symbol.asyncIterator](){try{for(this.active=this.buildInner(this.currentModel,!1),this.activeModel=this.currentModel,yield*this.driveUntilInit(!1);!this.closed;){let t=await this.outerIterator.next();if(t.done)break;let n=t.value;this.lastSessionId=n.sessionId;let r=this.currentModel!==this.activeModel,o=!this.active||r&&this.resolveInner(this.currentModel).signature!==this.active.signature;if(this.activeModel=this.currentModel,o&&(await this.closeActive(),this.active=this.buildInner(this.currentModel,!0),W(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=eX(n.content),this.pendingAssistantText="",this.active.input.pushUserMessage(n.content);;){let i=await this.active.iterator.next();if(i.done){this.closed=!0;break}let s=i.value;if(this.observeEvent(s),yield s,s.type==="turn.completed"){this.commitShadowTurn();break}if(s.type==="error"){this.commitShadowTurn();break}}}}finally{await this.closeActive()}}async*driveUntilInit(t){for(;;){let n=await this.active.iterator.next();if(n.done)return yield{type:"error",error:new Error("provider ended before initialization")},this.closed=!0,!0;let r=n.value;if(r.type==="session.init")return t||(yield r),!1;if(r.type==="error")return yield r,this.closed=!0,!0;yield r}}async interrupt(){await this.active?.query.interrupt()}async setModel(t){typeof t=="string"&&t.length>0&&(this.currentModel=t,this.active&&this.resolveInner(t).signature===this.active.signature&&await this.active.query.setModel(t))}async setPermissionMode(t){this.currentPermissionMode=t,await this.active?.query.setPermissionMode(t)}setCwd(t){this.currentCwd=t,this.active?.query.setCwd?.(t)}async reauth(){return await this.active?.query.reauth?.()??null}async supportedCommands(){return await this.active?.query.supportedCommands()??[]}async supportedModels(){return await this.active?.query.supportedModels()??[]}async supportedAgents(){return await this.active?.query.supportedAgents()??[]}async getContextUsage(){return await this.active?.query.getContextUsage()??{}}async mcpServerStatus(){return await this.active?.query.mcpServerStatus()??[]}async accountInfo(){return await this.active?.query.accountInfo()??{}}async rewindFiles(t,n){let r=this.active;return r?r.query.rewindFiles(t,n):{canRewind:!1,error:"no active provider"}}async compact(){let t=this.active;return t?.query.compact?t.query.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}}async reloadPlugins(...t){let n=this.active?.query;if(n&&typeof n.reloadPlugins=="function")return n.reloadPlugins(...t)}async close(){this.closed=!0,await this.closeActive()}}});async function Tf(e,t,n){if(!e)return;if(n.kind==="blocked"){await sn(e,{hookEvent:t,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await sn(e,{hookEvent:t,decision:r.decision,...r.reason!==void 0?{reason:r.reason}:{},...r.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(r.injectContext,"utf8")}:{}})}async function tO(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Tf(n.traceWriter,"SessionStart",{kind:"decision",decision:r})}catch(r){throw r instanceof me&&await Tf(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function nO(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Tf(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof me&&await Tf(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof me||r instanceof gt){W(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}W(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var rO=x(()=>{"use strict";fe();et();Re()});function Ci(e){return e==="abort"?Cv:null}var Cv,xf=x(()=>{"use strict";Cv="Session ended via abort before reaching a terminal state. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state, or re-run the task if the interruption was intentional."});function tX(e){return e==="max_tokens"||e==="length"}function oO(e){return e.maxTurnsHit?"max_turns_exceeded":e.hookBlocked?"hook_blocked":e.dispatchReason==="error"?"abort":e.abort!==null?e.abort:e.sawProviderError?"abort":e.lastStopReason==="tool_use_loop_capped"?"iteration_cap":tX(e.lastStopReason)?"truncated":"model_end_turn"}var iO=x(()=>{"use strict"});function nX(e){let t=null,n=e.signal;if(n.aborted&&n.reason!=="closed"){let r=n.reason;r instanceof Qr?t="budget_exceeded":r instanceof xt?t="timeout":typeof r=="string"&&r.startsWith("Budget ")?t="budget_exceeded":typeof r=="string"&&r.includes("timed out")?t="timeout":t="abort"}return oO({dispatchReason:e.dispatchReason,maxTurnsHit:e.maxTurnsHit,hookBlocked:e.hookBlocked,abort:t,lastStopReason:e.lastStopReason,sawProviderError:e.sawProviderError})}function rX(e){if(e.dispatchReason==="error")return"failed";let t=e.signal;return t.aborted&&t.reason!=="closed"?"cancelled":e.sawProviderError?"failed":"succeeded"}async function sO(e,t){if(!e)return;let n=nX(t),r={},o=t.runningTokens;o.input>0&&(r.input=o.input),o.output>0&&(r.output=o.output),o.cacheRead>0&&(r.cacheRead=o.cacheRead),o.cacheCreation>0&&(r.cacheCreation=o.cacheCreation);let i=Ci(n);await Yx(e,{reason:n,finalTurnCount:t.finalTurnCount,finalCostUsd:t.finalCostUsd,finalTokens:r,...t.lastStopReason!==void 0?{lastStopReason:t.lastStopReason}:{},...i!==null?{guidance:i}:{}})}async function aO(e,t){if(!e)return;let n=rX(t),r=t.subagentCompletedCount>0?t.subagentCompletedCount:void 0,o=t.subagentRunningTokens,s=o.input>0||o.output>0||o.cacheRead>0||o.cacheCreation>0?{...o.input>0?{input:o.input}:{},...o.output>0?{output:o.output}:{},...o.cacheRead>0?{cacheRead:o.cacheRead}:{},...o.cacheCreation>0?{cacheCreation:o.cacheCreation}:{}}:void 0,a=t.subagentRunningCostUsd>0?t.subagentRunningCostUsd:void 0;await e.seal({status:n,finalCostUsd:t.finalCostUsd,finalTurnCount:t.finalTurnCount,closedAt:new Date().toISOString(),...r!==void 0?{subagentCount:r}:{},...s!==void 0?{subagentTokens:s}:{},...a!==void 0?{subagentCostUsd:a}:{}})}var lO=x(()=>{"use strict";et();Re();xf();iO()});import*as ba from"node:fs";import*as wa from"node:fs/promises";import*as dO from"node:readline";function Rf(e,t){return e.length>t?`${e.slice(0,t)}\u2026 [truncated]`:e}function oX(e){switch(e.type){case"message":return e.message.role!=="assistant"||!e.message.content?null:{kind:"assistant",text:Rf(e.message.content,uO)};case"chunk":{let t=e.chunk;return t.type==="tool_use_detail"?{kind:"tool",toolName:t.toolName,input:Rf(t.toolInput,cO)}:t.type==="tool_result"&&t.isError===!0?{kind:"tool_error",content:Rf(t.content,cO)}:null}case"done":{let t=e.metadata?.totalCostUsd,n=e.metadata?.durationMs;return{kind:"done",...typeof t=="number"?{costUsd:t}:{},...typeof n=="number"?{durationMs:n}:{}}}case"error":return{kind:"error",message:e.error.message};case"paused":return{kind:"paused",...e.resetsAt?{resetsAt:e.resetsAt.toISOString()}:{}};case"resumed":return{kind:"resumed"};default:return null}}function pO(e){let t=e.trim();if(!t)return null;try{let n=JSON.parse(t);return n.v!==1||typeof n.ts!="number"||typeof n.kind!="string"?null:n}catch{return null}}async function*mO(e){if(!Bl(e))return;let t;try{t=await wa.open(vu(e),"r")}catch(n){if(n.code==="ENOENT")return;throw n}try{let n=dO.createInterface({input:t.createReadStream({encoding:"utf8"}),crlfDelay:1/0});for await(let r of n){let o=pO(r);o&&(yield o)}}finally{await t.close()}}async function*Av(e,t){if(!Bl(e))return;let n=vu(e),r=Ul(e),{fromStart:o=!1,signal:i}=t??{},s=0,a="",l=!1;async function*c(){let m=null;try{m=await wa.open(n,"r");let g=await m.stat();if(g.size<=s)return;let h=g.size-s,y=Buffer.allocUnsafe(h),{bytesRead:b}=await m.read(y,0,h,s);if(b===0)return;s+=b,a+=y.toString("utf8",0,b);let w=a.split(`
|
|
1135
|
+
`:"")+t.text)}commitShadowTurn(){this.pendingUserText!==void 0&&(this.shadowHistory.push({user:this.pendingUserText,assistant:this.pendingAssistantText}),this.pendingUserText=void 0,this.pendingAssistantText="")}async*[Symbol.asyncIterator](){try{for(this.active=this.buildInner(this.currentModel,!1),this.activeModel=this.currentModel,yield*this.driveUntilInit(!1);!this.closed;){let t=await this.outerIterator.next();if(t.done)break;let n=t.value;this.lastSessionId=n.sessionId;let r=this.currentModel!==this.activeModel,o=!this.active||r&&this.resolveInner(this.currentModel).signature!==this.active.signature;if(this.activeModel=this.currentModel,o&&(await this.closeActive(),this.active=this.buildInner(this.currentModel,!0),W(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=eX(n.content),this.pendingAssistantText="",this.active.input.pushUserMessage(n.content);;){let i=await this.active.iterator.next();if(i.done){this.closed=!0;break}let s=i.value;if(this.observeEvent(s),yield s,s.type==="turn.completed"){this.commitShadowTurn();break}if(s.type==="error"){this.commitShadowTurn();break}}}}finally{await this.closeActive()}}async*driveUntilInit(t){for(;;){let n=await this.active.iterator.next();if(n.done)return yield{type:"error",error:new Error("provider ended before initialization")},this.closed=!0,!0;let r=n.value;if(r.type==="session.init")return t||(yield r),!1;if(r.type==="error")return yield r,this.closed=!0,!0;yield r}}async interrupt(){await this.active?.query.interrupt()}async setModel(t){typeof t=="string"&&t.length>0&&(this.currentModel=t,this.active&&this.resolveInner(t).signature===this.active.signature&&await this.active.query.setModel(t))}async setPermissionMode(t){this.currentPermissionMode=t,await this.active?.query.setPermissionMode(t)}setCwd(t){this.currentCwd=t,this.active?.query.setCwd?.(t)}async reauth(){return await this.active?.query.reauth?.()??null}async supportedCommands(){return await this.active?.query.supportedCommands()??[]}async supportedModels(){return await this.active?.query.supportedModels()??[]}async supportedAgents(){return await this.active?.query.supportedAgents()??[]}async getContextUsage(){return await this.active?.query.getContextUsage()??{}}async mcpServerStatus(){return await this.active?.query.mcpServerStatus()??[]}async accountInfo(){return await this.active?.query.accountInfo()??{}}async rewindFiles(t,n){let r=this.active;return r?r.query.rewindFiles(t,n):{canRewind:!1,error:"no active provider"}}async compact(){let t=this.active;return t?.query.compact?t.query.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}}async reloadPlugins(...t){let n=this.active?.query;if(n&&typeof n.reloadPlugins=="function")return n.reloadPlugins(...t)}async close(){this.closed=!0,await this.closeActive()}}});async function Tf(e,t,n){if(!e)return;if(n.kind==="blocked"){await sn(e,{hookEvent:t,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await sn(e,{hookEvent:t,decision:r.decision,...r.reason!==void 0?{reason:r.reason}:{},...r.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(r.injectContext,"utf8")}:{}})}async function tO(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);return await Tf(n.traceWriter,"SessionStart",{kind:"decision",decision:r}),r.injectContext}catch(r){throw r instanceof me&&await Tf(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function nO(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Tf(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof me&&await Tf(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof me||r instanceof gt){W(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}W(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var rO=x(()=>{"use strict";fe();et();Re()});function Ci(e){return e==="abort"?Cv:null}var Cv,xf=x(()=>{"use strict";Cv="Session ended via abort before reaching a terminal state. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state, or re-run the task if the interruption was intentional."});function tX(e){return e==="max_tokens"||e==="length"}function oO(e){return e.maxTurnsHit?"max_turns_exceeded":e.hookBlocked?"hook_blocked":e.dispatchReason==="error"?"abort":e.abort!==null?e.abort:e.sawProviderError?"abort":e.lastStopReason==="tool_use_loop_capped"?"iteration_cap":tX(e.lastStopReason)?"truncated":"model_end_turn"}var iO=x(()=>{"use strict"});function nX(e){let t=null,n=e.signal;if(n.aborted&&n.reason!=="closed"){let r=n.reason;r instanceof Qr?t="budget_exceeded":r instanceof xt?t="timeout":typeof r=="string"&&r.startsWith("Budget ")?t="budget_exceeded":typeof r=="string"&&r.includes("timed out")?t="timeout":t="abort"}return oO({dispatchReason:e.dispatchReason,maxTurnsHit:e.maxTurnsHit,hookBlocked:e.hookBlocked,abort:t,lastStopReason:e.lastStopReason,sawProviderError:e.sawProviderError})}function rX(e){if(e.dispatchReason==="error")return"failed";let t=e.signal;return t.aborted&&t.reason!=="closed"?"cancelled":e.sawProviderError?"failed":"succeeded"}async function sO(e,t){if(!e)return;let n=nX(t),r={},o=t.runningTokens;o.input>0&&(r.input=o.input),o.output>0&&(r.output=o.output),o.cacheRead>0&&(r.cacheRead=o.cacheRead),o.cacheCreation>0&&(r.cacheCreation=o.cacheCreation);let i=Ci(n);await Yx(e,{reason:n,finalTurnCount:t.finalTurnCount,finalCostUsd:t.finalCostUsd,finalTokens:r,...t.lastStopReason!==void 0?{lastStopReason:t.lastStopReason}:{},...i!==null?{guidance:i}:{}})}async function aO(e,t){if(!e)return;let n=rX(t),r=t.subagentCompletedCount>0?t.subagentCompletedCount:void 0,o=t.subagentRunningTokens,s=o.input>0||o.output>0||o.cacheRead>0||o.cacheCreation>0?{...o.input>0?{input:o.input}:{},...o.output>0?{output:o.output}:{},...o.cacheRead>0?{cacheRead:o.cacheRead}:{},...o.cacheCreation>0?{cacheCreation:o.cacheCreation}:{}}:void 0,a=t.subagentRunningCostUsd>0?t.subagentRunningCostUsd:void 0;await e.seal({status:n,finalCostUsd:t.finalCostUsd,finalTurnCount:t.finalTurnCount,closedAt:new Date().toISOString(),...r!==void 0?{subagentCount:r}:{},...s!==void 0?{subagentTokens:s}:{},...a!==void 0?{subagentCostUsd:a}:{}})}var lO=x(()=>{"use strict";et();Re();xf();iO()});import*as ba from"node:fs";import*as wa from"node:fs/promises";import*as dO from"node:readline";function Rf(e,t){return e.length>t?`${e.slice(0,t)}\u2026 [truncated]`:e}function oX(e){switch(e.type){case"message":return e.message.role!=="assistant"||!e.message.content?null:{kind:"assistant",text:Rf(e.message.content,uO)};case"chunk":{let t=e.chunk;return t.type==="tool_use_detail"?{kind:"tool",toolName:t.toolName,input:Rf(t.toolInput,cO)}:t.type==="tool_result"&&t.isError===!0?{kind:"tool_error",content:Rf(t.content,cO)}:null}case"done":{let t=e.metadata?.totalCostUsd,n=e.metadata?.durationMs;return{kind:"done",...typeof t=="number"?{costUsd:t}:{},...typeof n=="number"?{durationMs:n}:{}}}case"error":return{kind:"error",message:e.error.message};case"paused":return{kind:"paused",...e.resetsAt?{resetsAt:e.resetsAt.toISOString()}:{}};case"resumed":return{kind:"resumed"};default:return null}}function pO(e){let t=e.trim();if(!t)return null;try{let n=JSON.parse(t);return n.v!==1||typeof n.ts!="number"||typeof n.kind!="string"?null:n}catch{return null}}async function*mO(e){if(!Bl(e))return;let t;try{t=await wa.open(vu(e),"r")}catch(n){if(n.code==="ENOENT")return;throw n}try{let n=dO.createInterface({input:t.createReadStream({encoding:"utf8"}),crlfDelay:1/0});for await(let r of n){let o=pO(r);o&&(yield o)}}finally{await t.close()}}async function*Av(e,t){if(!Bl(e))return;let n=vu(e),r=Ul(e),{fromStart:o=!1,signal:i}=t??{},s=0,a="",l=!1;async function*c(){let m=null;try{m=await wa.open(n,"r");let g=await m.stat();if(g.size<=s)return;let h=g.size-s,y=Buffer.allocUnsafe(h),{bytesRead:b}=await m.read(y,0,h,s);if(b===0)return;s+=b,a+=y.toString("utf8",0,b);let w=a.split(`
|
|
1189
1136
|
`);a=w.pop()??"";for(let S of w){let v=pO(S);if(v&&(v.kind==="closed"&&(l=!0),yield v,l))return}}catch(g){g.code!=="ENOENT"&&process.stderr.write(`[afk] session-ledger: tail read error for ${e}: ${String(g)}
|
|
1190
1137
|
`)}finally{m&&await m.close().catch(()=>{})}}if(o){if(yield*c(),l)return}else try{s=(await wa.stat(n)).size}catch{}let d=null,u=null,p=()=>new Promise(m=>{let g=setTimeout(()=>{u=null,m()},iX);u=()=>{clearTimeout(g),u=null,m()},i?.addEventListener("abort",()=>{clearTimeout(g),u=null,m()},{once:!0})});try{d=ba.watch(r,{persistent:!1},()=>{u?.()})}catch{}try{for(;!i?.aborted&&!l&&(await p(),!i?.aborted);)yield*c()}finally{d?.close()}}var uO,cO,Cf,iX,Af=x(()=>{"use strict";G();uO=8e3,cO=400;Cf=class{sessionId;ledgerPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;constructor(t){if(this.sessionId=t,!Bl(t)){this.errored=!0,this.ledgerPath="";return}this.ledgerPath=vu(t);try{ba.mkdirSync(Ul(t),{recursive:!0})}catch(n){process.stderr.write(`[afk] session-ledger: mkdir failed for ${t}: ${String(n)}
|
|
1191
1138
|
`),this.errored=!0}}get active(){return!this.errored&&!this.closed}record(t){if(this.errored||this.closed)return;let n={v:1,ts:Date.now(),...t},r=JSON.stringify(n)+`
|
|
@@ -1197,7 +1144,7 @@ ${t.body}`)}var T3,lv=x(()=>{"use strict";T3=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
|
|
|
1197
1144
|
`);if(r.length<=1&&e.length<=80)return{content:e,truncated:!1,sizeBytes:t,sizeLabel:n};if(r.length<=1)return e.length<=80?{content:e,truncated:!1,sizeBytes:t,sizeLabel:n}:{content:e.substring(0,80)+"\u2026",truncated:!0,sizeBytes:t,sizeLabel:n};if(e.length<=80)return{content:e,truncated:!1,sizeBytes:t,sizeLabel:n};let o=r[0]??"",i=o;return o.length>80&&(i=o.substring(0,80)+"\u2026"),{content:i+`\u2026+${r.length} lines`,truncated:!0,lineCount:r.length,sizeBytes:t,sizeLabel:n}}function pX(e,t){let n={...e.raw??{}};return e.inputTokens!==void 0&&(n.input_tokens=e.inputTokens),e.outputTokens!==void 0&&(n.output_tokens=e.outputTokens),e.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=e.cachedInputTokens),e.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=e.cacheCreationTokens),e.totalTokens!==void 0&&(n.total_tokens=e.totalTokens),e.contextWindowTokens!==void 0&&(n.context_window_tokens=e.contextWindowTokens),{sessionId:t,stopReason:e.stopReason??void 0,resultSubtype:e.resultSubtype,durationMs:e.durationMs,durationApiMs:e.durationApiMs,totalCostUsd:e.totalCostUsd,isError:e.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:e.modelUsage,permissionDenials:e.permissionDenials,errors:e.errors}}function mX(e){let t=e.isError===!0?null:RO(e.toolName,e.content),n=t!==null?{display:t}:{},r=typeof e.batchIndex=="number"&&typeof e.batchSize=="number"?{batchIndex:e.batchIndex,batchSize:e.batchSize}:{},o=cX(e.content);if(o)return{type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:`Output persisted (${o.sizeLabel}) \u2192 ${o.absolutePath}`,isError:e.isError===!0,persistedPath:o.absolutePath,sizeBytes:o.sizeBytes,sizeLabel:o.sizeLabel,...n,...r}};let{content:i,lineCount:s,sizeBytes:a,sizeLabel:l}=uX(e.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:i,isError:e.isError===!0,sizeBytes:a,sizeLabel:l,...e.truncated===!0&&{truncated:!0},...s!==void 0&&{lineCount:s},...n,...r}}}function Iv(e,t){switch(e.type){case"session.init":{let n=e.info;return t.setSessionMetadata(r=>({...r,sessionId:n.sessionId,model:n.model??r.model,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},tools:n.tools?[...n.tools]:r.tools,slashCommands:n.slashCommands?[...n.slashCommands]:r.slashCommands,skills:n.skills?[...n.skills]:r.skills,plugins:n.plugins?n.plugins.map(o=>({...o})):r.plugins,mcpServers:n.mcpServers?n.mcpServers.map(o=>({...o})):r.mcpServers,...n.apiKeySource!==void 0?{apiKeySource:n.apiKeySource}:{},...n.version!==void 0?{claudeCodeVersion:n.version}:{},...n.outputStyle!==void 0?{outputStyle:n.outputStyle}:{}})),t.updateSessionIdentity(n.sessionId),t.resolveInitialization(),null}case"session.status":return t.setSessionMetadata(n=>({...n,sessionId:e.sessionId,...e.permissionMode!==void 0?{permissionMode:e.permissionMode}:{permissionMode:n.permissionMode},...e.status!==void 0?{status:e.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:e.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:e.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(e.sessionId&&t.updateSessionIdentity(e.sessionId),e.text){let n={role:"assistant",content:e.text,timestamp:new Date};return t.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:e.toolUseId,toolName:e.toolName,toolInput:e.toolInput,toolInputRaw:e.toolInputRaw}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:e.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:e.toolUseIds}}};case"tool.output":return e.isError!==!0&&e.toolName&&(t._successfulToolNames??=[]).push(e.toolName),mX(e);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:e.toolUseId,diff:e.diff}};case"progress":return{type:"progress",progress:{taskId:e.progress.taskId,description:e.progress.description,...e.progress.summary!==void 0?{summary:e.progress.summary}:{},...e.progress.lastToolName!==void 0?{lastToolName:e.progress.lastToolName}:{},totalTokens:e.progress.totalTokens,toolUses:e.progress.toolUses,durationMs:e.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:e.suggestion};case"turn.completed":{let n=pX(e.usage,e.sessionId??t.getSessionMetadata().sessionId);t._successfulToolNames!==void 0&&t._successfulToolNames.length>0&&(n.successfulToolNames=[...t._successfulToolNames]),t.setLastResponseMetadata(n);for(let r=t.conversationHistory.length-1;r>=0;r--){let o=t.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(t.maxBudgetUsd!==void 0&&t.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(t._runningCostUsd=(t._runningCostUsd??0)+n.totalCostUsd,t._runningCostUsd>=t.maxBudgetUsd)){zx(t.traceWriter,{kind:"monetary",runningCostUsd:t._runningCostUsd,maxBudgetUsd:t.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new Qr(t._runningCostUsd,t.maxBudgetUsd);return t.abortBudget(r.message),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:e.error};case"paused":return{type:"paused",reason:e.reason,...e.resetsAt!==void 0?{resetsAt:e.resetsAt}:{},...e.accountId!==void 0?{accountId:e.accountId}:{},...e.autoResume!==void 0?{autoResume:e.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:e.hotSwapped,...e.accountId!==void 0?{accountId:e.accountId}:{}};case"stream.retry":return{type:"stream_retry"};case"rate_limit":return{type:"rate_limit",...e.retryAfterMs!==void 0?{retryAfterMs:e.retryAfterMs}:{}};default:return null}}var AO=x(()=>{"use strict";et();Re();CO()});import{stat as fX,readFile as gX,writeFile as hX,rename as yX,unlink as bX}from"node:fs/promises";async function PO(e,{maxBytes:t,keepTailLines:n}){let r={trimmed:!1,removedLines:0},o;try{if((await fX(e)).size<=t)return r;let a=(await gX(e,"utf8")).split(`
|
|
1198
1145
|
`);if(a.length>0&&a[a.length-1]===""&&a.pop(),a.length<=n)return r;let l=a.slice(a.length-n),c=a.length-l.length;return o=`${e}.tmp-${process.pid}-${Math.random().toString(36).slice(2,8)}`,await hX(o,l.join(`
|
|
1199
1146
|
`)+`
|
|
1200
|
-
`,{mode:384}),await yX(o,e),o=void 0,{trimmed:!0,removedLines:c}}catch{if(o!==void 0)try{await bX(o)}catch{}return r}}var _O,IO,MO=x(()=>{"use strict";_O=5*1024*1024,IO=5e3});import{z as wX}from"zod";var Pt,Pv=x(()=>{"use strict";fe();et();Re();qe();eO();At();XS();rO();et();lO();$S();xv();fO();gO();xn();go();uc();Dt();Rv();bO();wO();AO();G();MO();Pt=class{config;planExit=new If;currentState="idle";providerQuery;providerIterator;conversationHistory=[];turnCount=0;pendingFrameworkContext=[];lastResponseMetadata=null;initPromise=null;inputStream;abortController;_hookRegistry;sessionEndDispatched=!1;stateManager;sessionRunningCostUsd=0;sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};lastStopReason;maxTurnsHit=!1;hookBlocked=!1;sawProviderError=!1;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=new _f;constructor(t){this.config=t.parentSessionId===void 0&&t.planExitControls===void 0?{...t,planExitControls:{setPermissionMode:r=>this.setPermissionMode(r),requestImplementSeed:(r,o)=>this.planExit.requestImplementSeed(r,o),getPrePlanMode:()=>this.planExit.getPrePlanMode()}}:t,this.abortController=new AbortController,this._hookRegistry=t.hookRegistry,hO(t.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(t.model);ge(t.traceWriter,{phase:"session_init_start",model:n,resolvedModel:Rt(t.model)??n,origin:fo(t.surface),actor:cm(t.parentSessionId)}),this.initSdkLifecycle(),this.config.parentSessionId===void 0&&PO(hu(),{maxBytes:_O,keepTailLines:IO})}initSdkLifecycle(){this.config.models&&Du(this.config.models),kf(this.config);let t=Rt(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=yO(this.config,t);this.stateManager=new Pf(n,r),this.inputStream=new ya(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)W(`\u{1F7E2} AgentSession: Creating query session via injected provider=${this.config.provider.name}`),this.providerQuery=this.config.provider.query({prompt:o,config:this.config});else{W("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let s=this.config.providerFactory?this.config.providerFactory:a=>vf(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new Ef({prompt:o,config:this.config},{resolveProvider:s,providerNameForModel:a=>ne(a),resolveApiKey:a=>Oe(a)})}this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionRunningCostUsd=0,this.sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.lastStopReason=void 0,this.maxTurnsHit=!1,this.hookBlocked=!1,this.sawProviderError=!1,this.sessionEndDispatched=!1,this.currentState="idle",this.subagentCompletedCount=0,this.subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.subagentRunningCostUsd=0,this.pendingFrameworkContext=[];let i=this.providerQuery;this.providerIterator=i[Symbol.asyncIterator](),this.initPromise=this.pullInitialization()}async pullInitialization(){try{
|
|
1147
|
+
`,{mode:384}),await yX(o,e),o=void 0,{trimmed:!0,removedLines:c}}catch{if(o!==void 0)try{await bX(o)}catch{}return r}}var _O,IO,MO=x(()=>{"use strict";_O=5*1024*1024,IO=5e3});import{z as wX}from"zod";var Pt,Pv=x(()=>{"use strict";fe();et();Re();qe();eO();At();XS();rO();et();lO();$S();xv();fO();gO();xn();go();uc();Dt();Rv();bO();wO();AO();G();MO();Pt=class{config;planExit=new If;currentState="idle";providerQuery;providerIterator;conversationHistory=[];turnCount=0;pendingFrameworkContext=[];lastResponseMetadata=null;initPromise=null;inputStream;abortController;_hookRegistry;sessionEndDispatched=!1;stateManager;sessionRunningCostUsd=0;sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};lastStopReason;maxTurnsHit=!1;hookBlocked=!1;sawProviderError=!1;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=new _f;constructor(t){this.config=t.parentSessionId===void 0&&t.planExitControls===void 0?{...t,planExitControls:{setPermissionMode:r=>this.setPermissionMode(r),requestImplementSeed:(r,o)=>this.planExit.requestImplementSeed(r,o),getPrePlanMode:()=>this.planExit.getPrePlanMode()}}:t,this.abortController=new AbortController,this._hookRegistry=t.hookRegistry,hO(t.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(t.model);ge(t.traceWriter,{phase:"session_init_start",model:n,resolvedModel:Rt(t.model)??n,origin:fo(t.surface),actor:cm(t.parentSessionId)}),this.initSdkLifecycle(),this.config.parentSessionId===void 0&&PO(hu(),{maxBytes:_O,keepTailLines:IO})}initSdkLifecycle(){this.config.models&&Du(this.config.models),kf(this.config);let t=Rt(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=yO(this.config,t);this.stateManager=new Pf(n,r),this.inputStream=new ya(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)W(`\u{1F7E2} AgentSession: Creating query session via injected provider=${this.config.provider.name}`),this.providerQuery=this.config.provider.query({prompt:o,config:this.config});else{W("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let s=this.config.providerFactory?this.config.providerFactory:a=>vf(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new Ef({prompt:o,config:this.config},{resolveProvider:s,providerNameForModel:a=>ne(a),resolveApiKey:a=>Oe(a)})}this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionRunningCostUsd=0,this.sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.lastStopReason=void 0,this.maxTurnsHit=!1,this.hookBlocked=!1,this.sawProviderError=!1,this.sessionEndDispatched=!1,this.currentState="idle",this.subagentCompletedCount=0,this.subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.subagentRunningCostUsd=0,this.pendingFrameworkContext=[];let i=this.providerQuery;this.providerIterator=i[Symbol.asyncIterator](),this.initPromise=this.pullInitialization()}async pullInitialization(){try{let t=await tO(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId,parentSessionId:this.config.parentSessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});for(t&&this.config.parentSessionId===void 0&&this.queueFrameworkContext(t);;){let n=await this.providerIterator.next();if(n.done){this.stateManager.resolveInitializationIfNeeded();return}let r=n.value,o=Iv(r,this.buildTransformDeps());if(r.type==="session.init"){await ge(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(o&&o.type==="error"){this.sawProviderError=!0;return}}}catch(t){let n=t instanceof Error?t:new Error(String(t));n instanceof me&&(this.hookBlocked=!0),this.stateManager.isInitializationSettled()||this.stateManager.rejectInitializationOnce(n),await this.dispatchSessionEndOnce("error").catch(()=>{})}}buildTransformDeps(){return{_successfulToolNames:[],conversationHistory:this.conversationHistory,getSessionMetadata:()=>this.stateManager.getSessionMetadata(),setSessionMetadata:t=>this.stateManager.setSessionMetadata(t),updateSessionIdentity:t=>this.stateManager.updateSessionIdentity(t),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:t=>{this.lastResponseMetadata=t,typeof t.totalCostUsd=="number"&&Number.isFinite(t.totalCostUsd)&&(this.sessionRunningCostUsd+=t.totalCostUsd);let n=t.usage;if(n&&typeof n=="object"){let r=n,o=(i,s)=>{let a=r[i];typeof a=="number"&&Number.isFinite(a)&&(this.sessionRunningTokens[s]+=a)};o("input_tokens","input"),o("output_tokens","output"),o("cache_read_input_tokens","cacheRead"),o("cache_creation_input_tokens","cacheCreation")}typeof t.stopReason=="string"&&(this.lastStopReason=t.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:t=>{this.abortController.signal.aborted||this.abortController.abort(t)},...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}}}get state(){return this.currentState}get sessionId(){return this.stateManager.getSessionId()}get cwd(){return this.config.cwd}get abortSignal(){return this.abortController.signal}get hookRegistry(){return this._hookRegistry}abort(t){if(t==="closed"||t.startsWith("Budget ")||t.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${t}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(t)}async sendMessage(t,n={}){this.assertCanSend();let r=this.config.timeoutMs??YP,o=async()=>{let i=null,s="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(t)){if(a.type==="chunk"&&a.chunk.type==="content"&&(s+=a.chunk.content),a.type==="message"&&a.message.role==="assistant"&&(i=a.message),a.type==="error")throw a.error;if(a.type==="done"){if(i)return{...i,metadata:a.metadata};if(s)return{role:"assistant",content:s,metadata:a.metadata,timestamp:new Date}}}if(i)return i;if(s)return{role:"assistant",content:s,timestamp:new Date};throw new Error("No assistant response received")};try{return await Zm(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async sendMessageStructured(t,n,r={}){let{maxRetries:o=2,injectSchemaPrompt:i=!0,...s}=r,a=i?"\n\nRespond with ONLY a JSON object (optionally in a ```json fence) that conforms to this JSON Schema:\n```json\n"+JSON.stringify(wX.toJSONSchema(n,{target:"openapi-3.0"}))+"\n```":"",l="";for(let c=0;c<=o;c++){let d=c===0?t+a:`Your previous response did not match the required JSON schema.
|
|
1201
1148
|
Validation error: ${l}
|
|
1202
1149
|
Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,u=await this.sendMessage(d,s),p=Lm(u.content),m=n.safeParse(p);if(m.success)return m.data;l=m.error.message}throw new Error(`structured output did not match schema after ${o+1} attempt(s): ${l}`)}async*sendMessageStream(t){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(t)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(t){this.initPromise&&await this.initPromise,this.planExit.clearModeBeforeDefault();let n=this.withPendingFrameworkContext(t),r=typeof n=="string"?n:this.summarizeContentBlocks(n),o={role:"user",content:r,timestamp:new Date};this.conversationHistory.push(o),this.inputStream.pushUserMessage(n),this.ensureLedger(),this.ledger.recordUser(r);let i=this.buildTransformDeps();try{for(;;){let s=await this.providerIterator.next();if(s.done)break;let a=s.value,l=Iv(a,i);if(l&&(l.type==="done"?(this.turnCount++,this.sawProviderError=!1):l.type==="error"&&(this.sawProviderError=!0),this.ledger.recordEvent(l),yield l,l.type==="done"||l.type==="error"))break}}finally{this.currentState==="streaming"&&(this.currentState="idle")}}ensureLedger(){this.ledger.ensure({depth:this.config.depth,parentSessionId:this.config.parentSessionId,sessionId:this.sessionId,fallbackModel:String(this.config.model),tracePath:this.config.traceWriter?.getTracePath(),getMetadata:()=>this.getSessionMetadata()})}recordLedgerElicitation(t,n){this.ledger.recordElicitation(t,n)}summarizeContentBlocks(t){let n=[],r=0;for(let i of t)i.type==="text"?n.push(i.text):i.type==="image"&&r++;let o=n.join(" ");return r>0&&(o=o?`${o} [+ ${r} image(s)]`:`[+ ${r} image(s)]`),o||"[content block(s)]"}async interrupt(){this.currentState!=="streaming"&&this.currentState!=="processing"||(this.currentState="idle",await this.providerQuery.interrupt())}async reset(){if(this.currentState==="closed")throw new Error("Cannot reset: session is closed");if(this.abortController.signal.aborted)throw new gt("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset"),await this.ledger.seal("reset");try{await this.providerQuery.close()}catch{}await this.providerIterator.return?.(),this.initPromise&&await Promise.race([this.initPromise,new Promise(t=>setTimeout(t,VS))]).catch(()=>{}),this.stateManager.resolveInitializationIfNeeded(),this.config={...this.config},delete this.config.resume,delete this.config.sessionId,delete this.config.resumeHistory,delete this.config.resumeSessionAt,delete this.config.continue,delete this.config.forkSession;try{this.initSdkLifecycle()}catch(t){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async onAbort(){this.ledger.seal("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(t){let n=Rt(t);typeof t=="string"&&t.length>0&&await this.providerQuery.setModel(t),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(t){let n=this.stateManager.getSessionMetadata().permissionMode;this.planExit.recordModeTransition(t,n),await this.providerQuery.setPermissionMode(t),this.stateManager.setSessionMetadata(r=>({...r,permissionMode:t}))}getPrePlanMode(){return this.planExit.getPrePlanMode()}async takePendingPlanExitSeed(){let t=this.planExit.takeSeed();if(t!==void 0){try{await this.setPermissionMode(t.mode)}catch(n){W(`\u26A0\uFE0F AgentSession: deferred plan-exit mode flip to '${t.mode}' rejected; dropping implement-seed (staying in plan mode): ${n instanceof Error?n.message:String(n)}`);return}return{message:t.message,mode:t.mode}}}setCwd(t){this.config={...this.config,cwd:t},this.providerQuery.setCwd?.(t),this.config.sessionId!==void 0&&OC(this.config.sessionId,t)}async reauth(){return await this.providerQuery.reauth?.()??null}waitForInitialization(){return this.stateManager.waitForInitialization()}getSessionIdentity(){return this.stateManager.getSessionIdentity()}getSessionMetadata(){return this.stateManager.getSessionMetadata()}getQuery(){return this.providerQuery}supportedCommands(){return this.providerQuery.supportedCommands()}supportedModels(){return this.providerQuery.supportedModels()}supportedAgents(){return this.providerQuery.supportedAgents()}getContextUsage(){return this.providerQuery.getContextUsage()}mcpServerStatus(){return this.providerQuery.mcpServerStatus()}accountInfo(){return this.providerQuery.accountInfo()}rewindFiles(t,n){return this.providerQuery.rewindFiles(t,n)}async compact(){if(this.currentState==="closed")throw new Error("Cannot compact: session is closed");if(this.currentState!=="idle")return{compacted:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let t=this.providerQuery.compact?.bind(this.providerQuery);if(!t)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await t()}finally{this.currentState="idle"}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){throw new Error("getOutputStream() is not supported \u2014 use sendMessageStream() instead")}queueFrameworkContext(t){let n=t.trim();n.length!==0&&(this.pendingFrameworkContext.push(n),W(`AgentSession: queued framework context (${n.length} chars) for the next user message`))}withPendingFrameworkContext(t){if(this.pendingFrameworkContext.length===0)return t;let n=this.pendingFrameworkContext.join(`
|
|
1203
1150
|
|
|
@@ -1791,7 +1738,7 @@ ${S}
|
|
|
1791
1738
|
${v}`})}return{fileBlocks:a,warnings:l}}async function WU(e,t,n,r,o="summary",i,s){let a=OL(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0);let l="",c=0,d=!1,u=!1,p=!1,m=!1,g,h=!1,y=!1,b={abort:null},w=0,S=3e3,v=[],T=new Map,R=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,A=()=>{let j=r.subagentControl;j?.hasPromotableForeground()&&j.promoteActiveForeground().then(U=>{for(let P of U)(i??{fn:console.log}).fn(f.dim(` \u2192 subagent backgrounded as ${P.jobId}: ${P.label}`))}).catch(()=>{})},C=r.getCompositor?r.getCompositor():null,N=()=>new nl({out:rl(i),thinkingMode:o,...R?{activeSkillName:R}:{},onCancel:()=>{t.interrupt().catch(j=>{Ge()&&console.error(" "+f.error("session.interrupt() failed:"),j)})},...r.subagentControl?{onBackground:A}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...C?{compositor:C}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),_=N(),M=async()=>{if(!p){p=!0;try{await _.dispose()}catch{}}},B=async()=>{await _.arm();let j=_.getCompositor();if(i&&j){let U=j;i.fn=P=>U.commitAbove(P),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(j),r.setInterruptNotifier?.(U=>_.setInterrupting(U)),r.rearmStatus?.()};try{C?C.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{h=!0,t.interrupt().catch(O=>{Ge()&&console.error(" "+f.error("soft-stop session.interrupt() failed:"),O)});let I=r.subagentControl;I?.hasActiveForeground()&&I.cancelActiveForeground().catch(O=>{Ge()&&console.error(" "+f.error("soft-stop cancelActiveForeground() failed:"),O)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{y=!0,t.interrupt().catch(I=>{Ge()&&console.error(" "+f.error("pause-interrupt session.interrupt() failed:"),I)})}),await B(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(A);let{fileBlocks:j,warnings:U}=HU(e.text,{rootDir:process.cwd()});for(let I of U)(i??{fn:console.log}).fn(f.dim(` @-file: ${I}`));let P=j.length>0||e.attachments.length>0?UU(e.text,e.attachments,void 0,j):e.text,D=t.sendMessageStream(P);if(await Os((I,O)=>{_.process(I,O)},async()=>{for await(let I of D){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 O=I.chunk,$={toolName:O.toolName,toolUseId:O.toolUseId,input:O.toolInput,...O.toolInputRaw!==void 0&&{inputRaw:O.toolInputRaw}};T.set(O.toolUseId,$),v.push($)}else if(I.type==="chunk"&&I.chunk.type==="tool_result"){let O=I.chunk;c=l.length;let $=T.get(O.toolUseId);if($&&($.result=O.content,$.isError=O.isError,T.delete(O.toolUseId)),r.onContextProgress){let H=Date.now();if(H-w>=S){w=H;try{let z=r.onContextProgress();z instanceof Promise&&await z}catch(z){Ge()&&console.error(" "+f.error("onContextProgress (status refresh) failed:"),z)}}}}if(I.type==="paused"){if(r.setPausedState?.(!0),await M(),C&&I.autoResume===!0){let O=new AbortController;b.abort=O;let $=I.resetsAt?I.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,H=$?`Keep waiting \u2014 auto-resumes at ${$}`:"Keep waiting \u2014 auto-resume in progress",z="Switch model / provider (type /model after)",Q="Stop waiting",te=[f.warning(" \u23F3 Usage limit reached.")+($?f.dim(` Auto-resumes at ${$}.`):""),f.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];ur(C,{header:te,options:[H,z,Q],signal:O.signal,initialIndex:0}).then(oe=>{if(b.abort=null,!oe)return;let q=oe[0];q===void 0||q===H||(y=!0,q===z&&(i??{fn:console.log}).fn(f.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(Se=>{Ge()&&console.error(" "+f.error("picker pause-interrupt session.interrupt() failed:"),Se)}))}).catch(oe=>{Ge()&&console.error(" "+f.error("picker promise rejected:"),oe)})}else(i??{fn:console.log}).fn(Ux({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 O=I.hotSwapped&&I.accountId?`\u25B6 Resumed on ${I.accountId}`:"\u25B6 Resumed";l="",c=0,d=!1,v.length=0,T.clear(),m=!1,g=void 0,u=!1,_=N(),p=!1,await B(),(i??{fn:console.log}).fn(f.success(O));continue}if(I.type==="error"){await M(),hs(ps(I.error)),u=!0;continue}_.process(I),I.type==="done"&&(m=!0,g=I.metadata)}}),await M(),h){let I=i?i.fn:console.log;I(f.warning("\u23F8 Stopped \u2014 work so far kept.")+f.dim(" Send a message to continue.")),I("")}if(y){let I=i?i.fn:console.log;I(f.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),I("")}if(m&&!h&&!y){_i(n,a,l,g,v),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),Ba(process.stdout);let I=$=>{i?i.fn($):console.log($)},O=Fh(l);if(O){I(BU(O)),I("");let $=rF(v);if(r.onTerminalState)try{r.onTerminalState(O,{doneHasCorroboratingEvidence:$})}catch{}if(n.permissionMode==="autonomous"){let H=O.kind==="done"&&Vu().verifyDone===!0&&!$;iF(O,void 0,{unverified:H})}}if(dse(g,n,I),r.onAfterTurn){let $=r.onAfterTurn();$ instanceof Promise&&await $.catch(()=>{})}}}catch(j){await M(),u||hs(ps(j))}finally{await M(),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 cse(e,t){let n=Math.round(e*100),r=le(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${le(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 dse(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(we(e.durationMs)),e.totalCostUsd!==void 0&&r.push(ut(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(le(o+i)+" tok"),r.length>0&&n(f.dim(" \u25E6 "+r.join(" \xB7 ")));let s=ok(t),a=Xt(t.model),l=cse(s,a);if(l.text!==null){let c=l.tier==="over"||l.tier==="near"?f.error:l.tier==="caution"?f.warning:f.dim;n(c(l.text))}n("")}var use=5e3,pse=3,mse="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function fse(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(f.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function KU(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,verdictLedger:d,shellPassthrough:u,bgResultNotifier:p}=s,m=null,g=[];e.session.current.waitForInitialization().then(async R=>{Ge()&&(m=bg(R)),await $d(e.session.current),Ge()&&(g=gE())}).catch(()=>{});let h=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,y=!1,b=!1,w,S,v,T=0;for(p.onInjectable=()=>{T>=pse||!o.isAwaitingInput()||!o.bufferIsEmpty()||(T++,Ba(process.stdout),h={text:mse,attachments:[]},o.abortPendingRead())};;){if(m&&(e.replRenderer.writeLine(m),e.replRenderer.writeLine(""),m=null),g.length>0){for(let P of g)e.replRenderer.writeLine(P);e.replRenderer.writeLine(""),g=[]}let R=u.drainNotifications();for(let{job:P,result:D}of R){let F=D.errorReason===void 0?"\u2713":"\u2717",I=D.errorReason==="abort"?"killed":D.errorReason==="timeout"?"timed out":D.errorReason==="signal-killed"?"killed by signal":`exit ${D.exitCode??0}`,O=Math.max(0,Math.round(D.durationMs/100)/10);e.replRenderer.writeLine(f.dim(` ${F} [${P.id}] ${I} \xB7 ${O}s \xB7 `)+P.command)}let A=p.drainNotifications();for(let{job:P}of A){let D=P.status==="completed"?"\u2713":P.status==="failed"?"\u2717":"\u2298",F=P.endedAt!==void 0?Math.max(0,Math.round((P.endedAt-P.startedAt)/100)/10):0,I=P.label.length>60?`${P.label.slice(0,60)}\u2026`:P.label;e.replRenderer.writeLine(f.dim(` ${D} [${P.jobId}] subagent ${P.status} \xB7 ${F}s \xB7 `)+I)}let C=l.renderIfChanged(e.stats.sessionId);if(C.length>0){for(let P of C)e.replRenderer.writeLine(P);e.replRenderer.writeLine("")}let N,_;if(h===void 0){let P=await e.session.current.takePendingPlanExitSeed();P!==void 0&&(e.stats.permissionMode=P.mode,h={text:P.message,attachments:[]})}if(h!==void 0){let P=h;h=void 0;let D=al(e.stats.permissionMode),F=Bi({buffer:P.text,promptText:D,isTTY:!!process.stdout.isTTY,attachmentSummary:qa([...P.attachments])});e.replRenderer.writeLine(F),N=P.text.trim(),_=P.attachments}else{let P=await o.readLine({promptFn:()=>al(e.stats.permissionMode),onSigint:r,onShiftTab:()=>{Mh(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});N=P.text.trim(),_=P.attachments}if(!N&&_.length===0)continue;if(N.startsWith("!")){let P=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!P&&(y||(y=!0,e.replRenderer.writeLine(f.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(N))){e.statusLine.rearm();continue}}let M=!1;if(N.startsWith("/")){let P=await GD(N,e.slashCtx,_);if(P.handled){if(P.result==="exit"){e.rl.close();return}if((N==="/clear"||N.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(f.dim(` transcript: ${t.path()}`)),d.reset(),w=void 0),P.result!==null&&typeof P.result=="object"&&"kind"in P.result&&P.result.kind==="submit"){h={text:P.result.message,attachments:_??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}M=!0}a.push(N),await fse(e,N);let B=N;if(M){let P=rk(N);if(P){let D=P.name.replace(/^\//,"").split(":").pop()??"";if(D&&uE(D)){let F={skillName:D,rawArgs:P.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},I=e.session.current.sessionId,O=zi(I),$=Date.now();W(`[afk trace] preflight.start commandName=${D}`);let H=!1,z=await qi(F,{cwd:e.stats.cwd??process.cwd(),artifactDir:O},Q=>{Ge()&&e.replRenderer.writeLine(f.warning(`\u26A0 preflight(${D}) failed: `)+(Q instanceof Error?Q.message:String(Q)))});H=z!==null,W(`[afk trace] preflight.end commandName=${D} durationMs=${Date.now()-$} success=${H}`),B=mE(z?.manifestBlock,N)}}}let j=u.drainInjections();j.length>0&&(B=j+B);let U=p.drainInjections();if(U.length>0&&(B=U+B),w!==void 0&&(B=w+`
|
|
1792
1739
|
|
|
1793
1740
|
`+B,w=void 0),e.hookRegistry)try{let P={event:"UserPromptSubmit",prompt:B,sessionId:e.stats.sessionId},D=await e.hookRegistry.dispatch(P);D.injectContext&&(B=D.injectContext+B)}catch(P){if(P instanceof me){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+(P.reason?f.dim(`: ${Ir(P.reason)}`):"")),e.statusLine.rearm();continue}if(P instanceof zn){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+f.dim(`: handler timed out after ${P.timeoutMs}ms`)),e.statusLine.rearm();continue}throw P}if(S=void 0,v=void 0,await WU({text:B,attachments:_},e.session.current,e.stats,{setInFlight(P){n.turnInFlight=P},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(P){await t.appendUser(P)},async onTurnComplete(P,D){if(await t.appendTurn(P,D),e.stats.sessionId)try{Oo(e.stats)}catch(F){b||(b=!0,e.replRenderer.writeLine(f.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(F instanceof Error?F.message:String(F))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(P,D)=>{d?.push(P),S=P.kind,v=D?.doneHasCorroboratingEvidence},setActiveCompositor:P=>{n.activeCompositor=P},setInterruptNotifier:P=>{n.notifyInterrupting=P},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:P=>o.setBackgroundHandler(P),setSoftStopHandler:i,setPausedState:P=>o.setPausedState(P),setPauseInterruptHandler:P=>o.setPauseInterruptHandler(P),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(dr(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:P=>c.repaint(P)}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(al(e.stats.permissionMode))),e.hookRegistry)try{let P=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...S!==void 0?{terminalState:S}:{},...v!==void 0?{doneHasCorroboratingEvidence:v}:{}},void 0,use);P.injectContext&&P.injectContext.trim().length>0&&(w=P.injectContext)}catch(P){if(P instanceof gt)throw P;P instanceof zn?(W("[stop hook] handler timed out"),e.completionWriter.fn(f.dim(" [stop hook] timed out"))):P instanceof me?e.completionWriter.fn(f.dim(` [stop hook] blocked: ${Ir(P.reason??"no reason given")}`)):W("[stop hook] unexpected error: "+String(P))}}}function gse(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 GU(e,t,n,r){let o=await EU(),i=new Ph({rl:e.rl,history:o,statusLine:e.statusLine}),s=gse(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await AU(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar});a=NU(e,n),await KU(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)}}Ql();Ws();import{execFile as hse}from"node:child_process";import{dirname as yse,isAbsolute as bse,resolve as wse}from"node:path";import{promisify as Sse}from"node:util";var qU=Sse(hse),vse=3e3,kse=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function Ese(){let t=(await qU("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=bse(t)?t:wse(process.cwd(),t);return yse(n)}async function zU(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await Ese()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),vse)});try{let o=gn({execFile:qU,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=>kse.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Fu();Ql();import{promises as Tse}from"node:fs";import{dirname as xse,join as VU}from"node:path";import{randomBytes as Rse}from"node:crypto";var Cse=["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(`
|
|
1794
|
-
`),JU=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,LE=30,Ase=1024,_se=8e3,Ise="haiku";async function Pse(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=Dse(n,Ase),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??_se),s=t.signal?Fse([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await Es({token:t.token,model:t.model??Ise,system:Cse,user:r,maxTokens:32,signal:s})}catch(u){let p=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=Mse(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=xse(t.worktreePath);return await Ose(l,c)}function Mse(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(JU.test(t)&&t.length<=LE)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>LE)break;o=s}return JU.test(o)?o:null}async function Ose(e,t){if(!await $se(VU(t,e)))return e;let n=Rse(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,LE-5)}-${n}`}async function $se(e){try{return await Tse.access(e),!0}catch{return!1}}function Dse(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 Fse(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 XU(e){let t,n,r=VU(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Pse(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=`${Ku(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return YU(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 YU(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 YU(e,t){e&&e.setCwd(t),Lse(t)}function Lse(e){try{process.chdir(e)}catch{}}qt();G();import{spawn as ZU}from"child_process";import{existsSync as ej,mkdirSync as Hse,readFileSync as tj,unlinkSync as QU,writeFileSync as nj}from"fs";import{get as Wse}from"https";import{join as rj}from"path";import{readFileSync as Nse}from"fs";import{dirname as Bse,join as Use}from"path";import{fileURLToPath as jse}from"url";function hr(){try{return"5.
|
|
1741
|
+
`),JU=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,LE=30,Ase=1024,_se=8e3,Ise="haiku";async function Pse(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=Dse(n,Ase),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??_se),s=t.signal?Fse([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await Es({token:t.token,model:t.model??Ise,system:Cse,user:r,maxTokens:32,signal:s})}catch(u){let p=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=Mse(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=xse(t.worktreePath);return await Ose(l,c)}function Mse(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(JU.test(t)&&t.length<=LE)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>LE)break;o=s}return JU.test(o)?o:null}async function Ose(e,t){if(!await $se(VU(t,e)))return e;let n=Rse(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,LE-5)}-${n}`}async function $se(e){try{return await Tse.access(e),!0}catch{return!1}}function Dse(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 Fse(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 XU(e){let t,n,r=VU(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Pse(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=`${Ku(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return YU(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 YU(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 YU(e,t){e&&e.setCwd(t),Lse(t)}function Lse(e){try{process.chdir(e)}catch{}}qt();G();import{spawn as ZU}from"child_process";import{existsSync as ej,mkdirSync as Hse,readFileSync as tj,unlinkSync as QU,writeFileSync as nj}from"fs";import{get as Wse}from"https";import{join as rj}from"path";import{readFileSync as Nse}from"fs";import{dirname as Bse,join as Use}from"path";import{fileURLToPath as jse}from"url";function hr(){try{return"5.52.0"}catch{}try{let e=Bse(jse(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(Nse(Use(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}K();var Kse=64*1024,Gse=10800*1e3,qse=800,zse=3600*1e3,Jse="update-check.json",Yse="pending-update.json";function NE(){return rj(ds(),Jse)}function Ud(){return rj(ds(),Yse)}function BE(){let e=ds();ej(e)||Hse(e,{recursive:!0})}function oj(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 ij(){try{let e=tj(NE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function sj(){try{BE();let e=`
|
|
1795
1742
|
const https = require('https');
|
|
1796
1743
|
const fs = require('fs');
|
|
1797
1744
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|