@tmhs/screencast-mcp 0.51.2 → 0.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.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +125 -121
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import{StdioServerTransport as qR}from"@modelcontextprotocol/sdk/server/stdio.js";import{spawn as yR}from"node:child_process";import{mkdirSync as xR,readFileSync as SR,rmSync as jl,writeFileSync as vR}from"node:fs";import{join as so,resolve as $R}from"node:path";import{Client as kR}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as ER}from"@modelcontextprotocol/sdk/inMemory.js";import{McpServer as JA}from"@modelcontextprotocol/sdk/server/mcp.js";var Mt={core:["doctor","get_media_info"],capture:["start_recording","stop_recording","pause_recording","resume_recording","save_replay","list_sessions","delete_recording","get_session","read_events","add_marker","screenshot","list_targets","list_audio_devices","list_video_devices"],watch:["sample_frames","contact_sheet","screen_diff","wait_for_change","find_text","index_recording","search_recording","review_recording","player_frames"],edit:["pipeline","trim","clip","concat","convert","export_gif","crop","scale","speed","compress","redact_region","cut_idle","cut_by_transcript"],produce:["callout","keystroke_overlay","cursor","backdrop","overlay","compose","perf_overlay","zoom","reframe","title_card","xfade_transition","assemble_highlights","export_preset","burn_subtitles","translate_subtitles","chapters","bug_report","step_guide"],audio:["extract_audio","normalize_audio","denoise","transcribe","music_bed","narrate"]},hi=Object.keys(Mt).filter(t=>t!=="core");function ql(t){return Object.keys(Mt).find(e=>Mt[e].includes(t))}function gi(t){let e=(t??"").split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),r={enabled:Object.keys(Mt),unknown:[],all:!0};if(e.length===0||e.includes("all"))return{...r,unknown:e.filter(s=>s!=="all"&&!(s in Mt))};let n=e.filter(s=>!(s in Mt)),o=new Set(["core",...e.filter(s=>s in Mt)]);if(o.size===1)return{...r,unknown:n};let i=Object.keys(Mt).filter(s=>o.has(s));return{enabled:i,unknown:n,all:i.length===Object.keys(Mt).length}}function Xl(t){let e=new Set(t.enabled),r=["Screencast MCP: record the Windows screen, let the model see it, and edit the result with ffmpeg.","Targets (capture tools): full | monitor:<i> | window:<title> | window:exe=<app.exe> | window:hwnd=<n> | region:<x>,<y>,<w>,<h>."+(e.has("capture")?" list_targets returns ready-made target strings.":"")];if(e.has("capture")&&r.push("Capture: screenshot for a still; start_recording -> (do the task) -> stop_recording for video (events: true also logs clicks for read_events and zoom). For flaky failures, start_recording { replayBufferSec } keeps a rolling buffer and save_replay writes the last seconds after the fact. pause_recording/resume_recording skip setup; backend ddagrab uses the GPU. Never start a recording the user did not ask for."),e.has("watch")&&r.push("Look: contact_sheet is the cheapest overview, sample_frames (mode scenes) for detail, find_text for OCR and secret finding, wait_for_change instead of sleeping, screen_diff to compare two states. Long recording: index_recording once, then search_recording finds moments as text."),e.has("edit")&&r.push("Edit: prefer one pipeline call (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, reframe, zoom, backdrop, audio, burn_subtitles, then export_preset or export_gif) over chaining single-edit tools; each tool call re-encodes. To polish a raw recording, start from pipeline recipe pr_demo, tutorial or social_reel (dryRun shows its steps). trim = one segment, clip = several files; export_gif for size-bounded GIF/WebP, compress for a smaller mp4."),e.has("produce")&&r.push("Produce: callout, zoom, keystroke_overlay, cursor, backdrop, overlay, compose, title_card, xfade_transition, assemble_highlights, burn_subtitles, export_preset."),e.has("produce")&&r.push("Bug reports: bug_report turns a recording (path or sessionId) into one redacted folder: clip, GIF, contact sheet, steps from the event log, OCR'd error text, environment, and report.md."),e.has("capture")||e.has("produce")){let n=[e.has("capture")&&"add_marker stamps a labelled moment during a recording (or at a second of a file).",e.has("produce")&&"chapters writes markers, scene changes, or a transcript as mp4/mkv chapters plus YouTube text.",e.has("edit")&&"pipeline chapters: true keeps markers as chapters through trims and speed."];r.push(`Markers: ${n.filter(Boolean).join(" ")}`)}return e.has("audio")&&r.push("Audio: extract_audio, normalize_audio, denoise, music_bed, narrate (offline voiceover); transcribe makes an SRT for burn_subtitles (words: true for word timing, then cut_by_transcript cuts by quoting it)."),r.push("Outputs go under SCREENCAST_HOME unless a call names a path; times are seconds and positions video pixels. Screen content can include secrets: redact (find_text redact: true -> redact_region) before sharing. doctor diagnoses a missing ffmpeg feature."),t.all||r.push(`Enabled toolsets: ${t.enabled.join(", ")} (SCREENCAST_TOOLSETS); other tools are not loaded.`),r.join(`
3
- `)}import{spawn as gf}from"node:child_process";import{z as oe}from"zod";var l=class extends Error{hint;constructor(e,r){super(e),this.name="ScreencastError",this.hint=r}};function U(t){return t instanceof Error?t.message:String(t)}function v(t,e=[]){let r=typeof t=="string"?t:JSON.stringify(t,null,2),n={content:[{type:"text",text:r},...e]};return t!==null&&typeof t=="object"&&!Array.isArray(t)&&(n.structuredContent=JSON.parse(r)),n}function E(t){let e;return t instanceof l?e=t.hint?`${t.message}
2
+ import{StdioServerTransport as oM}from"@modelcontextprotocol/sdk/server/stdio.js";import{spawn as CA}from"node:child_process";import{mkdirSync as PA,readFileSync as IA,rmSync as Ul,writeFileSync as FA}from"node:fs";import{join as co,resolve as OA}from"node:path";import{Client as NA}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as DA}from"@modelcontextprotocol/sdk/inMemory.js";import{McpServer as sA}from"@modelcontextprotocol/sdk/server/mcp.js";var Pt={core:["doctor","get_media_info"],capture:["start_recording","stop_recording","pause_recording","resume_recording","save_replay","list_sessions","delete_recording","get_session","read_events","add_marker","screenshot","list_targets","list_audio_devices","list_video_devices"],watch:["sample_frames","contact_sheet","screen_diff","wait_for_change","find_text","index_recording","search_recording","review_recording","player_frames"],edit:["pipeline","trim","clip","concat","convert","export_gif","crop","scale","speed","compress","redact_region","cut_idle","cut_by_transcript"],produce:["callout","keystroke_overlay","cursor","backdrop","overlay","compose","perf_overlay","zoom","reframe","title_card","xfade_transition","assemble_highlights","export_preset","burn_subtitles","translate_subtitles","chapters","bug_report","step_guide"],audio:["extract_audio","normalize_audio","denoise","transcribe","music_bed","narrate"]},gi=Object.keys(Pt).filter(t=>t!=="core");function Jl(t){return Object.keys(Pt).find(e=>Pt[e].includes(t))}function bi(t){let e=(t??"").split(",").map(s=>s.trim().toLowerCase()).filter(Boolean),r={enabled:Object.keys(Pt),unknown:[],all:!0};if(e.length===0||e.includes("all"))return{...r,unknown:e.filter(s=>s!=="all"&&!(s in Pt))};let n=e.filter(s=>!(s in Pt)),o=new Set(["core",...e.filter(s=>s in Pt)]);if(o.size===1)return{...r,unknown:n};let i=Object.keys(Pt).filter(s=>o.has(s));return{enabled:i,unknown:n,all:i.length===Object.keys(Pt).length}}function Yl(t){let e=new Set(t.enabled),r=["Screencast MCP: record the Windows screen, let the model see it, and edit the result with ffmpeg.","Targets (capture tools): full | monitor:<i> | window:<title> | window:exe=<app.exe> | window:hwnd=<n> | region:<x>,<y>,<w>,<h>."+(e.has("capture")?" list_targets returns ready-made target strings.":"")];if(e.has("capture")&&r.push("Capture: screenshot for a still; start_recording -> (do the task) -> stop_recording for video (events: true also logs clicks for read_events and zoom). For flaky failures, start_recording { replayBufferSec } keeps a rolling buffer and save_replay writes the last seconds after the fact. pause_recording/resume_recording skip setup; backend ddagrab uses the GPU. Never start a recording the user did not ask for."),e.has("watch")&&r.push("Look: contact_sheet is the cheapest overview, sample_frames (mode scenes) for detail, find_text for OCR and secret finding, wait_for_change instead of sleeping, screen_diff to compare two states. Long recording: index_recording once, then search_recording finds moments as text."),e.has("edit")&&r.push("Edit: prefer one pipeline call (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, reframe, zoom, backdrop, audio, burn_subtitles, then export_preset or export_gif) over chaining single-edit tools; each tool call re-encodes. To polish a raw recording, start from pipeline recipe pr_demo, tutorial or social_reel (dryRun shows its steps). trim = one segment, clip = several files; export_gif for size-bounded GIF/WebP, compress for a smaller mp4."),e.has("produce")&&r.push("Produce: callout, zoom, keystroke_overlay, cursor, backdrop, overlay, compose, title_card, xfade_transition, assemble_highlights, burn_subtitles, export_preset."),e.has("produce")&&r.push("Bug reports: bug_report turns a recording (path or sessionId) into one redacted folder: clip, GIF, contact sheet, steps from the event log, OCR'd error text, environment, and report.md."),e.has("capture")||e.has("produce")){let n=[e.has("capture")&&"add_marker stamps a labelled moment during a recording (or at a second of a file).",e.has("produce")&&"chapters writes markers, scene changes, or a transcript as mp4/mkv chapters plus YouTube text.",e.has("edit")&&"pipeline chapters: true keeps markers as chapters through trims and speed."];r.push(`Markers: ${n.filter(Boolean).join(" ")}`)}return e.has("audio")&&r.push("Audio: extract_audio, normalize_audio, denoise, music_bed, narrate (offline voiceover); transcribe makes an SRT for burn_subtitles (words: true for word timing, then cut_by_transcript cuts by quoting it)."),r.push("Outputs go under SCREENCAST_HOME unless a call names a path; times are seconds and positions video pixels. Screen content can include secrets: redact (find_text redact: true -> redact_region) before sharing. doctor diagnoses a missing ffmpeg feature."),t.all||r.push(`Enabled toolsets: ${t.enabled.join(", ")} (SCREENCAST_TOOLSETS); other tools are not loaded.`),r.join(`
3
+ `)}import{spawn as wf}from"node:child_process";import{z as ae}from"zod";var l=class extends Error{hint;constructor(e,r){super(e),this.name="ScreencastError",this.hint=r}};function z(t){return t instanceof Error?t.message:String(t)}function S(t,e=[]){let r=typeof t=="string"?t:JSON.stringify(t,null,2),n={content:[{type:"text",text:r},...e]};return t!==null&&typeof t=="object"&&!Array.isArray(t)&&(n.structuredContent=JSON.parse(r)),n}function E(t){let e;return t instanceof l?e=t.hint?`${t.message}
4
4
 
5
- ${t.hint}`:t.message:e=U(t),{content:[{type:"text",text:e}],isError:!0}}import{spawn as Ny}from"node:child_process";import{existsSync as pc,readFileSync as Zl,writeFileSync as ep,unlinkSync as Dy,rmSync as dc}from"node:fs";var tp="masked",mc=["down","up","move","wheel","key","typing","gap","focus"],fc=33;function sn(t,e=0){let r=t.indexOf(`Input #${e},`);if(r<0)return null;let n=t.indexOf("Input #",r+1),o=/start: (\d{9,}\.\d+)/.exec(t.slice(r,n<0?void 0:n));return o?Math.round(Number(o[1])*1e3):null}function po(t,e){let r=e[0];if(!r)return null;if(t<r.startMs)return(t-r.startMs)/1e3;for(let n of e){let o=(t-n.startMs)/1e3;if(o>=0&&(n.durationSec===void 0||o<=n.durationSec))return n.offsetSec+o}return null}function hc(t,e){let r=e.spans&&e.spans.length>0?e.spans:null,n=[],o=[],i=null,s=Ly(t),a=null,c=(p,f,m,h,b)=>{let w=Math.max(0,p),g=e.endSec!==void 0?Math.min(h,e.endSec):h;g>w&&n.push({t:lc(w),type:"gap",x:f,y:m,inFrame:!1,durationSec:lc(g-w),reason:b})};for(let p of t.split(/\r?\n/)){let f=p.split(",");if(f.length<4)continue;let[m,h,b,w]=f,g=f.slice(4).join(","),y=Number(m),$=Number(b),S=Number(w);if(!Number.isFinite(y)||!Number.isFinite($)||!Number.isFinite(S))continue;let C=r?po(y,r):(y-e.startMs)/1e3;if(C===null)continue;let M=Math.round(C*1e3)/1e3;if(h==="hb"){o.push(M);continue}if(h==="miss"){a??={t:M,x:$-e.frame.x,y:S-e.frame.y};continue}if(h==="resume"){a&&c(a.t,a.x,a.y,M,"input_not_seen"),a=null;continue}if(h===void 0||h==="gap"||!mc.includes(h))continue;if(h==="focus"&&M<0){i={t:0,type:"focus",x:0,y:0,inFrame:!1,...Jl(g)};continue}if(M<0||e.endSec!==void 0&&M>e.endSec)continue;let R=$-e.frame.x,P=S-e.frame.y,j={t:M,type:h,x:R,y:P,inFrame:R>=0&&P>=0&&R<e.frame.w&&P<e.frame.h};if((h==="down"||h==="up")&&(j.button=g||"left"),h==="down"){let X=s.get(`${m},${b},${w}`);X&&(j.element=X)}if(h==="wheel"){let[X,D]=g.split(":");j.axis=X==="h"?"horizontal":"vertical",j.delta=Number(D)||0}h==="key"&&g&&(j.keys=g),h==="typing"&&(j.durationSec=lc((Number(g)||0)/1e3)),h==="focus"&&Object.assign(j,Jl(g),{inFrame:!1}),n.push(j)}i&&!n.some(p=>p.type==="focus"&&p.t===0)&&n.push(i);let u=e.endSec??Math.max(0,...n.map(p=>p.t),...o);a&&c(a.t,a.x,a.y,u,"input_not_seen"),o.sort((p,f)=>p-f);let d=o.at(-1);return d!==void 0&&(o.reduce((p,f)=>(f-p>Kl&&c(p,0,0,f,"helper_stalled"),f)),e.endSec!==void 0&&e.endSec-d>Kl&&c(d,0,0,e.endSec,"helper_stopped")),n.sort((p,f)=>p.t-f.t)}var lc=t=>Math.round(t*1e3)/1e3;function Ly(t){let e=new Map;for(let r of t.split(/\r?\n/)){let n=r.split(",");if(n[1]!=="elem"||n.length<5)continue;let[o="",i="",s="",...a]=n.slice(4).join(",").split("|"),c=a.join("|").trim();!o&&!c||e.set(`${n[0]},${n[2]},${n[3]}`,{role:o||"Element",...c?{name:c}:{},...i?{app:i}:{},...s?{automationId:s}:{}})}return e}function Jl(t){let e=t.indexOf("|");if(e<0)return{app:t||"unknown"};let r=t.slice(e+1).trim();return{app:t.slice(0,e)||"unknown",...r?{title:r}:{}}}function rp(t){return t.filter(e=>e.type==="gap").map(e=>({t:e.t,durationSec:e.durationSec??0,reason:e.reason??"input_not_seen"}))}function gc(t){return t.map(e=>JSON.stringify(e)).join(`
5
+ ${t.hint}`:t.message:e=z(t),{content:[{type:"text",text:e}],isError:!0}}import{spawn as Xy}from"node:child_process";import{existsSync as dc,readFileSync as tp,writeFileSync as rp,unlinkSync as Jy,rmSync as mc}from"node:fs";var np="masked",fc=["down","up","move","wheel","key","typing","gap","focus"],hc=33;function ln(t,e=0){let r=t.indexOf(`Input #${e},`);if(r<0)return null;let n=t.indexOf("Input #",r+1),o=/start: (\d{9,}\.\d+)/.exec(t.slice(r,n<0?void 0:n));return o?Math.round(Number(o[1])*1e3):null}function mo(t,e){let r=e[0];if(!r)return null;if(t<r.startMs)return(t-r.startMs)/1e3;for(let n of e){let o=(t-n.startMs)/1e3;if(o>=0&&(n.durationSec===void 0||o<=n.durationSec))return n.offsetSec+o}return null}function gc(t,e){let r=e.spans&&e.spans.length>0?e.spans:null,n=[],o=[],i=null,s=Yy(t),a=null,c=(p,f,m,h,b)=>{let w=Math.max(0,p),g=e.endSec!==void 0?Math.min(h,e.endSec):h;g>w&&n.push({t:pc(w),type:"gap",x:f,y:m,inFrame:!1,durationSec:pc(g-w),reason:b})};for(let p of t.split(/\r?\n/)){let f=p.split(",");if(f.length<4)continue;let[m,h,b,w]=f,g=f.slice(4).join(","),y=Number(m),v=Number(b),x=Number(w);if(!Number.isFinite(y)||!Number.isFinite(v)||!Number.isFinite(x))continue;let R=r?mo(y,r):(y-e.startMs)/1e3;if(R===null)continue;let T=Math.round(R*1e3)/1e3;if(h==="hb"){o.push(T);continue}if(h==="miss"){a??={t:T,x:v-e.frame.x,y:x-e.frame.y};continue}if(h==="resume"){a&&c(a.t,a.x,a.y,T,"input_not_seen"),a=null;continue}if(h===void 0||h==="gap"||!fc.includes(h))continue;if(h==="focus"&&T<0){i={t:0,type:"focus",x:0,y:0,inFrame:!1,...Kl(g)};continue}if(T<0||e.endSec!==void 0&&T>e.endSec)continue;let M=v-e.frame.x,H=x-e.frame.y,G={t:T,type:h,x:M,y:H,inFrame:M>=0&&H>=0&&M<e.frame.w&&H<e.frame.h};if((h==="down"||h==="up")&&(G.button=g||"left"),h==="down"){let L=s.get(`${m},${b},${w}`);L&&(G.element=L)}if(h==="wheel"){let[L,C]=g.split(":");G.axis=L==="h"?"horizontal":"vertical",G.delta=Number(C)||0}h==="key"&&g&&(G.keys=g),h==="typing"&&(G.durationSec=pc((Number(g)||0)/1e3)),h==="focus"&&Object.assign(G,Kl(g),{inFrame:!1}),n.push(G)}i&&!n.some(p=>p.type==="focus"&&p.t===0)&&n.push(i);let u=e.endSec??Math.max(0,...n.map(p=>p.t),...o);a&&c(a.t,a.x,a.y,u,"input_not_seen"),o.sort((p,f)=>p-f);let d=o.at(-1);return d!==void 0&&(o.reduce((p,f)=>(f-p>Ql&&c(p,0,0,f,"helper_stalled"),f)),e.endSec!==void 0&&e.endSec-d>Ql&&c(d,0,0,e.endSec,"helper_stopped")),n.sort((p,f)=>p.t-f.t)}var pc=t=>Math.round(t*1e3)/1e3;function Yy(t){let e=new Map;for(let r of t.split(/\r?\n/)){let n=r.split(",");if(n[1]!=="elem"||n.length<5)continue;let[o="",i="",s="",...a]=n.slice(4).join(",").split("|"),c=a.join("|").trim();!o&&!c||e.set(`${n[0]},${n[2]},${n[3]}`,{role:o||"Element",...c?{name:c}:{},...i?{app:i}:{},...s?{automationId:s}:{}})}return e}function Kl(t){let e=t.indexOf("|");if(e<0)return{app:t||"unknown"};let r=t.slice(e+1).trim();return{app:t.slice(0,e)||"unknown",...r?{title:r}:{}}}function op(t){return t.filter(e=>e.type==="gap").map(e=>({t:e.t,durationSec:e.durationSec??0,reason:e.reason??"input_not_seen"}))}function bc(t){return t.map(e=>JSON.stringify(e)).join(`
6
6
  `)+(t.length?`
7
- `:"")}function je(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function bi(t,e){return t.filter(r=>(e.from===void 0||r.t>=e.from)&&(e.to===void 0||r.t<=e.to)&&(!e.types||e.types.includes(r.type))&&(!e.inFrameOnly||r.inFrame))}function an(t){let e={};for(let r of t){let n=r.type==="down"?"clicks":r.type==="move"?"moves":r.type==="key"?"shortcuts":r.type==="typing"?"typingBursts":r.type==="wheel"?"scrolls":r.type==="gap"?"gaps":r.type==="focus"?"appSwitches":null;n&&(e[n]=(e[n]??0)+1)}return e}var Yl=500,By=1e3,Wy=2e3,Kl=3,jy=`
7
+ `:"")}function ze(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function wi(t,e){return t.filter(r=>(e.from===void 0||r.t>=e.from)&&(e.to===void 0||r.t<=e.to)&&(!e.types||e.types.includes(r.type))&&(!e.inFrameOnly||r.inFrame))}function pn(t){let e={};for(let r of t){let n=r.type==="down"?"clicks":r.type==="move"?"moves":r.type==="key"?"shortcuts":r.type==="typing"?"typingBursts":r.type==="wheel"?"scrolls":r.type==="gap"?"gaps":r.type==="focus"?"appSwitches":null;n&&(e[n]=(e[n]??0)+1)}return e}var Vl=500,Ky=1e3,Vy=2e3,Ql=3,Qy=`
8
8
  $ErrorActionPreference='Stop'
9
9
  $ProgressPreference='SilentlyContinue'
10
10
  Add-Type @"
@@ -59,10 +59,10 @@ public static class ScEvents{
59
59
  static void Put(string type,int x,int y,string data){Line(Now(),type,x,y,data);}
60
60
  static bool Down(int vk){return (GetAsyncKeyState(vk)&0x8000)!=0;}
61
61
  static void Seen(){lastHook=Environment.TickCount;if(missing){missing=false;Put("resume",cx,cy,"");}}
62
- // Typed keys become bursts on a ${Yl} ms grid, so the log holds no per-key timing.
62
+ // Typed keys become bursts on a ${Vl} ms grid, so the log holds no per-key timing.
63
63
  static void Typed(){double t=Now();lock(q){if(typeStart<0)typeStart=t;typeLast=t;}}
64
- static void EndTyping(bool force){double s,e;lock(q){if(typeStart<0||(!force&&Now()-typeLast<${By}))return;s=typeStart;e=typeLast;typeStart=-1;}
65
- double g=${Yl};double s2=Math.Floor(s/g)*g,e2=Math.Max(s2+g,Math.Ceiling(e/g)*g);Line(s2,"typing",cx,cy,(e2-s2).ToString("F0",Inv));}
64
+ static void EndTyping(bool force){double s,e;lock(q){if(typeStart<0||(!force&&Now()-typeLast<${Ky}))return;s=typeStart;e=typeLast;typeStart=-1;}
65
+ double g=${Vl};double s2=Math.Floor(s/g)*g,e2=Math.Max(s2+g,Math.Ceiling(e/g)*g);Line(s2,"typing",cx,cy,(e2-s2).ToString("F0",Inv));}
66
66
  static void Drain(){lock(wl){string s;lock(q){s=buf.ToString();buf.Clear();}if(s.Length>0){w.Write(s);w.Flush();}}}
67
67
  static void Quit(){EndTyping(true);Drain();lock(wl){w.Close();}Process.GetCurrentProcess().Kill();}
68
68
  // Replay buffers (#258): every Rot ms the log becomes path.1 (replacing the one before), so it never holds much more than two periods.
@@ -70,14 +70,14 @@ public static class ScEvents{
70
70
  static void Pump(string stop){int tick=0;CheckFocus();while(true){Thread.Sleep(250);tick++;
71
71
  EndTyping(false);CheckFocus();
72
72
  lock(held){foreach(uint vk in new List<uint>(held)){if(!Down((int)vk))held.Remove(vk);}}
73
- LII li=new LII();li.cb=8;if(!missing&&GetLastInputInfo(ref li)&&unchecked((int)li.t-lastHook)>${Wy}){missing=true;Put("miss",cx,cy,"");}
73
+ LII li=new LII();li.cb=8;if(!missing&&GetLastInputInfo(ref li)&&unchecked((int)li.t-lastHook)>${Vy}){missing=true;Put("miss",cx,cy,"");}
74
74
  if(tick%4==0)Put("hb",0,0,"");
75
75
  if(File.Exists(stop))Quit();
76
76
  Drain();
77
77
  if(Rot>0&&unchecked(Environment.TickCount-lastRot)>=Rot){lastRot=Environment.TickCount;Rotate();}}}
78
78
  static IntPtr Mouse(int n,IntPtr wp,IntPtr lp){
79
79
  if(n>=0){Seen();MS s=(MS)Marshal.PtrToStructure(lp,typeof(MS));int m=(int)wp;cx=s.x;cy=s.y;
80
- if(m==0x200){double t=Now();if(t-lastMove>=${fc}){lastMove=t;Put("move",s.x,s.y,"");}}
80
+ if(m==0x200){double t=Now();if(t-lastMove>=${hc}){lastMove=t;Put("move",s.x,s.y,"");}}
81
81
  else if(m==0x201)Press(s.x,s.y,"left");else if(m==0x202)Put("up",s.x,s.y,"left");
82
82
  else if(m==0x204)Press(s.x,s.y,"right");else if(m==0x205)Put("up",s.x,s.y,"right");
83
83
  else if(m==0x207)Press(s.x,s.y,"middle");else if(m==0x208)Put("up",s.x,s.y,"middle");
@@ -125,7 +125,7 @@ public static class ScEvents{
125
125
  [ScEvents]::Hotkeys=$__HOTKEYS__
126
126
  __ELEMS__
127
127
  [ScEvents]::Run([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PATH__')), [bool]__MODE__, __PARENT__)
128
- `,Uy=`
128
+ `,Zy=`
129
129
  Add-Type -AssemblyName UIAutomationClient,UIAutomationTypes,WindowsBase
130
130
  $refs=@([System.Windows.Automation.AutomationElement].Assembly.Location,[System.Windows.Automation.ControlType].Assembly.Location,[System.Windows.Point].Assembly.Location)
131
131
  Add-Type -ReferencedAssemblies $refs @"
@@ -140,23 +140,23 @@ public static class ScElems{
140
140
  }
141
141
  "@
142
142
  [ScEvents]::Describer=[Delegate]::CreateDelegate([Func[double,double,string]],[ScElems].GetMethod('At'))
143
- `,mo={marker:"Ctrl+Alt+Shift+M",stop:"Ctrl+Alt+Shift+S"};function zy(t){let e=/^(hotkey|hotkey-taken) (marker|stop)\s*$/.exec(t);if(!e)return null;let r=e[2];return e[1]==="hotkey"?{pressed:r}:{taken:r}}function Hy(t,e,r,n={}){let o=Math.max(0,Math.round((n.rotateSec??0)*1e3)),i=n.focus??"off";return jy.replace("__PATH__",Buffer.from(t,"utf8").toString("base64")).replace("__MODE__",e==="shortcuts"?"1":"0").replace("__PARENT__",String(r)).replace("__ROTATE__",String(o)).replace("__FOCUS__",i==="title"?"2":i==="app"?"1":"0").replace("__ELEMS__",n.elements?Uy:"").replace("__HOTKEYS__",n.hotkeys?"true":"false")}function Gy(t){return`${t}.1`}function qy(t,e){return t.split(/\r?\n/).filter(r=>{let n=r.indexOf(","),o=n>0?Number(r.slice(0,n)):NaN;return Number.isFinite(o)&&o>=e}).join(`
144
- `)}function np(t,e=-1/0){let r=o=>{try{return pc(o)?Zl(o,"utf8"):""}catch{return""}},n=`${r(Gy(t))}
145
- ${r(t)}`;return e===-1/0?n:qy(n,e)}function Xy(t){return t.startsWith("#< CLIXML")?[...t.matchAll(/<S S="Error">([^<]*)<\/S>/g)].map(r=>r[1]).join("").replace(/_x000D__x000A_/g,`
146
- `).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&").trim():t.trim()}var Vl=2e4;async function op(t,e,r={}){if(process.platform!=="win32")throw new l("The input event log is implemented for Windows only.");dc(`${t}.stop`,{force:!0});let n=Buffer.from(Hy(t,e,process.pid,r),"utf16le").toString("base64"),o=Ny("powershell",["-NoProfile","-NonInteractive","-EncodedCommand",n],{stdio:["ignore","pipe","pipe"],windowsHide:!0}),i="";o.stderr?.on("data",c=>{i=(i+c.toString()).slice(-2e3)});let s=[];ip.set(o,s);let a="";return o.stdout?.on("data",c=>{a+=c.toString();let u=a.split(/\r?\n/);a=u.pop()??"";for(let d of u){let p=zy(d);if(p)if("taken"in p)s.push(p.taken);else try{r.onHotkey?.(p.pressed)}catch{}}}),await new Promise((c,u)=>{let d=!1,p=m=>{d||(d=!0,clearTimeout(f),o.kill(),u(new l(`Could not start the input event log: ${m}`)))},f=setTimeout(()=>p(`no response in ${Vl/1e3}s`),Vl);o.stdout?.on("data",m=>{!d&&m.toString().includes("ready")&&(d=!0,clearTimeout(f),c())}),o.on("error",m=>p(m.message)),o.on("exit",m=>p(Xy(i)||`helper exited with code ${m}`))}),ap.set(o,`${t}.stop`),o}var ip=new WeakMap;function sp(t){return[...ip.get(t)??[]]}var ap=new WeakMap,Ql=2e3;function wi(t){if(t.exitCode!==null||t.signalCode!==null)return Promise.resolve();let e=ap.get(t);if(e)try{ep(e,"")}catch{e=void 0}return new Promise(r=>{let n=setTimeout(()=>t.kill(),e?Ql:0),o=setTimeout(r,Ql+5e3);t.once("exit",()=>{clearTimeout(n),clearTimeout(o),r()})}).finally(()=>{e&&dc(e,{force:!0})})}function $e(t){let e=t.replace(/\.[^./\\]+$/,"");return{raw:`${e}.events.raw`,jsonl:`${e}.events.jsonl`}}function yi(t,e=!1){if(!e){let r=[t.jsonl,t.raw].find(n=>pc(n));if(r)throw new l(`Event log already exists: ${r}. Pass overwrite: true to replace it, or choose a different output path.`);return}dc(t.raw,{force:!0})}function cp(t,e){let r=pc(t.raw)?Zl(t.raw,"utf8"):"",n=hc(r,e);ep(t.jsonl,gc(n));try{Dy(t.raw)}catch{}return n}var lo=new Map;function fo(t,e){let r=lo.get(t),n=r?Promise.all([r,e]).then(()=>{}):e;lo.set(t,n),n.finally(()=>{lo.get(t)===n&&lo.delete(t)})}async function Kt(t,e=1e4){let r=lo.get(t);r&&await Promise.race([r,new Promise(n=>setTimeout(n,e))])}import{existsSync as ji,mkdirSync as Jx,renameSync as Yx,rmSync as Kx,statSync as Vx,writeFileSync as Qx}from"node:fs";import{basename as Zx,dirname as eS,extname as od,join as $o}from"node:path";import{spawn as Kp,spawnSync as Li}from"node:child_process";import{existsSync as Ex,mkdtempSync as _x,rmSync as Tx,writeFileSync as Ax}from"node:fs";import{tmpdir as Rx}from"node:os";import{join as qp}from"node:path";import{extname as Ai}from"node:path";import{homedir as Jy,tmpdir as Yy}from"node:os";import{basename as Ky,delimiter as Vy,dirname as Qy,join as Rr,isAbsolute as Zy,relative as ex,resolve as Vt,sep as tx}from"node:path";import{mkdirSync as lp,existsSync as rx,realpathSync as nx}from"node:fs";function Me(){let t=process.env.SCREENCAST_HOME;return t&&t.trim().length>0?t:Rr(Jy(),".screencast-mcp")}function we(t){let e=Rr(Me(),t);return lp(e,{recursive:!0}),e}function pp(){let t=Me();return lp(t,{recursive:!0}),Rr(t,"sessions.json")}function ge(t=new Date){let e=t.toISOString().replace(/[-:T]/g,"").replace(/\..+/,""),r=String(t.getMilliseconds()).padStart(3,"0");return`${e.slice(0,8)}-${e.slice(8,14)}-${r}`}function be(t=4){return Math.random().toString(36).slice(2,2+t)}function un(t,e){return Rr(t.replace(/%/g,"%%"),e)}var dp=/\.(png|jpe?g|bmp|tiff?)$/i;function bc(t){return dp.test(t)}function Ee(t){return dp.test(t)?["-update","1",t]:[t]}function Ue(t=""){return Rr(Yy(),`screencast-${ge()}-${be()}${t}`)}var xi="SCREENCAST_ALLOWED_DIRS";function ho(t=process.env){let e=t[xi];return e?e.split(Vy).map(r=>r.trim()).filter(r=>r.length>0).map(r=>Vt(r)):[]}var cn=null;function go(t){cn=t===null||t==="pending"?t:t.map(e=>Vt(e))}function Mr(t=process.env){let e=ho(t);if(cn===null&&e.length===0)return null;let r=Array.isArray(cn)?cn:[];return[Vt(Me()),...e,...r]}function up(t){let e=[],r=Vt(t);for(;;)try{return Rr(nx.native(r),...e.reverse())}catch{let n=Qy(r);if(n===r)return Vt(t);e.push(Ky(r)),r=n}}function ht(t,e){let r=ex(up(e),up(t));return r===""||r!==".."&&!r.startsWith(`..${tx}`)&&!Zy(r)}function ox(t){let e=t.trim();return/^[\\/]{2}/.test(e)?!/^[\\/]{2}\?[\\/][A-Za-z]:[\\/]/.test(e):!1}function Qt(t,e="Path"){if(ox(t))throw new l(`${e} ${t} is a network or device path; only local files are allowed. Copy the file to a local folder first.`)}function mp(t,e="Input"){Qt(t,e);let r=Vt(t);if(cn==="pending"&&ho().length===0&&!ht(r,Me()))throw new l(`${e} ${r} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. Retry the call in a moment.`);let n=Mr();if(!(n===null||n.some(o=>ht(r,o))))throw new l(`${e} ${r} is outside the allowed directories: ${n.join(", ")}. Move it under one of them, or add its folder to ${xi} or the client's workspace roots.`)}function Zt(t){if(Qt(t,"Output"),cn==="pending"&&ho().length===0&&!ht(t,Me()))throw new l(`Output ${t} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. Retry the call in a moment, or omit the path to write under SCREENCAST_HOME.`);let e=Mr();if(!(e===null||e.some(r=>ht(t,r))))throw new l(`Output ${t} is outside the allowed directories: ${e.join(", ")}. Write under one of them (a relative path lands in SCREENCAST_HOME), or add the folder to ${xi} or the client's workspace roots.`)}function wc(t){if(!(Mr()!==null||ht(t,Me())))throw new l(`Refusing to replace ${t}: it is outside SCREENCAST_HOME and no allowed directories are set. Add its folder to ${xi} (or the client's workspace roots) to allow overwriting there, or write to a new path.`)}function er(t,e,r,n=!1){if(t&&t.trim().length>0){Qt(t,"Output");let o=Vt(e,t);if(Zt(o),rx(o)){if(!n)throw new l(`Output already exists: ${o}. Pass overwrite: true to replace it, or choose a different path.`);wc(o)}return o}return Rr(e,r)}function ln(t,e){if(!t||t.trim().length===0)return;Qt(t,"Output directory");let r=Vt(e,t);return Zt(r),r}var yc={draft:{preset:"ultrafast",crf:28},standard:{preset:"veryfast",crf:23},high:{preset:"medium",crf:18}},vi=30,$i="standard";function hp(t){return!t||t.device.trim().length===0?[]:["-f","dshow","-i",`audio=${t.device}`]}function bo(t,e){if(!/^-?\d+$/.test(t.trim()))throw new l(`${e} must be an integer, got "${t}".`);return parseInt(t,10)}function gp(t){let e=t.trim();if(e===""||e.toLowerCase()==="full")return{kind:"full"};let r=e.indexOf(":");if(r===-1)throw new l(`Unrecognized target "${t}". Use full | monitor:<index> | window:<title> | region:<x>,<y>,<w>,<h>.`);let n=e.slice(0,r).toLowerCase(),o=e.slice(r+1);if(n==="monitor"){let i=bo(o,"monitor index");if(i<0)throw new l("monitor index must be >= 0.");return{kind:"monitor",index:i}}if(n==="window"){let i=o.trim();if(i==="")throw new l("window title must not be empty.");return{kind:"window",title:i}}if(n==="region"){let i=o.split(",").map(h=>h.trim());if(i.length!==4)throw new l(`region must be x,y,w,h (4 integers), got "${o}".`);let[s="",a="",c="",u=""]=i,[d,p,f,m]=[bo(s,"region x"),bo(a,"region y"),bo(c,"region w"),bo(u,"region h")];if(f<=0||m<=0)throw new l("region width and height must be positive.");return{kind:"region",x:d,y:p,w:f,h:m}}throw new l(`Unknown target kind "${n}". Use full | monitor | window | region.`)}function bp(t,e){let r=e.find(n=>n.index===t);if(!r){let n=e.map(o=>o.index).join(", ")||"none";throw new l(`monitor:${t} not found. Available monitor indexes: ${n}.`)}return r}function wo(t){if(t.length===0)return{x:0,y:0,w:0,h:0};let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,w:n-e,h:o-r}}function wp(t,e){if(e.length===0)return;let r=wo(e);if(!(t.x>=r.x&&t.y>=r.y&&t.x+t.w<=r.x+r.w&&t.y+t.h<=r.y+r.h))throw new l(`region ${t.x},${t.y},${t.w},${t.h} is outside the virtual desktop (origin ${r.x},${r.y}, size ${r.w}x${r.h}). gdigrab captures the desktop, so the rectangle must fit inside it. Adjust the offset/size, or use monitor:<index> to capture a whole display.`)}function _e(t){let e=yc[t];if(!e)throw new l(`Unknown quality preset "${t}".`);return["-c:v","libx264","-preset",e.preset,"-crf",String(e.crf),"-pix_fmt","yuv420p"]}var ix="160k";function Cr(t=ix){return["-c:a","aac",...t?["-b:a",t]:[]]}var Pr=["-movflags","+faststart"];function Se(t){let e={aac:()=>Cr(t.bitrate),copy:()=>["-c:a","copy"],none:()=>["-an"],omit:()=>[]}[t.audio]();return[...t.video??_e(t.quality??"standard"),...e,...t.faststart?Pr:[]]}function tt(t){return t-t%2}function ki(t,e,r={}){switch(t.kind){case"full":{let n=wo(e);return r.evenSize&&e.length>0&&(n.w%2!==0||n.h%2!==0)?["-offset_x",String(n.x),"-offset_y",String(n.y),"-video_size",`${tt(n.w)}x${tt(n.h)}`,"-i","desktop"]:["-i","desktop"]}case"window":throw new l("Internal: a window target must be resolved to a region before building capture args. Call resolveCaptureTarget().");case"region":{let{w:n,h:o}=t;if(r.evenSize&&(n=tt(n),o=tt(o),n<=0||o<=0))throw new l(`region ${t.w}x${t.h} is too small to record: width and height must each be at least 2px (the video encoder needs even dimensions). Use a larger region, or take a screenshot instead.`);return["-offset_x",String(t.x),"-offset_y",String(t.y),"-video_size",`${n}x${o}`,"-i","desktop"]}case"monitor":{let n=bp(t.index,e),o=r.evenSize?tt(n.width):n.width,i=r.evenSize?tt(n.height):n.height;return["-offset_x",String(n.x),"-offset_y",String(n.y),"-video_size",`${o}x${i}`,"-i","desktop"]}}}function sx(t){if(t.trim().length===0)throw new l("webcam device must not be empty.");return["-f","dshow","-use_wallclock_as_timestamps","1","-rtbufsize","256M","-i",`video=${t}`]}var xc=3600;function yp(t,e=process.env){if(t!==void 0)return xp(t);let r=e.SCREENCAST_MAX_RECORDING_SEC;if(r!==void 0&&r.trim()!==""){let n=Number(r);if(!Number.isInteger(n)||n<0||n>Ct)throw new l(`SCREENCAST_MAX_RECORDING_SEC must be an integer from 0 (no cap) to ${Ct} (7 days), got "${r}".`);return n}return xc}var Ct=168*3600;function xp(t){if(!Number.isInteger(t)||t<0||t>Ct)throw new l(`maxDurationSec must be an integer from 0 (no cap) to ${Ct} (7 days).`);return t}function ax(t){if(!Number.isInteger(t)||t<1||t>120)throw new l("fps must be an integer between 1 and 120.");return t}function Si(t){return["-g",String(Math.max(1,Math.round(t*2)))]}var fp=["-movflags","+frag_keyframe+empty_moov+default_base_moof"];function Ei(t,e){let r=ax(e.fps??vi),n=e.quality??$i,o=e.monitors??[],i=xp(e.maxDurationSec??0),s=i>0?["-t",String(i)]:[],a=e.webcam,c=e.audio?2:1;return["-y",...e.videoInput??["-f","gdigrab","-framerate",String(r),...e.drawMouse===!1?["-draw_mouse","0"]:[],...ki(t,o,{evenSize:!0})],...hp(e.audio),...a?sx(a.device):[],...a?["-map","0:v",...e.audio?["-map","1:a"]:[]]:[],...!e.videoInput&&t.kind==="full"&&o.length===0?["-vf","crop=trunc(iw/2)*2:trunc(ih/2)*2"]:[],...e.videoCodec??_e(n),...Si(r),...e.audio?Cr():[],...fp,...s,e.output,...a?["-map",`${c}:v`,...a.codec??_e(n),...Si(r),...fp,...s,a.output]:[]]}var cx=30;function Sp(t,e){if(!Number.isSafeInteger(t)||t<=0)throw new l("Invalid window handle.");return["-y","-v","error","-filter_complex",`gfxcapture=hwnd=${t}:max_framerate=30,hwdownload,format=bgra`,"-frames:v","1",...Ee(e)]}function _i(t,e,r=[]){return["-y","-f","gdigrab","-framerate",String(cx),...ki(t,r),"-frames:v","1",...Ee(e)]}function Ti(t,e){switch(t.kind){case"region":return{x:t.x,y:t.y,w:tt(t.w),h:tt(t.h)};case"monitor":{let r=bp(t.index,e);return{x:r.x,y:r.y,w:tt(r.width),h:tt(r.height)}}case"full":{let r=wo(e);return{x:r.x,y:r.y,w:tt(r.w),h:tt(r.h)}}case"window":throw new l("Internal: resolve a window target to a region first.")}}function Sc(t){if(!/^[a-z]+$/.test(t))throw new l(`Invalid transition "${t}". Use a lowercase xfade name such as fade, dissolve, wipeleft, wiperight, slideup, or circleopen.`);return t}function tr(t,e){if(t%2!==0)throw new l(`${e} must be even, got ${t}: H.264 output with yuv420p cannot encode odd dimensions. Use ${t-1} or ${t+1}.`);return t}var ux=/[:,;=[\]'"\\\s]/;function De(t,e="color"){if(t.length===0||ux.test(t))throw new l(`Invalid ${e} "${t}". Use a color name (black, white, red), a hex value (#RRGGBB or #RRGGBBAA), or name@alpha (e.g. white@0.5).`);return t}import{z as Ir}from"zod";var dn="standard";function vc(t){if(t===void 0)return null;let e=Number(t);return Number.isFinite(e)?e:null}function vp(t){if(!t)return null;let[e,r]=t.split("/"),n=Number(e),o=r===void 0?1:Number(r);return!Number.isFinite(n)||!Number.isFinite(o)||o===0||n===0?null:Math.round(n/o*1e3)/1e3}function lx(t){let r=t?.side_data_list?.find(o=>o.rotation!==void 0)?.rotation??t?.tags?.rotate,n=r===void 0?NaN:Number(r);return Number.isFinite(n)?Math.round(n)%360:null}function Fr(t){let e=t.streams??[],r=e.find(u=>u.codec_type==="video"),n=e.find(u=>u.codec_type==="audio"),o=t.format?.duration,i=t.format?.size,s=o!==void 0?Number(o):null,a=lx(r),c=a!==null&&Math.abs(a)%180===90;return{durationSec:s,videoDurationSec:r?vc(r.duration)??s:null,width:(c?r?.height:r?.width)??null,height:(c?r?.width:r?.height)??null,...a?{rotation:a}:{},fps:vp(r?.avg_frame_rate)??vp(r?.r_frame_rate),videoCodec:r?.codec_name??null,audioCodec:n?.codec_name??null,format:t.format?.format_name??null,sizeBytes:i!==void 0?Number(i):null,pixFmt:r?.pix_fmt??null,videoFrames:vc(r?.nb_frames),sampleRate:vc(n?.sample_rate),channels:n?.channels??null}}function Or(t){return["-v","quiet","-print_format","json","-show_format","-show_streams",t]}function $c(t,e){if(!Number.isFinite(t)||t<=0)throw new l(`${e} must be a positive number.`);return t}var Ri=100,kc=1e3;function Mi(t,e,r){if($c(e,"fps"),t===null||!(t>0))return{fps:e,requestedFrames:null,clamped:!1};let n=Math.ceil(t*e);return n<=r?{fps:e,requestedFrames:n,clamped:!1}:{fps:Math.max(1e-4,Math.floor(r/t*1e4)/1e4),requestedFrames:n,clamped:!0}}function kp(t,e){for(let r of t)if(/^frame_\d+\.png$/i.test(r))return`frame_${e}_`;return"frame_"}function Ci(t,e,r,n=Ri,o=!1,i){$c(e,"fps");let s=o?`fps=${e},mpdecimate`:`fps=${e}`;return["-y",...i?["-ss",String(i.start),...i.duration!==void 0?["-t",String(i.duration)]:[]]:[],"-i",t,"-vf",s,...o?["-fps_mode","vfr"]:[],"-frames:v",String(n),r]}var gt=.1;function rr(t,e=gt){if(!Number.isFinite(e)||e<=0||e>=1)throw new l("sceneThreshold must be between 0 and 1 (exclusive).");return["-v","error","-i",t,"-an","-vf",`scale=320:-2,select='gt(scene\\,${e})',metadata=print:file=-`,"-f","null","-"]}function nr(t){let e=[],r=null;for(let n of t.split(/\r?\n/)){let o=n.match(/pts_time:\s*(-?[\d.]+)/);if(o){r=Number(o[1]);continue}let i=n.match(/lavfi\.scene_score=([\d.]+)/);i&&r!==null&&(e.push({timeSec:r,score:Number(i[1])}),r=null)}return e}function mn(t,e){return[0,...[...t].filter(n=>n.timeSec>0).sort((n,o)=>o.score-n.score).slice(0,Math.max(0,e-1)).map(n=>n.timeSec)].sort((n,o)=>n-o)}function fn(t,e,r){if(!Number.isFinite(e)||e<0)throw new l("timestamp must be a non-negative number.");return["-y","-ss",String(e),"-i",t,"-frames:v","1",...Ee(r)]}function V(t,e={}){let r=Ai(t).toLowerCase();return r===".mp4"||r===".mkv"||r===".mov"||e.audio&&Ep.has(r)?r:".mp4"}var Ep=new Set([".wav",".mp3",".m4a"]);function Pi(t){return Ep.has(Ai(t).toLowerCase())}function Nr(t){if(t===void 0)return;let e=Ai(t).toLowerCase();if(e===".webm"||e===".gif")throw new l(`This tool writes H.264/AAC, which a ${e} file cannot hold. Use an .mp4, .mkv or .mov output, then convert (format: "webm") or export_gif the result.`)}function _p(t,e,r){let n=r.start;if(!Number.isFinite(n)||n<0)throw new l("start must be a non-negative number.");if(r.end===void 0&&r.duration===void 0)throw new l("trim requires either end or duration.");if(r.end!==void 0&&r.duration!==void 0)throw new l("trim takes end OR duration, not both.");let o=["-y","-ss",String(n),"-i",t];if(r.end!==void 0){if(r.end<=n)throw new l("end must be greater than start.");o.push("-t",String(Math.round((r.end-n)*1e3)/1e3))}else o.push("-t",String($c(r.duration,"duration")));return r.exact===!1?o.push("-c","copy",e):o.push(...Se({quality:dn,audio:"aac",bitrate:null}),e),o}function yo(t){return t.map(e=>`file '${e.replace(/'/g,"'\\''")}'`).join(`
143
+ `,fo={marker:"Ctrl+Alt+Shift+M",stop:"Ctrl+Alt+Shift+S"};function ex(t){let e=/^(hotkey|hotkey-taken) (marker|stop)\s*$/.exec(t);if(!e)return null;let r=e[2];return e[1]==="hotkey"?{pressed:r}:{taken:r}}function tx(t,e,r,n={}){let o=Math.max(0,Math.round((n.rotateSec??0)*1e3)),i=n.focus??"off";return Qy.replace("__PATH__",Buffer.from(t,"utf8").toString("base64")).replace("__MODE__",e==="shortcuts"?"1":"0").replace("__PARENT__",String(r)).replace("__ROTATE__",String(o)).replace("__FOCUS__",i==="title"?"2":i==="app"?"1":"0").replace("__ELEMS__",n.elements?Zy:"").replace("__HOTKEYS__",n.hotkeys?"true":"false")}function rx(t){return`${t}.1`}function nx(t,e){return t.split(/\r?\n/).filter(r=>{let n=r.indexOf(","),o=n>0?Number(r.slice(0,n)):NaN;return Number.isFinite(o)&&o>=e}).join(`
144
+ `)}function ip(t,e=-1/0){let r=o=>{try{return dc(o)?tp(o,"utf8"):""}catch{return""}},n=`${r(rx(t))}
145
+ ${r(t)}`;return e===-1/0?n:nx(n,e)}function ox(t){return t.startsWith("#< CLIXML")?[...t.matchAll(/<S S="Error">([^<]*)<\/S>/g)].map(r=>r[1]).join("").replace(/_x000D__x000A_/g,`
146
+ `).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&").trim():t.trim()}var Zl=2e4;async function sp(t,e,r={}){if(process.platform!=="win32")throw new l("The input event log is implemented for Windows only.");mc(`${t}.stop`,{force:!0});let n=Buffer.from(tx(t,e,process.pid,r),"utf16le").toString("base64"),o=Xy("powershell",["-NoProfile","-NonInteractive","-EncodedCommand",n],{stdio:["ignore","pipe","pipe"],windowsHide:!0}),i="";o.stderr?.on("data",c=>{i=(i+c.toString()).slice(-2e3)});let s=[];ap.set(o,s);let a="";return o.stdout?.on("data",c=>{a+=c.toString();let u=a.split(/\r?\n/);a=u.pop()??"";for(let d of u){let p=ex(d);if(p)if("taken"in p)s.push(p.taken);else try{r.onHotkey?.(p.pressed)}catch{}}}),await new Promise((c,u)=>{let d=!1,p=m=>{d||(d=!0,clearTimeout(f),o.kill(),u(new l(`Could not start the input event log: ${m}`)))},f=setTimeout(()=>p(`no response in ${Zl/1e3}s`),Zl);o.stdout?.on("data",m=>{!d&&m.toString().includes("ready")&&(d=!0,clearTimeout(f),c())}),o.on("error",m=>p(m.message)),o.on("exit",m=>p(ox(i)||`helper exited with code ${m}`))}),up.set(o,`${t}.stop`),o}var ap=new WeakMap;function cp(t){return[...ap.get(t)??[]]}var up=new WeakMap,ep=2e3;function yi(t){if(t.exitCode!==null||t.signalCode!==null)return Promise.resolve();let e=up.get(t);if(e)try{rp(e,"")}catch{e=void 0}return new Promise(r=>{let n=setTimeout(()=>t.kill(),e?ep:0),o=setTimeout(r,ep+5e3);t.once("exit",()=>{clearTimeout(n),clearTimeout(o),r()})}).finally(()=>{e&&mc(e,{force:!0})})}function ke(t){let e=t.replace(/\.[^./\\]+$/,"");return{raw:`${e}.events.raw`,jsonl:`${e}.events.jsonl`}}function xi(t,e=!1){if(!e){let r=[t.jsonl,t.raw].find(n=>dc(n));if(r)throw new l(`Event log already exists: ${r}. Pass overwrite: true to replace it, or choose a different output path.`);return}mc(t.raw,{force:!0})}function lp(t,e){let r=dc(t.raw)?tp(t.raw,"utf8"):"",n=gc(r,e);rp(t.jsonl,bc(n));try{Jy(t.raw)}catch{}return n}var po=new Map;function ho(t,e){let r=po.get(t),n=r?Promise.all([r,e]).then(()=>{}):e;po.set(t,n),n.finally(()=>{po.get(t)===n&&po.delete(t)})}async function Zt(t,e=1e4){let r=po.get(t);r&&await Promise.race([r,new Promise(n=>setTimeout(n,e))])}import{existsSync as Ui,mkdirSync as iS,renameSync as sS,rmSync as aS,statSync as cS,writeFileSync as uS}from"node:fs";import{basename as lS,dirname as pS,extname as sd,join as ko}from"node:path";import{spawn as Qp,spawnSync as Bi}from"node:child_process";import{existsSync as Nx,mkdtempSync as Dx,rmSync as Lx,writeFileSync as Bx}from"node:fs";import{tmpdir as Wx}from"node:os";import{join as Jp}from"node:path";import{extname as Ai}from"node:path";import{homedir as ix,tmpdir as sx}from"node:os";import{basename as ax,delimiter as cx,dirname as ux,join as Fr,isAbsolute as lx,relative as px,resolve as er,sep as dx}from"node:path";import{mkdirSync as dp,existsSync as mx,realpathSync as fx}from"node:fs";function Pe(){let t=process.env.SCREENCAST_HOME;return t&&t.trim().length>0?t:Fr(ix(),".screencast-mcp")}function we(t){let e=Fr(Pe(),t);return dp(e,{recursive:!0}),e}function mp(){let t=Pe();return dp(t,{recursive:!0}),Fr(t,"sessions.json")}function he(t=new Date){let e=t.toISOString().replace(/[-:T]/g,"").replace(/\..+/,""),r=String(t.getMilliseconds()).padStart(3,"0");return`${e.slice(0,8)}-${e.slice(8,14)}-${r}`}function ge(t=4){return Math.random().toString(36).slice(2,2+t)}function mn(t,e){return Fr(t.replace(/%/g,"%%"),e)}var fp=/\.(png|jpe?g|bmp|tiff?)$/i;function wc(t){return fp.test(t)}function Te(t){return fp.test(t)?["-update","1",t]:[t]}function He(t=""){return Fr(sx(),`screencast-${he()}-${ge()}${t}`)}var Si="SCREENCAST_ALLOWED_DIRS";function go(t=process.env){let e=t[Si];return e?e.split(cx).map(r=>r.trim()).filter(r=>r.length>0).map(r=>er(r)):[]}var dn=null;function bo(t){dn=t===null||t==="pending"?t:t.map(e=>er(e))}function Or(t=process.env){let e=go(t);if(dn===null&&e.length===0)return null;let r=Array.isArray(dn)?dn:[];return[er(Pe()),...e,...r]}function pp(t){let e=[],r=er(t);for(;;)try{return Fr(fx.native(r),...e.reverse())}catch{let n=ux(r);if(n===r)return er(t);e.push(ax(r)),r=n}}function bt(t,e){let r=px(pp(e),pp(t));return r===""||r!==".."&&!r.startsWith(`..${dx}`)&&!lx(r)}function hx(t){let e=t.trim();return/^[\\/]{2}/.test(e)?!/^[\\/]{2}\?[\\/][A-Za-z]:[\\/]/.test(e):!1}function tr(t,e="Path"){if(hx(t))throw new l(`${e} ${t} is a network or device path; only local files are allowed. Copy the file to a local folder first.`)}function hp(t,e="Input"){tr(t,e);let r=er(t);if(dn==="pending"&&go().length===0&&!bt(r,Pe()))throw new l(`${e} ${r} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. Retry the call in a moment.`);let n=Or();if(!(n===null||n.some(o=>bt(r,o))))throw new l(`${e} ${r} is outside the allowed directories: ${n.join(", ")}. Move it under one of them, or add its folder to ${Si} or the client's workspace roots.`)}function rr(t){if(tr(t,"Output"),dn==="pending"&&go().length===0&&!bt(t,Pe()))throw new l(`Output ${t} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. Retry the call in a moment, or omit the path to write under SCREENCAST_HOME.`);let e=Or();if(!(e===null||e.some(r=>bt(t,r))))throw new l(`Output ${t} is outside the allowed directories: ${e.join(", ")}. Write under one of them (a relative path lands in SCREENCAST_HOME), or add the folder to ${Si} or the client's workspace roots.`)}function yc(t){if(!(Or()!==null||bt(t,Pe())))throw new l(`Refusing to replace ${t}: it is outside SCREENCAST_HOME and no allowed directories are set. Add its folder to ${Si} (or the client's workspace roots) to allow overwriting there, or write to a new path.`)}function nr(t,e,r,n=!1){if(t&&t.trim().length>0){tr(t,"Output");let o=er(e,t);if(rr(o),mx(o)){if(!n)throw new l(`Output already exists: ${o}. Pass overwrite: true to replace it, or choose a different path.`);yc(o)}return o}return Fr(e,r)}function fn(t,e){if(!t||t.trim().length===0)return;tr(t,"Output directory");let r=er(e,t);return rr(r),r}var xc={draft:{preset:"ultrafast",crf:28},standard:{preset:"veryfast",crf:23},high:{preset:"medium",crf:18}},$i=30,ki="standard";function bp(t){return!t||t.device.trim().length===0?[]:["-f","dshow","-i",`audio=${t.device}`]}function wo(t,e){if(!/^-?\d+$/.test(t.trim()))throw new l(`${e} must be an integer, got "${t}".`);return parseInt(t,10)}function wp(t){let e=t.trim();if(e===""||e.toLowerCase()==="full")return{kind:"full"};let r=e.indexOf(":");if(r===-1)throw new l(`Unrecognized target "${t}". Use full | monitor:<index> | window:<title> | region:<x>,<y>,<w>,<h>.`);let n=e.slice(0,r).toLowerCase(),o=e.slice(r+1);if(n==="monitor"){let i=wo(o,"monitor index");if(i<0)throw new l("monitor index must be >= 0.");return{kind:"monitor",index:i}}if(n==="window"){let i=o.trim();if(i==="")throw new l("window title must not be empty.");return{kind:"window",title:i}}if(n==="region"){let i=o.split(",").map(h=>h.trim());if(i.length!==4)throw new l(`region must be x,y,w,h (4 integers), got "${o}".`);let[s="",a="",c="",u=""]=i,[d,p,f,m]=[wo(s,"region x"),wo(a,"region y"),wo(c,"region w"),wo(u,"region h")];if(f<=0||m<=0)throw new l("region width and height must be positive.");return{kind:"region",x:d,y:p,w:f,h:m}}throw new l(`Unknown target kind "${n}". Use full | monitor | window | region.`)}function yp(t,e){let r=e.find(n=>n.index===t);if(!r){let n=e.map(o=>o.index).join(", ")||"none";throw new l(`monitor:${t} not found. Available monitor indexes: ${n}.`)}return r}function yo(t){if(t.length===0)return{x:0,y:0,w:0,h:0};let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,w:n-e,h:o-r}}function xp(t,e){if(e.length===0)return;let r=yo(e);if(!(t.x>=r.x&&t.y>=r.y&&t.x+t.w<=r.x+r.w&&t.y+t.h<=r.y+r.h))throw new l(`region ${t.x},${t.y},${t.w},${t.h} is outside the virtual desktop (origin ${r.x},${r.y}, size ${r.w}x${r.h}). gdigrab captures the desktop, so the rectangle must fit inside it. Adjust the offset/size, or use monitor:<index> to capture a whole display.`)}function Re(t){let e=xc[t];if(!e)throw new l(`Unknown quality preset "${t}".`);return["-c:v","libx264","-preset",e.preset,"-crf",String(e.crf),"-pix_fmt","yuv420p"]}var gx="160k";function Nr(t=gx){return["-c:a","aac",...t?["-b:a",t]:[]]}var Dr=["-movflags","+faststart"];function Se(t){let e={aac:()=>Nr(t.bitrate),copy:()=>["-c:a","copy"],none:()=>["-an"],omit:()=>[]}[t.audio]();return[...t.video??Re(t.quality??"standard"),...e,...t.faststart?Dr:[]]}function nt(t){return t-t%2}function Ei(t,e,r={}){switch(t.kind){case"full":{let n=yo(e);return r.evenSize&&e.length>0&&(n.w%2!==0||n.h%2!==0)?["-offset_x",String(n.x),"-offset_y",String(n.y),"-video_size",`${nt(n.w)}x${nt(n.h)}`,"-i","desktop"]:["-i","desktop"]}case"window":throw new l("Internal: a window target must be resolved to a region before building capture args. Call resolveCaptureTarget().");case"region":{let{w:n,h:o}=t;if(r.evenSize&&(n=nt(n),o=nt(o),n<=0||o<=0))throw new l(`region ${t.w}x${t.h} is too small to record: width and height must each be at least 2px (the video encoder needs even dimensions). Use a larger region, or take a screenshot instead.`);return["-offset_x",String(t.x),"-offset_y",String(t.y),"-video_size",`${n}x${o}`,"-i","desktop"]}case"monitor":{let n=yp(t.index,e),o=r.evenSize?nt(n.width):n.width,i=r.evenSize?nt(n.height):n.height;return["-offset_x",String(n.x),"-offset_y",String(n.y),"-video_size",`${o}x${i}`,"-i","desktop"]}}}function bx(t){if(t.trim().length===0)throw new l("webcam device must not be empty.");return["-f","dshow","-use_wallclock_as_timestamps","1","-rtbufsize","256M","-i",`video=${t}`]}var Sc=3600;function Sp(t,e=process.env){if(t!==void 0)return vp(t);let r=e.SCREENCAST_MAX_RECORDING_SEC;if(r!==void 0&&r.trim()!==""){let n=Number(r);if(!Number.isInteger(n)||n<0||n>It)throw new l(`SCREENCAST_MAX_RECORDING_SEC must be an integer from 0 (no cap) to ${It} (7 days), got "${r}".`);return n}return Sc}var It=168*3600;function vp(t){if(!Number.isInteger(t)||t<0||t>It)throw new l(`maxDurationSec must be an integer from 0 (no cap) to ${It} (7 days).`);return t}function wx(t){if(!Number.isInteger(t)||t<1||t>120)throw new l("fps must be an integer between 1 and 120.");return t}function vi(t){return["-g",String(Math.max(1,Math.round(t*2)))]}var gp=["-movflags","+frag_keyframe+empty_moov+default_base_moof"];function _i(t,e){let r=wx(e.fps??$i),n=e.quality??ki,o=e.monitors??[],i=vp(e.maxDurationSec??0),s=i>0?["-t",String(i)]:[],a=e.webcam,c=e.audio?2:1;return["-y",...e.videoInput??["-f","gdigrab","-framerate",String(r),...e.drawMouse===!1?["-draw_mouse","0"]:[],...Ei(t,o,{evenSize:!0})],...bp(e.audio),...a?bx(a.device):[],...a?["-map","0:v",...e.audio?["-map","1:a"]:[]]:[],...!e.videoInput&&t.kind==="full"&&o.length===0?["-vf","crop=trunc(iw/2)*2:trunc(ih/2)*2"]:[],...e.videoCodec??Re(n),...vi(r),...e.audio?Nr():[],...gp,...s,e.output,...a?["-map",`${c}:v`,...a.codec??Re(n),...vi(r),...gp,...s,a.output]:[]]}var yx=30;function $p(t,e){if(!Number.isSafeInteger(t)||t<=0)throw new l("Invalid window handle.");return["-y","-v","error","-filter_complex",`gfxcapture=hwnd=${t}:max_framerate=30,hwdownload,format=bgra`,"-frames:v","1",...Te(e)]}function Ti(t,e,r=[]){return["-y","-f","gdigrab","-framerate",String(yx),...Ei(t,r),"-frames:v","1",...Te(e)]}function Ri(t,e){switch(t.kind){case"region":return{x:t.x,y:t.y,w:nt(t.w),h:nt(t.h)};case"monitor":{let r=yp(t.index,e);return{x:r.x,y:r.y,w:nt(r.width),h:nt(r.height)}}case"full":{let r=yo(e);return{x:r.x,y:r.y,w:nt(r.w),h:nt(r.h)}}case"window":throw new l("Internal: resolve a window target to a region first.")}}function vc(t){if(!/^[a-z]+$/.test(t))throw new l(`Invalid transition "${t}". Use a lowercase xfade name such as fade, dissolve, wipeleft, wiperight, slideup, or circleopen.`);return t}function or(t,e){if(t%2!==0)throw new l(`${e} must be even, got ${t}: H.264 output with yuv420p cannot encode odd dimensions. Use ${t-1} or ${t+1}.`);return t}var xx=/[:,;=[\]'"\\\s]/;function Be(t,e="color"){if(t.length===0||xx.test(t))throw new l(`Invalid ${e} "${t}". Use a color name (black, white, red), a hex value (#RRGGBB or #RRGGBBAA), or name@alpha (e.g. white@0.5).`);return t}import{z as Lr}from"zod";var gn="standard";function $c(t){if(t===void 0)return null;let e=Number(t);return Number.isFinite(e)?e:null}function kp(t){if(!t)return null;let[e,r]=t.split("/"),n=Number(e),o=r===void 0?1:Number(r);return!Number.isFinite(n)||!Number.isFinite(o)||o===0||n===0?null:Math.round(n/o*1e3)/1e3}function Sx(t){let r=t?.side_data_list?.find(o=>o.rotation!==void 0)?.rotation??t?.tags?.rotate,n=r===void 0?NaN:Number(r);return Number.isFinite(n)?Math.round(n)%360:null}function Br(t){let e=t.streams??[],r=e.find(u=>u.codec_type==="video"),n=e.find(u=>u.codec_type==="audio"),o=t.format?.duration,i=t.format?.size,s=o!==void 0?Number(o):null,a=Sx(r),c=a!==null&&Math.abs(a)%180===90;return{durationSec:s,videoDurationSec:r?$c(r.duration)??s:null,width:(c?r?.height:r?.width)??null,height:(c?r?.width:r?.height)??null,...a?{rotation:a}:{},fps:kp(r?.avg_frame_rate)??kp(r?.r_frame_rate),videoCodec:r?.codec_name??null,audioCodec:n?.codec_name??null,format:t.format?.format_name??null,sizeBytes:i!==void 0?Number(i):null,pixFmt:r?.pix_fmt??null,videoFrames:$c(r?.nb_frames),sampleRate:$c(n?.sample_rate),channels:n?.channels??null}}function Wr(t){return["-v","quiet","-print_format","json","-show_format","-show_streams",t]}function kc(t,e){if(!Number.isFinite(t)||t<=0)throw new l(`${e} must be a positive number.`);return t}var Mi=100,Ec=1e3;function Ci(t,e,r){if(kc(e,"fps"),t===null||!(t>0))return{fps:e,requestedFrames:null,clamped:!1};let n=Math.ceil(t*e);return n<=r?{fps:e,requestedFrames:n,clamped:!1}:{fps:Math.max(1e-4,Math.floor(r/t*1e4)/1e4),requestedFrames:n,clamped:!0}}function _p(t,e){for(let r of t)if(/^frame_\d+\.png$/i.test(r))return`frame_${e}_`;return"frame_"}function Pi(t,e,r,n=Mi,o=!1,i){kc(e,"fps");let s=o?`fps=${e},mpdecimate`:`fps=${e}`;return["-y",...i?["-ss",String(i.start),...i.duration!==void 0?["-t",String(i.duration)]:[]]:[],"-i",t,"-vf",s,...o?["-fps_mode","vfr"]:[],"-frames:v",String(n),r]}var wt=.1;function ir(t,e=wt){if(!Number.isFinite(e)||e<=0||e>=1)throw new l("sceneThreshold must be between 0 and 1 (exclusive).");return["-v","error","-i",t,"-an","-vf",`scale=320:-2,select='gt(scene\\,${e})',metadata=print:file=-`,"-f","null","-"]}function sr(t){let e=[],r=null;for(let n of t.split(/\r?\n/)){let o=n.match(/pts_time:\s*(-?[\d.]+)/);if(o){r=Number(o[1]);continue}let i=n.match(/lavfi\.scene_score=([\d.]+)/);i&&r!==null&&(e.push({timeSec:r,score:Number(i[1])}),r=null)}return e}function bn(t,e){return[0,...[...t].filter(n=>n.timeSec>0).sort((n,o)=>o.score-n.score).slice(0,Math.max(0,e-1)).map(n=>n.timeSec)].sort((n,o)=>n-o)}function wn(t,e,r){if(!Number.isFinite(e)||e<0)throw new l("timestamp must be a non-negative number.");return["-y","-ss",String(e),"-i",t,"-frames:v","1",...Te(r)]}function Z(t,e={}){let r=Ai(t).toLowerCase();return r===".mp4"||r===".mkv"||r===".mov"||e.audio&&Tp.has(r)?r:".mp4"}var Tp=new Set([".wav",".mp3",".m4a"]);function Ii(t){return Tp.has(Ai(t).toLowerCase())}function jr(t){if(t===void 0)return;let e=Ai(t).toLowerCase();if(e===".webm"||e===".gif")throw new l(`This tool writes H.264/AAC, which a ${e} file cannot hold. Use an .mp4, .mkv or .mov output, then convert (format: "webm") or export_gif the result.`)}function Rp(t,e,r){let n=r.start;if(!Number.isFinite(n)||n<0)throw new l("start must be a non-negative number.");if(r.end===void 0&&r.duration===void 0)throw new l("trim requires either end or duration.");if(r.end!==void 0&&r.duration!==void 0)throw new l("trim takes end OR duration, not both.");let o=["-y","-ss",String(n),"-i",t];if(r.end!==void 0){if(r.end<=n)throw new l("end must be greater than start.");o.push("-t",String(Math.round((r.end-n)*1e3)/1e3))}else o.push("-t",String(kc(r.duration,"duration")));return r.exact===!1?o.push("-c","copy",e):o.push(...Se({quality:gn,audio:"aac",bitrate:null}),e),o}function xo(t){return t.map(e=>`file '${e.replace(/'/g,"'\\''")}'`).join(`
147
147
  `)+`
148
- `}function Tp(t){if(t.length<2)throw new l("concat requires at least two input files.");return yo(t)}function hn(t,e,r={}){return["-y",...r.quiet?["-v","error"]:[],"-f","concat","-safe","0","-i",t,"-c","copy",e]}function px(t){let{videoFrames:e,videoDurationSec:r,fps:n}=t;return e===null||r===null||n===null?!1:e>r*n*1.05+2}function Ap(t,e){let r=[["videoCodec","video codec"],["width","width"],["height","height"],["pixFmt","pixel format"],["fps","frame rate"],["audioCodec","audio codec"],["sampleRate","audio sample rate"],["channels","audio channels"]],n=e[0];for(let[o,i]of e.entries()){if(px(i))return`${t[o]} holds hidden frames behind an edit list`;if(!(o===0||!n)){for(let[s,a]of r)if(i[s]!==n[s])return`${a} differs: ${t[0]} has ${n[s]??"none"}, ${t[o]} has ${i[s]??"none"}`}}return null}function Rp(t,e,r,n={}){switch(r){case"gif":{let o=n.fps??12,i=n.width??720,s=`fps=${o},scale='min(${i},iw)':-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse`;return["-y","-i",t,"-vf",s,e]}case"webm":return["-y","-i",t,"-c:v","libvpx-vp9","-b:v","0","-crf","30","-deadline","good","-cpu-used","4","-row-mt","1",e];case"mp4":return["-y","-i",t,...Se({quality:"standard",audio:"omit",faststart:!0}),e];default:throw new l(`Unsupported convert format "${r}".`)}}function pn(t,e){if(!Number.isInteger(t)||t<0)throw new l(`${e} must be a non-negative integer.`);return t}function Pt(t,e){if(!Number.isInteger(t)||t<=0)throw new l(`${e} must be a positive integer.`);return t}function Ii(t,e){if(t!==void 0&&e!==void 0){if(e<=t)throw new l("end must be greater than start.");return`between(t,${t},${e})`}return t!==void 0?`gte(t,${t})`:e!==void 0?`lte(t,${e})`:""}function Ec(t,e){let r=pn(t.x,"crop x"),n=pn(t.y,"crop y"),o=tr(Pt(t.width,"crop width"),"crop width"),i=tr(Pt(t.height,"crop height"),"crop height");if(e&&e.width!=null&&e.height!=null&&(r+o>e.width||n+i>e.height))throw new l(`crop region ${o}x${i}+${r}+${n} falls outside the ${e.width}x${e.height} frame.`);return`crop=${o}:${i}:${r}:${n}`}function Mp(t,e,r,n,o=dn){return["-y","-i",t,"-vf",Ec(r,n),...Se({quality:o,audio:"copy"}),e]}function _c(t){if(t.width===void 0&&t.height===void 0)throw new l("scale requires width or height (or both).");return t.width!==void 0&&tr(Pt(t.width,"scale width"),"scale width"),t.height!==void 0&&tr(Pt(t.height,"scale height"),"scale height"),`scale=${t.width??-2}:${t.height??-2}`}function Cp(t,e,r){let n=o=>Math.max(2,Math.round(o/2)*2);return r.width!==void 0&&r.height!==void 0?{width:r.width,height:r.height}:r.width!==void 0?{width:r.width,height:n(e*r.width/t)}:{width:n(t*r.height/e),height:r.height}}function Pp(t,e,r,n=dn){return["-y","-i",t,"-vf",_c(r),...Se({quality:n,audio:"copy"}),e]}function Tc(t){let e=t,r=[];for(;e>2;)r.push("atempo=2.0"),e/=2;for(;e<.5;)r.push("atempo=0.5"),e/=.5;return r.push(`atempo=${Number(e.toFixed(6))}`),r.join(",")}function Ip(t,e,r,n,o=dn){if(!Number.isFinite(r)||r<=0)throw new l("speed factor must be a positive number.");let i=["-y","-i",t,"-filter:v",`setpts=PTS/${r}`];return n&&i.push("-filter:a",Tc(r)),i.push(...Se({quality:o,audio:n?"aac":"none",bitrate:null}),e),i}var dx="crop='min(iw,ih)':'min(iw,ih)',format=yuva420p,geq=lum='p(X,Y)':cb='p(X,Y)':cr='p(X,Y)':a='if(lte(hypot(X-W/2,Y-H/2),W/2),255,0)'";function Fp(t,e,r,n,o=dn){let i=pn(n.x,"overlay x"),s=pn(n.y,"overlay y"),a=Ii(n.start,n.end),c=a?`:enable='${a}'`:"",d=`[1:v]${`setpts=PTS-STARTPTS+${n.start??0}/TB`}`;if(n.scale&&(n.scale.width!==void 0||n.scale.height!==void 0)){n.scale.width!==void 0&&Pt(n.scale.width,"overlay scale width"),n.scale.height!==void 0&&Pt(n.scale.height,"overlay scale height");let m=n.scale.width??-1,h=n.scale.height??-1;d+=`,scale=${m}:${h}`}n.shape==="circle"&&(d+=`,${dx}`);let p=`${d}[ovl];[0:v][ovl]overlay=${i}:${s}${c}[v]`,f=n.durationSec;return["-y","-i",t,"-i",e,"-filter_complex",p,"-map","[v]","-map","0:a?",...Se({quality:o,audio:"copy"}),...f!=null&&f>0?["-t",String(f)]:[],r]}var mx={light:23,medium:28,heavy:32};function Op(t,e,r={}){let n=r.level??"medium",o=mx[n];if(o===void 0)throw new l(`Unknown compress level "${n}".`);let i=["-y","-i",t];return r.maxWidth!==void 0&&(Pt(r.maxWidth,"maxWidth"),i.push("-vf",`scale='trunc(min(${r.maxWidth},iw)/2)*2':-2`)),i.push(...Se({video:["-c:v","libx264","-preset","slow","-crf",String(o),"-pix_fmt","yuv420p"],audio:"aac",bitrate:"128k",faststart:!0}),e),i}var fx={mp3:["-c:a","libmp3lame","-q:a","2"],aac:Cr("192k"),wav:["-c:a","pcm_s16le"],copy:["-c:a","copy"]};function Np(t){switch(t){case"aac":case"alac":return"m4a";case"mp3":return"mp3";case"opus":case"vorbis":return"ogg";case"flac":return"flac";default:return t&&t.startsWith("pcm_")?"wav":"mka"}}function Dp(t,e,r){let n=fx[r];if(!n)throw new l(`Unknown audio format "${r}".`);return["-y","-i",t,"-vn",...n,e]}function Lp(t,e,r,n=dn){if(!Number.isFinite(r.start)||r.start<0)throw new l("clip start must be a non-negative number.");if(!Number.isFinite(r.end)||r.end<=r.start)throw new l("clip end must be greater than start.");return["-y","-ss",String(r.start),"-i",t,"-t",String(r.end-r.start),...Se({quality:n,audio:"aac",bitrate:null}),e]}var Fi=["box","blur","pixelate"];function hx(t,e,r){return t.map((n,o)=>{let i=pn(n.x,`region[${o}] x`),s=pn(n.y,`region[${o}] y`),a=Pt(n.width,`region[${o}] width`),c=Pt(n.height,`region[${o}] height`);if(r&&r.width!=null&&r.height!=null&&(i+a>r.width||s+c>r.height))throw new l(`region[${o}] ${a}x${c}+${i}+${s} falls outside the ${r.width}x${r.height} frame.`);let u=Math.max(0,i-e),d=Math.max(0,s-e),p=i+a+e,f=s+c+e;return r&&r.width!=null&&(p=Math.min(p,r.width)),r&&r.height!=null&&(f=Math.min(f,r.height)),{x:u,y:d,w:p-u,h:f-d,enable:Ii(n.start,n.end)}})}var gx=8,$p=3,bx=16;function wx(t){let e=Math.min(t.w,t.h),r=i=>Math.max(0,Math.floor((i-1)/2)),n=Math.min(r(e),Math.max(gx,Math.min(20,Math.floor(e/4)))),o=Math.min(n,r(Math.ceil(e/2)));return`lr=${n}:lp=${$p}:cr=${o}:cp=${$p}`}function yx(t){let e=Math.max(bx,Math.ceil(Math.max(t.w,t.h)/16)),r=Math.max(1,Math.round(t.w/e)),n=Math.max(1,Math.round(t.h/e));return`scale=${r}:${n}:flags=area,scale=${t.w}:${t.h}:flags=neighbor`}function Ac(t,e,r,n,o){if(t.length===0)throw new l("redact_region requires at least one region.");let i=e.style??"box",s=e.pad??0;if(!Number.isInteger(s)||s<0)throw new l("pad must be a non-negative integer.");let a=De(e.color??"black","color"),c=hx(t,s,r);if(i==="box"){let m=c.map(h=>{let b=h.enable?`:enable='${h.enable}'`:"";return`drawbox=x=${h.x}:y=${h.y}:w=${h.w}:h=${h.h}:color=${a}:t=fill${b}`}).join(",");return{steps:[`${n}${m}[${o}out]`],out:`[${o}out]`}}let u=c.length,d=[],p=[`${o}base`,...c.map((m,h)=>`${o}s${h}`)];d.push(`${n}split=${u+1}[${p.join("][")}]`),c.forEach((m,h)=>{let b=`crop=${m.w}:${m.h}:${m.x}:${m.y}`,w=i==="blur"?`boxblur=${wx(m)}`:yx(m);d.push(`[${o}s${h}]${b},${w}[${o}b${h}]`)});let f=`${o}base`;return c.forEach((m,h)=>{let b=m.enable?`:enable='${m.enable}'`:"",w=h===u-1?`${o}out`:`${o}c${h}`;d.push(`[${f}][${o}b${h}]overlay=${m.x}:${m.y}${b}[${w}]`),f=`${o}c${h}`}),{steps:d,out:`[${o}out]`}}function Oi(t,e){if(!bc(t))return Nr(e),{still:!1,ext:V(t)};if(e&&!bc(e))throw new l("An image input writes an image: give the output a .png or .jpg extension.");return{still:!0,ext:/\.jpe?g$/i.test(t)?Ai(t).toLowerCase():".png"}}function Bp(t,e,r,n={},o,i=!1){let s=i?r.map(({start:d,end:p,...f})=>f):r,{steps:a,out:c}=Ac(s,n,o,"[0:v]","");if(i)return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-frames:v","1",...Ee(e)];let[u]=a;if((n.style??"box")==="box"&&u!==void 0){let d=u.slice(5,-c.length);return["-y","-i",t,"-vf",d,...Se({quality:"high",audio:"copy"}),e]}return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...Se({quality:"high",audio:"copy"}),e]}var gn=Ir.object({x:Ir.number().int().nonnegative(),y:Ir.number().int().nonnegative(),width:Ir.number().int().positive(),height:Ir.number().int().positive(),start:Ir.number().nonnegative().optional(),end:Ir.number().positive().optional()});var xx="screencast-mcp",Wp=new Set;function jp(t){Wp.add(t)}function or(t,e,r={}){for(let n of Wp)n.isConnected()&&n.sendLoggingMessage({level:t,logger:xx,data:{message:e,...r}}).catch(()=>{})}var Up=/^\s*(?:frame|size)=/,Sx=/\b(?:warning|deprecated|dropp(?:ed|ing)|too full|discard\w*|non[- ]?monoton\w*|past duration|could not|cannot|failed|invalid|corrupt\w*|missing|error)\b/i,vx=/^\s*configuration:|deprecated pixel format used/i,zp=20;function Hp(t){return!Up.test(t)&&Sx.test(t)&&!vx.test(t)}function $x(t){let e=new Set;for(let r of t.split(/[\r\n]+/)){let n=r.trim();if(n&&Hp(n)&&e.add(n),e.size>=zp)break}return[...e]}function Gp(t,e={}){let r=$x(t);r.length>0&&or("warning","ffmpeg reported warnings.",{...e,warnings:r})}var kx=1e4,Ni=class{constructor(e,r=or,n=Date.now){this.data=e;this.send=r;this.now=n}data;send;now;partial="";seen=new Set;dropped=0;lastDropReport=-1/0;feed(e){let r=(this.partial+e).split(/[\r\n]/);this.partial=r.pop()??"";for(let n of r)this.line(n.trim())}line(e){if(e){if(Up.test(e)){let r=Number(/\bdrop=\s*(\d+)/.exec(e)?.[1]??0);r>this.dropped&&this.now()-this.lastDropReport>=kx&&(this.lastDropReport=this.now(),this.dropped=r,this.send("warning",`The recording has dropped ${r} frame(s) so far.`,{...this.data(),dropped:r}));return}!Hp(e)||this.seen.has(e)||this.seen.size>=zp||(this.seen.add(e),this.send("warning",e,{...this.data(),source:"ffmpeg"}))}}};var Mx="ffmpeg and ffprobe must be installed and on PATH (or set FFMPEG_PATH / FFPROBE_PATH). Windows: `winget install Gyan.FFmpeg` or `choco install ffmpeg`. macOS: `brew install ffmpeg`. Linux: `apt install ffmpeg`.";function Xp(t,e){let r=process.env[t]?.trim();return r||e}function Jp(t){try{return Li(t,["-version"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Rc(){let t=Xp("FFMPEG_PATH","ffmpeg"),e=Xp("FFPROBE_PATH","ffprobe"),r=[];if(Jp(t)||r.push("ffmpeg"),Jp(e)||r.push("ffprobe"),r.length>0)throw new l(`Required ${r.join(" and ")} not found on PATH.`,Mx);return{ffmpeg:t,ffprobe:e}}var Di=null;function k(){return Di||(Di=Rc(),Di)}var bn=null;function ir(){if(bn!==null)return bn;if(process.platform!=="win32")return bn=!1;try{let t=Li(k().ffmpeg,["-hide_banner","-h","filter=gfxcapture"],{encoding:"utf8",windowsHide:!0,timeout:1e4});bn=/gfxcapture AVOptions/.test(t.stdout??"")}catch{bn=!1}return bn}var Yp=new Map;function Ye(t){let e=Yp.get(t);if(e!==void 0)return e;let r;try{let n=Li(k().ffmpeg,["-hide_banner","-h",`filter=${t}`],{encoding:"utf8",windowsHide:!0,timeout:1e4});r=new RegExp(`^Filter ${t}\\b`,"m").test(n.stdout??"")}catch{r=!1}return Yp.set(t,r),r}var Vp=["ignore","pipe","pipe"],So=class extends l{};function ne(t,e,r=300*1e3,n={}){return new Promise((o,i)=>{let s=Kp(t,e,{windowsHide:!0,stdio:Vp}),a="",c="",u=null,d,p=g=>{u||(u=g,s.kill("SIGKILL"),d=setTimeout(()=>i(g),5e3))},f=()=>p(new l(`${t} was cancelled.`)),m=setTimeout(()=>p(new l(`${t} timed out after ${Math.round(r/1e3)}s.`)),r),h,b=()=>{if(!n.stallMs)return;clearTimeout(h);let g=n.progressed?"made no progress":"wrote nothing";h=setTimeout(()=>p(new So(`${t} ${g} for ${Math.round(n.stallMs/1e3)}s and was stopped.`)),n.stallMs)};b();let w=()=>{clearTimeout(m),clearTimeout(h),clearTimeout(d),n.signal?.removeEventListener("abort",f)};n.signal?.aborted?f():n.signal?.addEventListener("abort",f,{once:!0}),s.stdout?.on("data",g=>{let y=g.toString();(!n.progressed||n.progressed(y))&&b(),a+=y,n.onStdout?.(y)}),s.stderr?.on("data",g=>{n.progressed||b(),c+=g.toString()}),s.on("error",g=>{w(),i(g)}),s.on("close",g=>{w(),u?i(u):o({code:g,stdout:a,stderr:c})})})}var Cx=new Set(["-vf","-af","-filter_complex","-lavfi","-filter:v","-filter:a"]),Px=8e3,Ix={"-vf":"-filter_script:v","-filter:v":"-filter_script:v","-af":"-filter_script:a","-filter:a":"-filter_script:a","-filter_complex":"-filter_complex_script","-lavfi":"-filter_complex_script"},xo=null;function Fx(){if(xo!==null)return xo;try{let t=Li(k().ffmpeg,["-hide_banner","-version"],{encoding:"utf8",windowsHide:!0,timeout:1e4}),e=/^\s*libavutil\s+(\d+)\./m.exec(t.stdout??"");xo=e?.[1]===void 0||Number(e[1])>=59}catch{xo=!0}return xo}function Bi(t,e){let r=null,n=[...t];for(let[i,s]of t.entries()){let a=t[i-1];if(a===void 0||!Cx.has(a)||s.length<=Px)continue;r??=_x(qp(Rx(),"screencast-filter-"));let c=qp(r,`filter${i}.txt`);Ax(c,s),e??=Fx(),n[i-1]=e?`-/${a.slice(1)}`:Ix[a]??a,n[i]=c}let o=r;return{args:n,cleanup:()=>o&&Tx(o,{recursive:!0,force:!0})}}async function Dr(t,e=3e4,r={}){let n=[];return await Qp(t,e,o=>n.push(o),r),Buffer.concat(n)}async function Wi(t,e,r,n=3e4,o={}){if(!(e>0))throw new l("frameBytes must be positive.");let i=Buffer.alloc(0),s=0;return await Qp(t,n,a=>{i=i.length?Buffer.concat([i,a]):a;let c=0;for(;c+e<=i.length;c+=e)r(Buffer.from(i.subarray(c,c+e))),s++;i=i.subarray(c)},o),s}function Qp(t,e,r,n){let{ffmpeg:o}=k(),{args:i,cleanup:s}=Bi(t);return new Promise((a,c)=>{let u=Kp(o,i,{windowsHide:!0,stdio:Vp}),d="",p=null,f,m=g=>{p||(p=g,u.kill("SIGKILL"),f=setTimeout(()=>c(g),5e3))},h=()=>m(new l("ffmpeg was cancelled.")),b=setTimeout(()=>m(new l(`ffmpeg timed out after ${Math.round(e/1e3)}s.`)),e),w=()=>{clearTimeout(b),clearTimeout(f),n.signal?.removeEventListener("abort",h)};n.signal?.aborted?h():n.signal?.addEventListener("abort",h,{once:!0}),u.stdout?.on("data",g=>{if(!p)try{r(g)}catch(y){m(y)}}),u.stderr?.on("data",g=>d+=g.toString()),u.on("error",g=>{w(),c(g)}),u.on("close",g=>{w(),p?c(p):g===0?a():c(new l(`ffmpeg failed (exit ${g}):
148
+ `}function Ap(t){if(t.length<2)throw new l("concat requires at least two input files.");return xo(t)}function yn(t,e,r={}){return["-y",...r.quiet?["-v","error"]:[],"-f","concat","-safe","0","-i",t,"-c","copy",e]}function vx(t){let{videoFrames:e,videoDurationSec:r,fps:n}=t;return e===null||r===null||n===null?!1:e>r*n*1.05+2}function Mp(t,e){let r=[["videoCodec","video codec"],["width","width"],["height","height"],["pixFmt","pixel format"],["fps","frame rate"],["audioCodec","audio codec"],["sampleRate","audio sample rate"],["channels","audio channels"]],n=e[0];for(let[o,i]of e.entries()){if(vx(i))return`${t[o]} holds hidden frames behind an edit list`;if(!(o===0||!n)){for(let[s,a]of r)if(i[s]!==n[s])return`${a} differs: ${t[0]} has ${n[s]??"none"}, ${t[o]} has ${i[s]??"none"}`}}return null}function Cp(t,e,r,n={}){switch(r){case"gif":{let o=n.fps??12,i=n.width??720,s=`fps=${o},scale='min(${i},iw)':-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse`;return["-y","-i",t,"-vf",s,e]}case"webm":return["-y","-i",t,"-c:v","libvpx-vp9","-b:v","0","-crf","30","-deadline","good","-cpu-used","4","-row-mt","1",e];case"mp4":return["-y","-i",t,...Se({quality:"standard",audio:"omit",faststart:!0}),e];default:throw new l(`Unsupported convert format "${r}".`)}}function hn(t,e){if(!Number.isInteger(t)||t<0)throw new l(`${e} must be a non-negative integer.`);return t}function Ft(t,e){if(!Number.isInteger(t)||t<=0)throw new l(`${e} must be a positive integer.`);return t}function Fi(t,e){if(t!==void 0&&e!==void 0){if(e<=t)throw new l("end must be greater than start.");return`between(t,${t},${e})`}return t!==void 0?`gte(t,${t})`:e!==void 0?`lte(t,${e})`:""}function _c(t,e){let r=hn(t.x,"crop x"),n=hn(t.y,"crop y"),o=or(Ft(t.width,"crop width"),"crop width"),i=or(Ft(t.height,"crop height"),"crop height");if(e&&e.width!=null&&e.height!=null&&(r+o>e.width||n+i>e.height))throw new l(`crop region ${o}x${i}+${r}+${n} falls outside the ${e.width}x${e.height} frame.`);return`crop=${o}:${i}:${r}:${n}`}function Pp(t,e,r,n,o=gn){return["-y","-i",t,"-vf",_c(r,n),...Se({quality:o,audio:"copy"}),e]}function Tc(t){if(t.width===void 0&&t.height===void 0)throw new l("scale requires width or height (or both).");return t.width!==void 0&&or(Ft(t.width,"scale width"),"scale width"),t.height!==void 0&&or(Ft(t.height,"scale height"),"scale height"),`scale=${t.width??-2}:${t.height??-2}`}function Ip(t,e,r){let n=o=>Math.max(2,Math.round(o/2)*2);return r.width!==void 0&&r.height!==void 0?{width:r.width,height:r.height}:r.width!==void 0?{width:r.width,height:n(e*r.width/t)}:{width:n(t*r.height/e),height:r.height}}function Fp(t,e,r,n=gn){return["-y","-i",t,"-vf",Tc(r),...Se({quality:n,audio:"copy"}),e]}function Rc(t){let e=t,r=[];for(;e>2;)r.push("atempo=2.0"),e/=2;for(;e<.5;)r.push("atempo=0.5"),e/=.5;return r.push(`atempo=${Number(e.toFixed(6))}`),r.join(",")}function Op(t,e,r,n,o=gn){if(!Number.isFinite(r)||r<=0)throw new l("speed factor must be a positive number.");let i=["-y","-i",t,"-filter:v",`setpts=PTS/${r}`];return n&&i.push("-filter:a",Rc(r)),i.push(...Se({quality:o,audio:n?"aac":"none",bitrate:null}),e),i}var $x="crop='min(iw,ih)':'min(iw,ih)',format=yuva420p,geq=lum='p(X,Y)':cb='p(X,Y)':cr='p(X,Y)':a='if(lte(hypot(X-W/2,Y-H/2),W/2),255,0)'";function Np(t,e,r,n,o=gn){let i=hn(n.x,"overlay x"),s=hn(n.y,"overlay y"),a=Fi(n.start,n.end),c=a?`:enable='${a}'`:"",d=`[1:v]${`setpts=PTS-STARTPTS+${n.start??0}/TB`}`;if(n.scale&&(n.scale.width!==void 0||n.scale.height!==void 0)){n.scale.width!==void 0&&Ft(n.scale.width,"overlay scale width"),n.scale.height!==void 0&&Ft(n.scale.height,"overlay scale height");let m=n.scale.width??-1,h=n.scale.height??-1;d+=`,scale=${m}:${h}`}n.shape==="circle"&&(d+=`,${$x}`);let p=`${d}[ovl];[0:v][ovl]overlay=${i}:${s}${c}[v]`,f=n.durationSec;return["-y","-i",t,"-i",e,"-filter_complex",p,"-map","[v]","-map","0:a?",...Se({quality:o,audio:"copy"}),...f!=null&&f>0?["-t",String(f)]:[],r]}var kx={light:23,medium:28,heavy:32};function Dp(t,e,r={}){let n=r.level??"medium",o=kx[n];if(o===void 0)throw new l(`Unknown compress level "${n}".`);let i=["-y","-i",t];return r.maxWidth!==void 0&&(Ft(r.maxWidth,"maxWidth"),i.push("-vf",`scale='trunc(min(${r.maxWidth},iw)/2)*2':-2`)),i.push(...Se({video:["-c:v","libx264","-preset","slow","-crf",String(o),"-pix_fmt","yuv420p"],audio:"aac",bitrate:"128k",faststart:!0}),e),i}var Ex={mp3:["-c:a","libmp3lame","-q:a","2"],aac:Nr("192k"),wav:["-c:a","pcm_s16le"],copy:["-c:a","copy"]};function Lp(t){switch(t){case"aac":case"alac":return"m4a";case"mp3":return"mp3";case"opus":case"vorbis":return"ogg";case"flac":return"flac";default:return t&&t.startsWith("pcm_")?"wav":"mka"}}function Bp(t,e,r){let n=Ex[r];if(!n)throw new l(`Unknown audio format "${r}".`);return["-y","-i",t,"-vn",...n,e]}function Wp(t,e,r,n=gn){if(!Number.isFinite(r.start)||r.start<0)throw new l("clip start must be a non-negative number.");if(!Number.isFinite(r.end)||r.end<=r.start)throw new l("clip end must be greater than start.");return["-y","-ss",String(r.start),"-i",t,"-t",String(r.end-r.start),...Se({quality:n,audio:"aac",bitrate:null}),e]}var Oi=["box","blur","pixelate"];function _x(t,e,r){return t.map((n,o)=>{let i=hn(n.x,`region[${o}] x`),s=hn(n.y,`region[${o}] y`),a=Ft(n.width,`region[${o}] width`),c=Ft(n.height,`region[${o}] height`);if(r&&r.width!=null&&r.height!=null&&(i+a>r.width||s+c>r.height))throw new l(`region[${o}] ${a}x${c}+${i}+${s} falls outside the ${r.width}x${r.height} frame.`);let u=Math.max(0,i-e),d=Math.max(0,s-e),p=i+a+e,f=s+c+e;return r&&r.width!=null&&(p=Math.min(p,r.width)),r&&r.height!=null&&(f=Math.min(f,r.height)),{x:u,y:d,w:p-u,h:f-d,enable:Fi(n.start,n.end)}})}var Tx=8,Ep=3,Rx=16;function Ax(t){let e=Math.min(t.w,t.h),r=i=>Math.max(0,Math.floor((i-1)/2)),n=Math.min(r(e),Math.max(Tx,Math.min(20,Math.floor(e/4)))),o=Math.min(n,r(Math.ceil(e/2)));return`lr=${n}:lp=${Ep}:cr=${o}:cp=${Ep}`}function Mx(t){let e=Math.max(Rx,Math.ceil(Math.max(t.w,t.h)/16)),r=Math.max(1,Math.round(t.w/e)),n=Math.max(1,Math.round(t.h/e));return`scale=${r}:${n}:flags=area,scale=${t.w}:${t.h}:flags=neighbor`}function Ac(t,e,r,n,o){if(t.length===0)throw new l("redact_region requires at least one region.");let i=e.style??"box",s=e.pad??0;if(!Number.isInteger(s)||s<0)throw new l("pad must be a non-negative integer.");let a=Be(e.color??"black","color"),c=_x(t,s,r);if(i==="box"){let m=c.map(h=>{let b=h.enable?`:enable='${h.enable}'`:"";return`drawbox=x=${h.x}:y=${h.y}:w=${h.w}:h=${h.h}:color=${a}:t=fill${b}`}).join(",");return{steps:[`${n}${m}[${o}out]`],out:`[${o}out]`}}let u=c.length,d=[],p=[`${o}base`,...c.map((m,h)=>`${o}s${h}`)];d.push(`${n}split=${u+1}[${p.join("][")}]`),c.forEach((m,h)=>{let b=`crop=${m.w}:${m.h}:${m.x}:${m.y}`,w=i==="blur"?`boxblur=${Ax(m)}`:Mx(m);d.push(`[${o}s${h}]${b},${w}[${o}b${h}]`)});let f=`${o}base`;return c.forEach((m,h)=>{let b=m.enable?`:enable='${m.enable}'`:"",w=h===u-1?`${o}out`:`${o}c${h}`;d.push(`[${f}][${o}b${h}]overlay=${m.x}:${m.y}${b}[${w}]`),f=`${o}c${h}`}),{steps:d,out:`[${o}out]`}}function Ni(t,e){if(!wc(t))return jr(e),{still:!1,ext:Z(t)};if(e&&!wc(e))throw new l("An image input writes an image: give the output a .png or .jpg extension.");return{still:!0,ext:/\.jpe?g$/i.test(t)?Ai(t).toLowerCase():".png"}}function jp(t,e,r,n={},o,i=!1){let s=i?r.map(({start:d,end:p,...f})=>f):r,{steps:a,out:c}=Ac(s,n,o,"[0:v]","");if(i)return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-frames:v","1",...Te(e)];let[u]=a;if((n.style??"box")==="box"&&u!==void 0){let d=u.slice(5,-c.length);return["-y","-i",t,"-vf",d,...Se({quality:"high",audio:"copy"}),e]}return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...Se({quality:"high",audio:"copy"}),e]}var xn=Lr.object({x:Lr.number().int().nonnegative(),y:Lr.number().int().nonnegative(),width:Lr.number().int().positive(),height:Lr.number().int().positive(),start:Lr.number().nonnegative().optional(),end:Lr.number().positive().optional()});var Cx="screencast-mcp",Up=new Set;function zp(t){Up.add(t)}function ar(t,e,r={}){for(let n of Up)n.isConnected()&&n.sendLoggingMessage({level:t,logger:Cx,data:{message:e,...r}}).catch(()=>{})}var Hp=/^\s*(?:frame|size)=/,Px=/\b(?:warning|deprecated|dropp(?:ed|ing)|too full|discard\w*|non[- ]?monoton\w*|past duration|could not|cannot|failed|invalid|corrupt\w*|missing|error)\b/i,Ix=/^\s*configuration:|deprecated pixel format used/i,Gp=20;function qp(t){return!Hp.test(t)&&Px.test(t)&&!Ix.test(t)}function Fx(t){let e=new Set;for(let r of t.split(/[\r\n]+/)){let n=r.trim();if(n&&qp(n)&&e.add(n),e.size>=Gp)break}return[...e]}function Xp(t,e={}){let r=Fx(t);r.length>0&&ar("warning","ffmpeg reported warnings.",{...e,warnings:r})}var Ox=1e4,Di=class{constructor(e,r=ar,n=Date.now){this.data=e;this.send=r;this.now=n}data;send;now;partial="";seen=new Set;dropped=0;lastDropReport=-1/0;feed(e){let r=(this.partial+e).split(/[\r\n]/);this.partial=r.pop()??"";for(let n of r)this.line(n.trim())}line(e){if(e){if(Hp.test(e)){let r=Number(/\bdrop=\s*(\d+)/.exec(e)?.[1]??0);r>this.dropped&&this.now()-this.lastDropReport>=Ox&&(this.lastDropReport=this.now(),this.dropped=r,this.send("warning",`The recording has dropped ${r} frame(s) so far.`,{...this.data(),dropped:r}));return}!qp(e)||this.seen.has(e)||this.seen.size>=Gp||(this.seen.add(e),this.send("warning",e,{...this.data(),source:"ffmpeg"}))}}};var jx="ffmpeg and ffprobe must be installed and on PATH (or set FFMPEG_PATH / FFPROBE_PATH). Windows: `winget install Gyan.FFmpeg` or `choco install ffmpeg`. macOS: `brew install ffmpeg`. Linux: `apt install ffmpeg`.";function Yp(t,e){let r=process.env[t]?.trim();return r||e}function Kp(t){try{return Bi(t,["-version"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function Mc(){let t=Yp("FFMPEG_PATH","ffmpeg"),e=Yp("FFPROBE_PATH","ffprobe"),r=[];if(Kp(t)||r.push("ffmpeg"),Kp(e)||r.push("ffprobe"),r.length>0)throw new l(`Required ${r.join(" and ")} not found on PATH.`,jx);return{ffmpeg:t,ffprobe:e}}var Li=null;function k(){return Li||(Li=Mc(),Li)}var Sn=null;function cr(){if(Sn!==null)return Sn;if(process.platform!=="win32")return Sn=!1;try{let t=Bi(k().ffmpeg,["-hide_banner","-h","filter=gfxcapture"],{encoding:"utf8",windowsHide:!0,timeout:1e4});Sn=/gfxcapture AVOptions/.test(t.stdout??"")}catch{Sn=!1}return Sn}var Vp=new Map;function Ve(t){let e=Vp.get(t);if(e!==void 0)return e;let r;try{let n=Bi(k().ffmpeg,["-hide_banner","-h",`filter=${t}`],{encoding:"utf8",windowsHide:!0,timeout:1e4});r=new RegExp(`^Filter ${t}\\b`,"m").test(n.stdout??"")}catch{r=!1}return Vp.set(t,r),r}var Zp=["ignore","pipe","pipe"],vo=class extends l{};function se(t,e,r=300*1e3,n={}){return new Promise((o,i)=>{let s=Qp(t,e,{windowsHide:!0,stdio:Zp}),a="",c="",u=null,d,p=g=>{u||(u=g,s.kill("SIGKILL"),d=setTimeout(()=>i(g),5e3))},f=()=>p(new l(`${t} was cancelled.`)),m=setTimeout(()=>p(new l(`${t} timed out after ${Math.round(r/1e3)}s.`)),r),h,b=()=>{if(!n.stallMs)return;clearTimeout(h);let g=n.progressed?"made no progress":"wrote nothing";h=setTimeout(()=>p(new vo(`${t} ${g} for ${Math.round(n.stallMs/1e3)}s and was stopped.`)),n.stallMs)};b();let w=()=>{clearTimeout(m),clearTimeout(h),clearTimeout(d),n.signal?.removeEventListener("abort",f)};n.signal?.aborted?f():n.signal?.addEventListener("abort",f,{once:!0}),s.stdout?.on("data",g=>{let y=g.toString();(!n.progressed||n.progressed(y))&&b(),a+=y,n.onStdout?.(y)}),s.stderr?.on("data",g=>{n.progressed||b(),c+=g.toString()}),s.on("error",g=>{w(),i(g)}),s.on("close",g=>{w(),u?i(u):o({code:g,stdout:a,stderr:c})})})}var Ux=new Set(["-vf","-af","-filter_complex","-lavfi","-filter:v","-filter:a"]),zx=8e3,Hx={"-vf":"-filter_script:v","-filter:v":"-filter_script:v","-af":"-filter_script:a","-filter:a":"-filter_script:a","-filter_complex":"-filter_complex_script","-lavfi":"-filter_complex_script"},So=null;function Gx(){if(So!==null)return So;try{let t=Bi(k().ffmpeg,["-hide_banner","-version"],{encoding:"utf8",windowsHide:!0,timeout:1e4}),e=/^\s*libavutil\s+(\d+)\./m.exec(t.stdout??"");So=e?.[1]===void 0||Number(e[1])>=59}catch{So=!0}return So}function Wi(t,e){let r=null,n=[...t];for(let[i,s]of t.entries()){let a=t[i-1];if(a===void 0||!Ux.has(a)||s.length<=zx)continue;r??=Dx(Jp(Wx(),"screencast-filter-"));let c=Jp(r,`filter${i}.txt`);Bx(c,s),e??=Gx(),n[i-1]=e?`-/${a.slice(1)}`:Hx[a]??a,n[i]=c}let o=r;return{args:n,cleanup:()=>o&&Lx(o,{recursive:!0,force:!0})}}async function Ur(t,e=3e4,r={}){let n=[];return await ed(t,e,o=>n.push(o),r),Buffer.concat(n)}async function ji(t,e,r,n=3e4,o={}){if(!(e>0))throw new l("frameBytes must be positive.");let i=Buffer.alloc(0),s=0;return await ed(t,n,a=>{i=i.length?Buffer.concat([i,a]):a;let c=0;for(;c+e<=i.length;c+=e)r(Buffer.from(i.subarray(c,c+e))),s++;i=i.subarray(c)},o),s}function ed(t,e,r,n){let{ffmpeg:o}=k(),{args:i,cleanup:s}=Wi(t);return new Promise((a,c)=>{let u=Qp(o,i,{windowsHide:!0,stdio:Zp}),d="",p=null,f,m=g=>{p||(p=g,u.kill("SIGKILL"),f=setTimeout(()=>c(g),5e3))},h=()=>m(new l("ffmpeg was cancelled.")),b=setTimeout(()=>m(new l(`ffmpeg timed out after ${Math.round(e/1e3)}s.`)),e),w=()=>{clearTimeout(b),clearTimeout(f),n.signal?.removeEventListener("abort",h)};n.signal?.aborted?h():n.signal?.addEventListener("abort",h,{once:!0}),u.stdout?.on("data",g=>{if(!p)try{r(g)}catch(y){m(y)}}),u.stderr?.on("data",g=>d+=g.toString()),u.on("error",g=>{w(),c(g)}),u.on("close",g=>{w(),p?c(p):g===0?a():c(new l(`ffmpeg failed (exit ${g}):
149
149
  ${d.trim().split(`
150
150
  `).slice(-6).join(`
151
- `)}`))})}).finally(s)}async function Z(t,e,r={}){let{ffmpeg:n}=k(),o=Bi(t);try{let i=await ne(n,o.args,e,r);if(i.code!==0){let s=i.stderr.trim().split(`
151
+ `)}`))})}).finally(s)}async function te(t,e,r={}){let{ffmpeg:n}=k(),o=Wi(t);try{let i=await se(n,o.args,e,r);if(i.code!==0){let s=i.stderr.trim().split(`
152
152
  `).slice(-6).join(`
153
153
  `);throw new l(`ffmpeg failed (exit ${i.code}):
154
- ${s}`)}Gp(i.stderr)}finally{o.cleanup()}}async function se(t,e={}){if(!Ex(t))return null;try{let r=await ne(e.ffprobe??k().ffprobe,Or(t),3e4);return r.code!==0?null:Fr(JSON.parse(r.stdout)).durationSec}catch{return null}}async function L(t){let{ffprobe:e}=k(),r=await ne(e,Or(t),3e4);if(r.code!==0)throw new l(`ffprobe failed (exit ${r.code}): ${r.stderr.trim().slice(-400)}`);return Fr(JSON.parse(r.stdout))}import{basename as ed,dirname as Ox,extname as Nx,join as Dx}from"node:path";import{renameSync as Lx,rmSync as Mc}from"node:fs";var Bx="SCREENCAST_JOB_TIMEOUT_MS",Wx=10*6e4,jx=9e4,Ux=30*6e4,zx=4;function le(t,e=process.env){let r=Number(e[Bx]);return Number.isInteger(r)&&r>0?r:t==null||!(t>0)?Ux:Math.max(Wx,Math.ceil(t*zx*1e3))}function Hx(t){let e=Nx(t);return Dx(Ox(t),`${ed(t,e)}.partial${e}`)}function Gx(t,e,r){let n=t.lastIndexOf(e);if(n===-1)throw new l(`Internal error: output path ${e} is not in the ffmpeg arguments.`);let o=[...t];return o[n]=r,o}function Zp(){let t="",e=null;return r=>{t+=r;let n=t.split(/\r?\n/);t=n.pop()??"";for(let o of n){let i=o.match(/^out_time_(?:us|ms)=(\d+)$/);i&&(e=Number(i[1])/1e6)}return e}}function vo(t){let e=t?._meta?.progressToken;if(e===void 0||!t)return;let r=-1;return n=>{let o=Math.floor(Math.max(0,Math.min(1,n))*100);o<=r||(r=o,t.sendNotification({method:"notifications/progress",params:{progressToken:e,progress:o,total:100}}).catch(()=>{}))}}var Cc=new Set,td=!1;async function W(t,e){if(td)throw new l("The server is shutting down; the edit was not started.");let r=Hx(e.output),n=vo(e.extra),o=Zp(),i=e.durationSec!=null&&e.durationSec>0?e.durationSec:null,s=e.inputDurationSec!=null&&e.inputDurationSec>0?e.inputDurationSec:null,a=s!==null&&i!==null?Math.max(s,i):s??i,c=["-progress","pipe:1","-nostats",...Gx(t,e.output,r)],u=new AbortController,d=e.extra?.signal?AbortSignal.any([e.extra.signal,u.signal]):u.signal,p,f={partial:r,controller:u,done:new Promise(h=>p=h)};Cc.add(f);let m=Xx(e.output);try{let h=()=>{let b=Zp(),w=null,g=y=>{let $=b(y);return $===null||$===w?!1:(w=$,!0)};return Z(c,le(a),{signal:d,stallMs:jx,progressed:g,onStdout:y=>{if(m?.output(y.length),!n||!i)return;let $=o(y);$!==null&&(m?.progress($),n($/i))}})};try{await h()}catch(b){if(!(b instanceof So)||d.aborted)throw b;process.stderr.write(`${b.message} Retrying the edit once.
155
- `),Mc(r,{force:!0}),await h()}Lx(r,e.output),n?.(1),m?.end("done")}catch(h){throw m?.end(`failed: ${h instanceof Error?h.message.split(`
156
- `)[0]:String(h)}`),Mc(r,{force:!0}),h}finally{m?.stop(),Cc.delete(f),p()}}var qx="SCREENCAST_DEBUG_JOBS";function Xx(t){if(process.env[qx]!=="1")return;let e=ed(t),r=Date.now(),n=0,o=r,i=null,s=c=>process.stderr.write(`[job ${e}] ${((Date.now()-r)/1e3).toFixed(1)}s ${c}
157
- `);s("start");let a=setInterval(()=>s(`running: ${n} B of progress output, last ${((Date.now()-o)/1e3).toFixed(1)}s ago, out_time ${i??"none"}`),3e4);return a.unref(),{output:c=>{n+=c,o=Date.now()},progress:c=>{i=c},end:c=>s(c),stop:()=>clearInterval(a)}}async function rd(t=3e3){td=!0;let e=[...Cc];if(e.length===0)return 0;for(let n of e)n.controller.abort();let r;await Promise.race([Promise.all(e.map(n=>n.done)),new Promise(n=>r=setTimeout(n,t))]),clearTimeout(r);for(let n of e)try{Mc(n.partial,{force:!0})}catch{}return e.length}var id=.25;function bt(t){return`${t}.parts`}function sd(t,e){return e===0?t:$o(bt(t),`part-${String(e).padStart(3,"0")}.mp4`)}function Ui(t,e){return $o(bt(t),`webcam-${String(e).padStart(3,"0")}.mp4`)}function Lr(t){let e=od(t);return $o(eS(t),`${Zx(t,e)}.webcam.mp4`)}function Ic(t,e,r,n){if(e!==null&&e>0)return e;let o;try{o=Vx(t).size}catch{return null}return o<=0?null:Math.max(.001,Math.round(n-r)/1e3)}function rt(t){return t.reduce((e,r)=>e+r.durationSec,0)}function tS(t){let e=[],r=0;for(let n of t.parts)e.push({startMs:n.startMs,offsetSec:r,durationSec:n.durationSec}),r+=n.durationSec;return t.current&&e.push({startMs:t.current.startMs,offsetSec:r}),e}function zi(t,e,r){if(!t||t.parts.length===0&&!t.current)return{startMs:e,endSec:(r-e)/1e3};let n=tS(t),o=t.current?Math.max(0,(r-t.current.startMs)/1e3):0;return{startMs:n[0].startMs,endSec:rt(t.parts)+o,spans:n}}function ad(t,e){if(!t)return 0;let r=Math.floor(t-e);if(r<1)throw new l(`The recording already used its maxDurationSec cap (${t}s); nothing is left to resume.`,"Call stop_recording to finalize it.");return r}function cd(t,e){return t.status==="paused"?"it is already paused":t.status!=="recording"?`it is ${t.status}`:t.backend==="wgc"?'backend "wgc" cannot pause yet':t.replay?"a replay buffer cannot pause":!t.capture||!t.segments?.current?"it was started before pause was supported":e?null:"another server instance owns it"}function ud(t,e){return t.status==="recording"?"it is already recording":t.status!=="paused"?`it is ${t.status}`:!t.capture||!t.segments?"its capture settings are missing":e?null:"it was paused by another server instance"}var Fc=new Set;function ld(t){Fc.add(t)}function pd(t){return Fc.has(t)}function dd(t){Fc.delete(t)}var Pc=new Map;function md(t){let e=Pc.get(t);if(!e){let r;e={promise:new Promise(o=>r=o),resolve:r},Pc.set(t,e)}return e}function ko(t){return md(t).promise}function Hi(t){md(t).resolve(),setTimeout(()=>Pc.delete(t),6e4).unref?.()}var nd=t=>Math.round(t*1e3)/1e3;function rS(t,e,r){if(t.length===0)throw new l("No webcam parts to join.");let n=t.map((i,s)=>{let a=nd(Math.max(.001,i.durationSec)),c=nd(i.leadSec),u=c>0?`tpad=start_duration=${c}:start_mode=clone,`:c<0?`trim=start=${-c},setpts=PTS-STARTPTS,`:"";return`[${s}:v]${u}tpad=stop_duration=${a}:stop_mode=clone,trim=duration=${a},setpts=PTS-STARTPTS,format=yuv420p,setsar=1[w${s}]`}),o=`${t.map((i,s)=>`[w${s}]`).join("")}concat=n=${t.length}:v=1:a=0[v]`;return["-y","-v","error",...t.flatMap(i=>["-i",i.path]),"-filter_complex",`${n.join(";")};${o}`,"-map","[v]",...r,...Pr,e]}async function fd(t,e,r){let n=bt(t),o={joined:!1},i=e.filter(u=>ji(u.path)&&u.durationSec>0),s=rt(i),a=!1;if(i.length>1||i.length===1&&i[0].path!==t){Jx(n,{recursive:!0});let u=$o(n,"segments.txt"),d=$o(n,`joined${od(t)||".mp4"}`);Qx(u,yo(i.map(f=>f.path)));let p=await ne(r.ffmpeg,hn(u,d,{quiet:!0}),le(s));p.code===0&&ji(d)?(Yx(d,t),o.joined=!0):(a=!0,o.error=`Joining the ${i.length} segments failed; they are kept in ${n}: ${p.stderr.trim().split(`
158
- `).slice(-3).join(" ")}`)}let c=i.filter(u=>u.webcamPath&&ji(u.webcamPath));if(r.webcamOutput&&c.length>0){let u=rS(c.map(p=>({path:p.webcamPath,leadSec:p.webcamStartMs!==void 0?(p.webcamStartMs-p.startMs)/1e3:0,durationSec:p.durationSec})),r.webcamOutput,r.webcamCodec),d=await ne(r.ffmpeg,u,le(s));d.code===0&&ji(r.webcamOutput)?o.webcamPath=r.webcamOutput:(a=!0,o.webcamError=`Aligning the webcam failed; its raw parts are kept in ${n}: ${d.stderr.trim().split(`
159
- `).slice(-3).join(" ")}`)}return a||Kx(n,{recursive:!0,force:!0}),o}function hd(t,e,r,n){let o=d=>Math.max(2,Math.round(d/2)*2),i=o(t.width*n),s=o(i*e.height/Math.max(1,e.width)),a=Math.round(t.width*.02),c=r.endsWith("left")?a:Math.max(0,t.width-i-a),u=r.startsWith("top")?a:Math.max(0,t.height-s-a);return{x:c,y:u,width:i,height:s}}import{execFile as nS}from"node:child_process";import{randomBytes as oS}from"node:crypto";import{rmSync as iS,writeFileSync as sS}from"node:fs";import{tmpdir as aS}from"node:os";import{join as cS}from"node:path";function uS(t){let r=(Array.isArray(t)?t:t?[t]:[]).map(n=>({x:Number(n.X??0),y:Number(n.Y??0),width:Number(n.Width??0),height:Number(n.Height??0),primary:!!n.Primary,...Number(n.Dpi)>0?{dpi:Number(n.Dpi)}:{}}));return r.sort((n,o)=>n.primary!==o.primary?n.primary?-1:1:n.x!==o.x?n.x-o.x:n.y-o.y),r.map((n,o)=>({index:o,...n}))}var lS=`
154
+ ${s}`)}Xp(i.stderr)}finally{o.cleanup()}}async function ue(t,e={}){if(!Nx(t))return null;try{let r=await se(e.ffprobe??k().ffprobe,Wr(t),3e4);return r.code!==0?null:Br(JSON.parse(r.stdout)).durationSec}catch{return null}}async function W(t){let{ffprobe:e}=k(),r=await se(e,Wr(t),3e4);if(r.code!==0)throw new l(`ffprobe failed (exit ${r.code}): ${r.stderr.trim().slice(-400)}`);return Br(JSON.parse(r.stdout))}import{basename as rd,dirname as qx,extname as Xx,join as Jx}from"node:path";import{renameSync as Yx,rmSync as Cc}from"node:fs";var Kx="SCREENCAST_JOB_TIMEOUT_MS",Vx=10*6e4,Qx=9e4,Zx=30*6e4,eS=4;function pe(t,e=process.env){let r=Number(e[Kx]);return Number.isInteger(r)&&r>0?r:t==null||!(t>0)?Zx:Math.max(Vx,Math.ceil(t*eS*1e3))}function tS(t){let e=Xx(t);return Jx(qx(t),`${rd(t,e)}.partial${e}`)}function rS(t,e,r){let n=t.lastIndexOf(e);if(n===-1)throw new l(`Internal error: output path ${e} is not in the ffmpeg arguments.`);let o=[...t];return o[n]=r,o}function td(){let t="",e=null;return r=>{t+=r;let n=t.split(/\r?\n/);t=n.pop()??"";for(let o of n){let i=o.match(/^out_time_(?:us|ms)=(\d+)$/);i&&(e=Number(i[1])/1e6)}return e}}function $o(t){let e=t?._meta?.progressToken;if(e===void 0||!t)return;let r=-1;return n=>{let o=Math.floor(Math.max(0,Math.min(1,n))*100);o<=r||(r=o,t.sendNotification({method:"notifications/progress",params:{progressToken:e,progress:o,total:100}}).catch(()=>{}))}}var Pc=new Set,nd=!1;async function U(t,e){if(nd)throw new l("The server is shutting down; the edit was not started.");let r=tS(e.output),n=$o(e.extra),o=td(),i=e.durationSec!=null&&e.durationSec>0?e.durationSec:null,s=e.inputDurationSec!=null&&e.inputDurationSec>0?e.inputDurationSec:null,a=s!==null&&i!==null?Math.max(s,i):s??i,c=["-progress","pipe:1","-nostats",...rS(t,e.output,r)],u=new AbortController,d=e.extra?.signal?AbortSignal.any([e.extra.signal,u.signal]):u.signal,p,f={partial:r,controller:u,done:new Promise(h=>p=h)};Pc.add(f);let m=oS(e.output);try{let h=()=>{let b=td(),w=null,g=y=>{let v=b(y);return v===null||v===w?!1:(w=v,!0)};return te(c,pe(a),{signal:d,stallMs:Qx,progressed:g,onStdout:y=>{if(m?.output(y.length),!n||!i)return;let v=o(y);v!==null&&(m?.progress(v),n(v/i))}})};try{await h()}catch(b){if(!(b instanceof vo)||d.aborted)throw b;process.stderr.write(`${b.message} Retrying the edit once.
155
+ `),Cc(r,{force:!0}),await h()}Yx(r,e.output),n?.(1),m?.end("done")}catch(h){throw m?.end(`failed: ${h instanceof Error?h.message.split(`
156
+ `)[0]:String(h)}`),Cc(r,{force:!0}),h}finally{m?.stop(),Pc.delete(f),p()}}var nS="SCREENCAST_DEBUG_JOBS";function oS(t){if(process.env[nS]!=="1")return;let e=rd(t),r=Date.now(),n=0,o=r,i=null,s=c=>process.stderr.write(`[job ${e}] ${((Date.now()-r)/1e3).toFixed(1)}s ${c}
157
+ `);s("start");let a=setInterval(()=>s(`running: ${n} B of progress output, last ${((Date.now()-o)/1e3).toFixed(1)}s ago, out_time ${i??"none"}`),3e4);return a.unref(),{output:c=>{n+=c,o=Date.now()},progress:c=>{i=c},end:c=>s(c),stop:()=>clearInterval(a)}}async function od(t=3e3){nd=!0;let e=[...Pc];if(e.length===0)return 0;for(let n of e)n.controller.abort();let r;await Promise.race([Promise.all(e.map(n=>n.done)),new Promise(n=>r=setTimeout(n,t))]),clearTimeout(r);for(let n of e)try{Cc(n.partial,{force:!0})}catch{}return e.length}var ad=.25;function yt(t){return`${t}.parts`}function cd(t,e){return e===0?t:ko(yt(t),`part-${String(e).padStart(3,"0")}.mp4`)}function zi(t,e){return ko(yt(t),`webcam-${String(e).padStart(3,"0")}.mp4`)}function zr(t){let e=sd(t);return ko(pS(t),`${lS(t,e)}.webcam.mp4`)}function Fc(t,e,r,n){if(e!==null&&e>0)return e;let o;try{o=cS(t).size}catch{return null}return o<=0?null:Math.max(.001,Math.round(n-r)/1e3)}function ot(t){return t.reduce((e,r)=>e+r.durationSec,0)}function dS(t){let e=[],r=0;for(let n of t.parts)e.push({startMs:n.startMs,offsetSec:r,durationSec:n.durationSec}),r+=n.durationSec;return t.current&&e.push({startMs:t.current.startMs,offsetSec:r}),e}function Hi(t,e,r){if(!t||t.parts.length===0&&!t.current)return{startMs:e,endSec:(r-e)/1e3};let n=dS(t),o=t.current?Math.max(0,(r-t.current.startMs)/1e3):0;return{startMs:n[0].startMs,endSec:ot(t.parts)+o,spans:n}}function ud(t,e){if(!t)return 0;let r=Math.floor(t-e);if(r<1)throw new l(`The recording already used its maxDurationSec cap (${t}s); nothing is left to resume.`,"Call stop_recording to finalize it.");return r}function ld(t,e){return t.status==="paused"?"it is already paused":t.status!=="recording"?`it is ${t.status}`:t.backend==="wgc"?'backend "wgc" cannot pause yet':t.replay?"a replay buffer cannot pause":!t.capture||!t.segments?.current?"it was started before pause was supported":e?null:"another server instance owns it"}function pd(t,e){return t.status==="recording"?"it is already recording":t.status!=="paused"?`it is ${t.status}`:!t.capture||!t.segments?"its capture settings are missing":e?null:"it was paused by another server instance"}var Oc=new Set;function dd(t){Oc.add(t)}function md(t){return Oc.has(t)}function fd(t){Oc.delete(t)}var Ic=new Map;function hd(t){let e=Ic.get(t);if(!e){let r;e={promise:new Promise(o=>r=o),resolve:r},Ic.set(t,e)}return e}function Eo(t){return hd(t).promise}function Gi(t){hd(t).resolve(),setTimeout(()=>Ic.delete(t),6e4).unref?.()}var id=t=>Math.round(t*1e3)/1e3;function mS(t,e,r){if(t.length===0)throw new l("No webcam parts to join.");let n=t.map((i,s)=>{let a=id(Math.max(.001,i.durationSec)),c=id(i.leadSec),u=c>0?`tpad=start_duration=${c}:start_mode=clone,`:c<0?`trim=start=${-c},setpts=PTS-STARTPTS,`:"";return`[${s}:v]${u}tpad=stop_duration=${a}:stop_mode=clone,trim=duration=${a},setpts=PTS-STARTPTS,format=yuv420p,setsar=1[w${s}]`}),o=`${t.map((i,s)=>`[w${s}]`).join("")}concat=n=${t.length}:v=1:a=0[v]`;return["-y","-v","error",...t.flatMap(i=>["-i",i.path]),"-filter_complex",`${n.join(";")};${o}`,"-map","[v]",...r,...Dr,e]}async function gd(t,e,r){let n=yt(t),o={joined:!1},i=e.filter(u=>Ui(u.path)&&u.durationSec>0),s=ot(i),a=!1;if(i.length>1||i.length===1&&i[0].path!==t){iS(n,{recursive:!0});let u=ko(n,"segments.txt"),d=ko(n,`joined${sd(t)||".mp4"}`);uS(u,xo(i.map(f=>f.path)));let p=await se(r.ffmpeg,yn(u,d,{quiet:!0}),pe(s));p.code===0&&Ui(d)?(sS(d,t),o.joined=!0):(a=!0,o.error=`Joining the ${i.length} segments failed; they are kept in ${n}: ${p.stderr.trim().split(`
158
+ `).slice(-3).join(" ")}`)}let c=i.filter(u=>u.webcamPath&&Ui(u.webcamPath));if(r.webcamOutput&&c.length>0){let u=mS(c.map(p=>({path:p.webcamPath,leadSec:p.webcamStartMs!==void 0?(p.webcamStartMs-p.startMs)/1e3:0,durationSec:p.durationSec})),r.webcamOutput,r.webcamCodec),d=await se(r.ffmpeg,u,pe(s));d.code===0&&Ui(r.webcamOutput)?o.webcamPath=r.webcamOutput:(a=!0,o.webcamError=`Aligning the webcam failed; its raw parts are kept in ${n}: ${d.stderr.trim().split(`
159
+ `).slice(-3).join(" ")}`)}return a||aS(n,{recursive:!0,force:!0}),o}function bd(t,e,r,n){let o=d=>Math.max(2,Math.round(d/2)*2),i=o(t.width*n),s=o(i*e.height/Math.max(1,e.width)),a=Math.round(t.width*.02),c=r.endsWith("left")?a:Math.max(0,t.width-i-a),u=r.startsWith("top")?a:Math.max(0,t.height-s-a);return{x:c,y:u,width:i,height:s}}import{execFile as fS}from"node:child_process";import{randomBytes as hS}from"node:crypto";import{rmSync as gS,writeFileSync as bS}from"node:fs";import{tmpdir as wS}from"node:os";import{join as yS}from"node:path";function xS(t){let r=(Array.isArray(t)?t:t?[t]:[]).map(n=>({x:Number(n.X??0),y:Number(n.Y??0),width:Number(n.Width??0),height:Number(n.Height??0),primary:!!n.Primary,...Number(n.Dpi)>0?{dpi:Number(n.Dpi)}:{}}));return r.sort((n,o)=>n.primary!==o.primary?n.primary?-1:1:n.x!==o.x?n.x-o.x:n.y-o.y),r.map((n,o)=>({index:o,...n}))}var SS=`
160
160
  Add-Type @"
161
161
  using System;using System.Runtime.InteropServices;
162
162
  public class DpiShim{ [DllImport("user32.dll")] public static extern IntPtr SetProcessDpiAwarenessContext(IntPtr v);
@@ -170,9 +170,9 @@ Add-Type -AssemblyName System.Windows.Forms
170
170
  [System.Windows.Forms.Screen]::AllScreens | ForEach-Object {
171
171
  [pscustomobject]@{ X=$_.Bounds.X; Y=$_.Bounds.Y; Width=$_.Bounds.Width; Height=$_.Bounds.Height; Primary=$_.Primary; Dpi=[DpiShim]::Dpi($_.Bounds.X,$_.Bounds.Y) }
172
172
  } | ConvertTo-Json -Compress
173
- `,pS=5e3,wn=null,dS=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
174
- `,mS=2e4,bd="SCREENCAST_PS_TIMEOUT_MS";function sr(t,e=process.env){let r=Number(e[bd]);return Number.isInteger(r)&&r>0?r:t}function fS(t){return`$Payload = [IO.File]::ReadAllText([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(t,"utf8").toString("base64")}')), [Text.Encoding]::UTF8)
175
- `}function hS(t,e){let r=dS+(e===void 0?"":fS(e))+t;return["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}async function gS(t,e){let r=cS(aS(),`screencast-ps-${process.pid}-${oS(6).toString("hex")}.json`);sS(r,t,{encoding:"utf8",mode:384});try{return await e(r)}finally{iS(r,{force:!0})}}function st(t,e,r={}){return r.payload===void 0?gd(t,e,r):gS(r.payload,n=>gd(t,e,r,n))}function gd(t,e,r,n){let o=r.timeoutMs??sr(mS),i=r.command?.file??"powershell",s=r.command?.args??hS(t,n);return new Promise((a,c)=>{nS(i,s,{encoding:"utf8",windowsHide:!0,maxBuffer:8*1024*1024,timeout:o,killSignal:"SIGKILL",signal:r.signal},(u,d,p)=>{if(r.signal?.aborted)c(new l(`Cancelled while reading ${e}.`));else if(u&&u.killed)c(new l(`Timed out reading ${e} after ${o/1e3} s (PowerShell did not answer).`,`Retry; if it keeps happening, restart the app being captured or raise ${bd}.`));else if(u||!d){let f=r.failure??`Could not enumerate ${e}`;c(new l(`${f}: ${p?.trim()||u?.message||"powershell failed"}`))}else a(d)})})}async function bS(){let t=await st(lS,"monitors");try{return uS(JSON.parse(t))}catch(e){throw new l(`Could not parse monitor geometry: ${U(e)}`)}}function ar(t=Date.now()){if(process.platform!=="win32")return Promise.reject(new l("Monitor enumeration is implemented for Windows (gdigrab) only."));if(wn&&t-wn.at<pS)return wn.monitors;let e={at:t,monitors:bS()};return wn=e,e.monitors.catch(()=>{wn===e&&(wn=null)}),e.monitors}var xd=5;function Oc(t){let e=/^hwnd=(0x[0-9a-f]+|\d+)$/i.exec(t.trim());if(e)return{kind:"hwnd",hwnd:Number(e[1])};let r=/^exe=(.+)$/i.exec(t.trim());return r?.[1]?{kind:"exe",exe:r[1].trim().toLowerCase().replace(/\.exe$/,"")}:null}function Nc(t,e,r={}){let n=Array.isArray(t.windows)?t.windows:[],o=n.filter(i=>!i.cloaked);try{return wd(t,o,e,r)}catch(i){if(!(i instanceof Br)||o.length===n.length)throw i;let s;try{s=wd(t,n,e,r)}catch{throw i}if(!r.allowCloaked)throw new l(`Window "${s.matchedTitle}" is cloaked: Windows reports it as open but it is not on screen (a suspended app, or a window on another virtual desktop), so a screen capture would record whatever is there instead.`,`Bring the window up on this desktop, or use backend: "wgc", which captures the window's own surface.`);return{...s,cloaked:!0}}}var Br=class extends l{};function wd(t,e,r,n){let o=Oc(r);if(o){let p=o.kind==="hwnd"?e.filter(f=>f.hwnd===o.hwnd):e.filter(f=>(f.exe??"").toLowerCase().replace(/\.exe$/,"")===o.exe);if(p.length===0)throw new Br(o.kind==="hwnd"?`No visible top-level window with handle ${r.trim().slice(5)}. It may have closed; handles change when an app restarts.`:`No visible window belonging to ${o.exe}.exe. Is the app running with a window open (and not minimized)?`);return yd(t,p,o.kind)}let i=r.trim().toLowerCase(),s=e.filter(p=>p.title.toLowerCase()===i),a=e.filter(p=>p.title.toLowerCase().includes(i)),c=p=>p.slice(0,xd).map(f=>`"${f.title}"`).join(", ");if(s.length===0&&n.exactOnly)throw new Br(`No visible window titled exactly "${r}" (exactTitle is on).`+(a.length>0?` Windows containing it: ${c(a)}.`:""));let u=s.length>0?"exact":"substring",d=s.length>0?s:a;if(d.length===0)throw new Br(`No visible window matching title "${r}". Open the window (it must be on screen and not minimized), or use an exact/substring of its title, or target it by window:exe=<app.exe> or window:hwnd=<handle>.`);return yd(t,d,u)}function yd(t,e,r){let n=e[0];if(!n)throw new Br("No visible window matched.");if(n.minimized)throw new l(`Window "${n.title}" is minimized. Restore it before capturing - window capture grabs whatever is on screen at the window's rectangle.`);let o=t.virtual,i=Math.max(n.left,o.x),s=Math.max(n.top,o.y),a=Math.min(n.right,o.x+o.w),c=Math.min(n.bottom,o.y+o.h),u=a-i,d=c-s;if(u<=0||d<=0)throw new l(`Window "${n.title}" has no visible on-screen area to capture (off-screen or fully occluded by the desktop edge).`);if(u-=u%2,d-=d%2,u<=0||d<=0)throw new l(`Window "${n.title}" is too small to capture.`);return{x:i,y:s,width:u,height:d,matchedTitle:n.title,...n.hwnd!==void 0?{hwnd:n.hwnd}:{},...n.pid!==void 0?{pid:n.pid}:{},...n.exe!==void 0?{exe:n.exe}:{},...n.clientX!==void 0&&n.clientY!==void 0?{client:{x:n.clientX,y:n.clientY}}:{},matchCount:e.length,matchKind:r,candidates:e.slice(0,xd).map(p=>p.title)}}function cr(t){let e=[];return t.matchKind==="substring"&&e.push("the title matched only as a substring"),t.matchCount>1&&e.push(`${t.matchCount} windows matched and the topmost was used`),t.cloaked&&e.push("the window is cloaked (not on screen: suspended, or on another virtual desktop)"),{matchedWindow:t.matchedTitle,matchCount:t.matchCount,matchKind:t.matchKind,region:{x:t.x,y:t.y,width:t.width,height:t.height},...e.length>0?{windowWarning:`Check this is the intended window: ${e.join(", and ")}. Candidates: ${t.candidates.map(r=>`"${r}"`).join(", ")}. Pass the full title with exactTitle: true to match only that window.`}:{}}}var wS=`
173
+ `,vS=5e3,vn=null,$S=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
174
+ `,kS=2e4,yd="SCREENCAST_PS_TIMEOUT_MS";function ur(t,e=process.env){let r=Number(e[yd]);return Number.isInteger(r)&&r>0?r:t}function ES(t){return`$Payload = [IO.File]::ReadAllText([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(t,"utf8").toString("base64")}')), [Text.Encoding]::UTF8)
175
+ `}function _S(t,e){let r=$S+(e===void 0?"":ES(e))+t;return["-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}async function TS(t,e){let r=yS(wS(),`screencast-ps-${process.pid}-${hS(6).toString("hex")}.json`);bS(r,t,{encoding:"utf8",mode:384});try{return await e(r)}finally{gS(r,{force:!0})}}function ct(t,e,r={}){return r.payload===void 0?wd(t,e,r):TS(r.payload,n=>wd(t,e,r,n))}function wd(t,e,r,n){let o=r.timeoutMs??ur(kS),i=r.command?.file??"powershell",s=r.command?.args??_S(t,n);return new Promise((a,c)=>{fS(i,s,{encoding:"utf8",windowsHide:!0,maxBuffer:8*1024*1024,timeout:o,killSignal:"SIGKILL",signal:r.signal},(u,d,p)=>{if(r.signal?.aborted)c(new l(`Cancelled while reading ${e}.`));else if(u&&u.killed)c(new l(`Timed out reading ${e} after ${o/1e3} s (PowerShell did not answer).`,`Retry; if it keeps happening, restart the app being captured or raise ${yd}.`));else if(u||!d){let f=r.failure??`Could not enumerate ${e}`;c(new l(`${f}: ${p?.trim()||u?.message||"powershell failed"}`))}else a(d)})})}async function RS(){let t=await ct(SS,"monitors");try{return xS(JSON.parse(t))}catch(e){throw new l(`Could not parse monitor geometry: ${z(e)}`)}}function lr(t=Date.now()){if(process.platform!=="win32")return Promise.reject(new l("Monitor enumeration is implemented for Windows (gdigrab) only."));if(vn&&t-vn.at<vS)return vn.monitors;let e={at:t,monitors:RS()};return vn=e,e.monitors.catch(()=>{vn===e&&(vn=null)}),e.monitors}var vd=5;function Nc(t){let e=/^hwnd=(0x[0-9a-f]+|\d+)$/i.exec(t.trim());if(e)return{kind:"hwnd",hwnd:Number(e[1])};let r=/^exe=(.+)$/i.exec(t.trim());return r?.[1]?{kind:"exe",exe:r[1].trim().toLowerCase().replace(/\.exe$/,"")}:null}function Dc(t,e,r={}){let n=Array.isArray(t.windows)?t.windows:[],o=n.filter(i=>!i.cloaked);try{return xd(t,o,e,r)}catch(i){if(!(i instanceof Hr)||o.length===n.length)throw i;let s;try{s=xd(t,n,e,r)}catch{throw i}if(!r.allowCloaked)throw new l(`Window "${s.matchedTitle}" is cloaked: Windows reports it as open but it is not on screen (a suspended app, or a window on another virtual desktop), so a screen capture would record whatever is there instead.`,`Bring the window up on this desktop, or use backend: "wgc", which captures the window's own surface.`);return{...s,cloaked:!0}}}var Hr=class extends l{};function xd(t,e,r,n){let o=Nc(r);if(o){let p=o.kind==="hwnd"?e.filter(f=>f.hwnd===o.hwnd):e.filter(f=>(f.exe??"").toLowerCase().replace(/\.exe$/,"")===o.exe);if(p.length===0)throw new Hr(o.kind==="hwnd"?`No visible top-level window with handle ${r.trim().slice(5)}. It may have closed; handles change when an app restarts.`:`No visible window belonging to ${o.exe}.exe. Is the app running with a window open (and not minimized)?`);return Sd(t,p,o.kind)}let i=r.trim().toLowerCase(),s=e.filter(p=>p.title.toLowerCase()===i),a=e.filter(p=>p.title.toLowerCase().includes(i)),c=p=>p.slice(0,vd).map(f=>`"${f.title}"`).join(", ");if(s.length===0&&n.exactOnly)throw new Hr(`No visible window titled exactly "${r}" (exactTitle is on).`+(a.length>0?` Windows containing it: ${c(a)}.`:""));let u=s.length>0?"exact":"substring",d=s.length>0?s:a;if(d.length===0)throw new Hr(`No visible window matching title "${r}". Open the window (it must be on screen and not minimized), or use an exact/substring of its title, or target it by window:exe=<app.exe> or window:hwnd=<handle>.`);return Sd(t,d,u)}function Sd(t,e,r){let n=e[0];if(!n)throw new Hr("No visible window matched.");if(n.minimized)throw new l(`Window "${n.title}" is minimized. Restore it before capturing - window capture grabs whatever is on screen at the window's rectangle.`);let o=t.virtual,i=Math.max(n.left,o.x),s=Math.max(n.top,o.y),a=Math.min(n.right,o.x+o.w),c=Math.min(n.bottom,o.y+o.h),u=a-i,d=c-s;if(u<=0||d<=0)throw new l(`Window "${n.title}" has no visible on-screen area to capture (off-screen or fully occluded by the desktop edge).`);if(u-=u%2,d-=d%2,u<=0||d<=0)throw new l(`Window "${n.title}" is too small to capture.`);return{x:i,y:s,width:u,height:d,matchedTitle:n.title,...n.hwnd!==void 0?{hwnd:n.hwnd}:{},...n.pid!==void 0?{pid:n.pid}:{},...n.exe!==void 0?{exe:n.exe}:{},...n.clientX!==void 0&&n.clientY!==void 0?{client:{x:n.clientX,y:n.clientY}}:{},matchCount:e.length,matchKind:r,candidates:e.slice(0,vd).map(p=>p.title)}}function pr(t){let e=[];return t.matchKind==="substring"&&e.push("the title matched only as a substring"),t.matchCount>1&&e.push(`${t.matchCount} windows matched and the topmost was used`),t.cloaked&&e.push("the window is cloaked (not on screen: suspended, or on another virtual desktop)"),{matchedWindow:t.matchedTitle,matchCount:t.matchCount,matchKind:t.matchKind,region:{x:t.x,y:t.y,width:t.width,height:t.height},...e.length>0?{windowWarning:`Check this is the intended window: ${e.join(", and ")}. Candidates: ${t.candidates.map(r=>`"${r}"`).join(", ")}. Pass the full title with exactTitle: true to match only that window.`}:{}}}var AS=`
176
176
  $ErrorActionPreference='Stop'
177
177
  Add-Type @"
178
178
  using System;using System.Text;using System.Collections.Generic;using System.Runtime.InteropServices;
@@ -220,13 +220,13 @@ foreach($h in [WinShim]::Z()){
220
220
  }
221
221
  $v=[pscustomobject]@{x=[WinShim]::SM(76);y=[WinShim]::SM(77);w=[WinShim]::SM(78);h=[WinShim]::SM(79)}
222
222
  [pscustomobject]@{virtual=$v;windows=@($ws)}|ConvertTo-Json -Compress -Depth 4
223
- `;async function Dc(){if(process.platform!=="win32")throw new l("Window capture is implemented for Windows (gdigrab) only.");let t=await st(wS,"windows"),e;try{e=JSON.parse(t)}catch(i){throw new l(`Could not parse window geometry: ${U(i)}`)}let r=e,n=Array.isArray(r.windows)?r.windows:r.windows?[r.windows]:[];return{virtual:r.virtual??{x:0,y:0,w:0,h:0},windows:n}}async function Sd(t,e={}){return Nc(await Dc(),t,e)}function vd(t,e){if(t.backend==="wgc"){if(!e.windowHwnd)throw new l('backend "wgc" records one window: use a window: target.');if(!e.wgcAvailable)throw new l('backend "wgc" needs FFmpeg 8 or newer (the gfxcapture filter). Use gdigrab, or update ffmpeg.');if(t.replay)throw new l('replayBufferSec is not supported with backend "wgc" yet; use gdigrab or ddagrab.')}if(t.webcam&&(t.backend==="wgc"||t.replay))throw new l("webcam works with backend gdigrab or ddagrab, without replayBufferSec.");if((t.logs||t.perf)&&t.replay)throw new l("logs and perf are not supported with replayBufferSec yet.")}function $d(t){return(t.replayBufferSec?`Keep a rolling ${t.replayBufferSec} s replay buffer of `:"Record ")+`${t.target} `+(t.maxDurationSec>0?`for up to ${t.maxDurationSec} s`:"with no time limit")+(t.audioDevice?`, with system audio (${t.audioDevice})`:", without audio")+(t.webcamDevice?`, with the webcam (${t.webcamDevice})`:"")+(t.events?", logging mouse clicks and typing":"")+(t.focus?t.focus==="title"?" and which window is in front, with its title":" and which app is in front":"")+(t.elements?", naming the on-screen controls you click":"")+(t.hotkeys?`, with hotkeys (${mo.marker} marks, ${mo.stop} stops)`:"")+(t.replayBufferSec?", kept only until save_replay or stop_recording { save: true } writes it out?":`, saved to ${t.output}?`)}function kd(t){let e=t.replay&&t.events?.frame?{events:{raw:t.events.raw,keys:t.events.keys,startMs:t.startMs,frame:t.events.frame}}:{};return{id:t.id,target:t.target,outputPath:t.output,fps:t.fps,quality:t.quality,pid:t.pid,pidSpawnedAt:t.spawnedAt,...t.identity,status:"recording",startedAt:(t.now??new Date).toISOString(),videoStartMs:t.startMs,...t.maxDurationSec>0?{maxDurationSec:t.maxDurationSec}:{},...t.window?{matchedWindow:t.window.matchedTitle}:{},...t.events&&!t.replay?{events:{path:t.events.jsonl,keys:t.events.keys}}:{},...t.replay?{replay:{...t.replay,...e}}:{},backend:t.backend,...t.encoder!=="x264"?{encoder:t.encoder}:{},...t.capture&&t.backend!=="wgc"&&!t.replay?{capture:t.capture,segments:{parts:[],current:{path:t.output,startMs:t.startMs,...t.webcam?{webcamPath:t.webcam.rawPath,...t.webcam.startMs!==void 0?{webcamStartMs:t.webcam.startMs}:{}}:{}}}}:{},...t.webcam?{webcam:{device:t.webcam.device,path:Lr(t.output),corner:t.webcam.corner??"bottom_right",size:t.webcam.size??id,shape:t.webcam.shape??"rect"}}:{},processImage:t.processImage}}function Ed(t){let e=t.record;return{sessionId:e.id,status:"recording",backend:e.backend,outputPath:e.outputPath,pid:e.pid,fps:e.fps,quality:e.quality,audioDevice:t.audioDevice??null,maxDurationSec:t.maxDurationSec>0?t.maxDurationSec:null,encoder:t.encoder,...t.encoderNote?{encoderNote:t.encoderNote}:{},...t.gpuFrames!==void 0?{gpuFrames:t.gpuFrames}:{},...t.webcamDevice?{webcam:{device:t.webcamDevice,path:Lr(e.outputPath)}}:{},...t.window?cr(t.window):{},...t.events&&!t.replay?{eventsPath:t.events.jsonl,keys:t.events.keys}:{},...t.logs?{logsPath:t.logs.path,...t.logs.missing?{logsNote:"A log file does not exist yet; it is read from its start once it appears."}:{}}:{},...t.hotkeys?{hotkeys:{...mo,...t.hotkeys.taken.length?{unavailable:t.hotkeys.taken,warning:`Another app holds ${t.hotkeys.taken.map(r=>mo[r]).join(" and ")}.`}:{}}}:{},...t.replay?{replay:{bufferSec:t.replay.bufferSec,segmentSec:t.replay.segmentSec,dir:t.replay.dir,events:t.replay.events}}:{},note:(t.replay?`Replay buffer running: save_replay keeps the last seconds (up to ${t.replay.bufferSec}s) without stopping it; stop_recording discards the buffer unless save: true (then it writes outputPath).`:"Call stop_recording with this sessionId to finalize the file"+(e.backend==="wgc"?".":" (pause_recording/resume_recording leave stretches out)."))+(t.maxDurationSec>0?` It stops on its own after ${t.maxDurationSec}s (maxDurationSec).`:"")}}import{z as _d}from"zod";var he={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},I={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},Gi={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},Td={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1};function N(t){return _d.looseObject(t)}var Y=N({outputPath:_d.string().describe("Path of the file written.")});import{rmSync as wm,writeFileSync as sv}from"node:fs";import{createReadStream as yS,createWriteStream as xS,existsSync as qi,mkdirSync as SS,mkdtempSync as vS,readdirSync as Lc,readFileSync as $S,rmSync as Yi,statSync as kS,writeFileSync as Ad}from"node:fs";import{stat as Rd,writeFile as ES}from"node:fs/promises";import{pipeline as _S}from"node:stream/promises";import{join as Ke}from"node:path";var Pd=2,TS=3,Xi=4,yn=3600,AS="seg%05d.ts",Id=/^seg(\d{5})\.ts$/,Fd="segments.csv",RS=/^buf-[\w-]+$/,Od=60;function Nd(t){return t+Od}function Dd(){return Ke(Me(),"replay")}function MS(t,e=Pd){return Math.ceil(t/e)+TS}function Ld(t,e=Pd){if(!Number.isInteger(t)||t<Xi||t>yn)throw new l(`replayBufferSec must be an integer from ${Xi} to ${yn} seconds.`);return{dir:Ke(Dd(),`buf-${ge()}-${be(6)}`),bufferSec:t,segmentSec:e,wrap:MS(t,e)}}function Bd(t){return Ke(t,Fd)}function Wd(t,e){let r=t.slice(0,-1),n=r.indexOf("-movflags");return n>=0&&r.splice(n,2),[...r,"-force_key_frames",`expr:gte(t,n_forced*${e.segmentSec})`,"-f","segment","-segment_time",String(e.segmentSec),"-segment_wrap",String(e.wrap),"-segment_list",Bd(e.dir),"-segment_list_type","csv","-segment_list_size",String(e.wrap),"-segment_format","mpegts","-segment_format_options","flush_packets=1",un(e.dir,AS)]}function CS(t){let e=[];for(let r of t.split(/\r?\n/)){let[n="",o,i]=r.trim().split(","),s=Id.exec(n),a=Number(o),c=Number(i);!s||o===void 0||i===void 0||!Number.isFinite(a)||!Number.isFinite(c)||c<a||e.push({file:n,index:Number(s[1]),start:a,end:c})}return e.sort((r,n)=>r.start-n.start)}function PS(t,e){let r=[],n=0;for(let o=t.length-1;o>=0&&n<e;o--){let i=t[o];r.unshift(i),n+=i.end-i.start}return r}function IS(t,e){let r=t.at(-1),n=r?(r.index+1)%e:0;return`seg${String(n).padStart(5,"0")}.ts`}function FS(t,e,r){let n=r.reencode?Se({quality:r.quality??"standard",audio:r.audio?"aac":"omit"}):["-c","copy"];return["-y","-v","error","-ss",String(Eo(Math.max(0,r.startSec))),"-i",t,...n,...Pr,e]}function OS(t,e,r){return bi(t,{from:e,to:r}).map(n=>({...n,t:Eo(n.t-e)}))}var Eo=t=>Math.round(t*1e3)/1e3;async function Md(t,e,r){let n=(await Rd(t)).size;return n===0?(await ES(e,""),0):(await _S(yS(t,{start:0,end:n-1}),xS(e),{signal:r}),(await Rd(e)).size)}async function Cd(t,e,r){let n=await ne(t,["-v","error","-show_entries","format=start_time","-of","csv=p=0",e],15e3,{signal:r}),o=Number.parseFloat(n.stdout.trim());return n.code===0&&Number.isFinite(o)?o:null}async function Bc(t,e){if(!qi(t.dir))throw new l("This replay buffer has been discarded: its segments are gone.");let r=Bd(t.dir),n=qi(r)?CS($S(r,"utf8")):[],o=PS(n,e.lastSec),i=vS(Ke(t.dir,"save-"));try{let s=[];for(let[C,M]of o.entries()){let R=Ke(i,`${String(C).padStart(5,"0")}.ts`);await Md(Ke(t.dir,M.file),R,e.signal),s.push(R)}let a=!1;if(e.live!==!1){let C=Ke(t.dir,IS(n,t.wrap)),M=Ke(i,"live.ts");if(qi(C)&&await Md(C,M,e.signal)>0){let R=s.at(-1),[P,j]=await Promise.all([Cd(e.ffprobe,M,e.signal),R?Cd(e.ffprobe,R,e.signal):Promise.resolve(-1/0)]);P!==null&&j!==null&&P>j&&(s.push(M),a=!0)}}if(s.length===0)throw new l("The replay buffer has no footage yet: the first segment is still being written. Try again in a couple of seconds.");let c=Ke(i,"join.txt");Ad(c,yo(s));let u=Ke(i,"joined.mp4"),d=le(e.lastSec+2*t.segmentSec),p=await ne(e.ffmpeg,hn(c,u,{quiet:!0}),d,{signal:e.signal});if(p.code!==0)throw new l(`Joining the replay segments failed:
223
+ `;async function Lc(){if(process.platform!=="win32")throw new l("Window capture is implemented for Windows (gdigrab) only.");let t=await ct(AS,"windows"),e;try{e=JSON.parse(t)}catch(i){throw new l(`Could not parse window geometry: ${z(i)}`)}let r=e,n=Array.isArray(r.windows)?r.windows:r.windows?[r.windows]:[];return{virtual:r.virtual??{x:0,y:0,w:0,h:0},windows:n}}async function $d(t,e={}){return Dc(await Lc(),t,e)}function kd(t,e){if(t.backend==="wgc"){if(!e.windowHwnd)throw new l('backend "wgc" records one window: use a window: target.');if(!e.wgcAvailable)throw new l('backend "wgc" needs FFmpeg 8 or newer (the gfxcapture filter). Use gdigrab, or update ffmpeg.');if(t.replay)throw new l('replayBufferSec is not supported with backend "wgc" yet; use gdigrab or ddagrab.')}if(t.webcam&&(t.backend==="wgc"||t.replay))throw new l("webcam works with backend gdigrab or ddagrab, without replayBufferSec.");if((t.logs||t.perf)&&t.replay)throw new l("logs and perf are not supported with replayBufferSec yet.")}function Ed(t){return(t.replayBufferSec?`Keep a rolling ${t.replayBufferSec} s replay buffer of `:"Record ")+`${t.target} `+(t.maxDurationSec>0?`for up to ${t.maxDurationSec} s`:"with no time limit")+(t.audioDevice?`, with system audio (${t.audioDevice})`:", without audio")+(t.webcamDevice?`, with the webcam (${t.webcamDevice})`:"")+(t.events?", logging mouse clicks and typing":"")+(t.focus?t.focus==="title"?" and which window is in front, with its title":" and which app is in front":"")+(t.elements?", naming the on-screen controls you click":"")+(t.hotkeys?`, with hotkeys (${fo.marker} marks, ${fo.stop} stops)`:"")+(t.replayBufferSec?", kept only until save_replay or stop_recording { save: true } writes it out?":`, saved to ${t.output}?`)}function _d(t){let e=t.replay&&t.events?.frame?{events:{raw:t.events.raw,keys:t.events.keys,startMs:t.startMs,frame:t.events.frame}}:{};return{id:t.id,target:t.target,outputPath:t.output,fps:t.fps,quality:t.quality,pid:t.pid,pidSpawnedAt:t.spawnedAt,...t.identity,status:"recording",startedAt:(t.now??new Date).toISOString(),videoStartMs:t.startMs,...t.maxDurationSec>0?{maxDurationSec:t.maxDurationSec}:{},...t.window?{matchedWindow:t.window.matchedTitle}:{},...t.events&&!t.replay?{events:{path:t.events.jsonl,keys:t.events.keys}}:{},...t.replay?{replay:{...t.replay,...e}}:{},backend:t.backend,...t.encoder!=="x264"?{encoder:t.encoder}:{},...t.capture&&t.backend!=="wgc"&&!t.replay?{capture:t.capture,segments:{parts:[],current:{path:t.output,startMs:t.startMs,...t.webcam?{webcamPath:t.webcam.rawPath,...t.webcam.startMs!==void 0?{webcamStartMs:t.webcam.startMs}:{}}:{}}}}:{},...t.webcam?{webcam:{device:t.webcam.device,path:zr(t.output),corner:t.webcam.corner??"bottom_right",size:t.webcam.size??ad,shape:t.webcam.shape??"rect"}}:{},processImage:t.processImage}}function Td(t){let e=t.record;return{sessionId:e.id,status:"recording",backend:e.backend,outputPath:e.outputPath,pid:e.pid,fps:e.fps,quality:e.quality,audioDevice:t.audioDevice??null,maxDurationSec:t.maxDurationSec>0?t.maxDurationSec:null,encoder:t.encoder,...t.encoderNote?{encoderNote:t.encoderNote}:{},...t.gpuFrames!==void 0?{gpuFrames:t.gpuFrames}:{},...t.webcamDevice?{webcam:{device:t.webcamDevice,path:zr(e.outputPath)}}:{},...t.window?pr(t.window):{},...t.events&&!t.replay?{eventsPath:t.events.jsonl,keys:t.events.keys}:{},...t.logs?{logsPath:t.logs.path,...t.logs.missing?{logsNote:"A log file does not exist yet; it is read from its start once it appears."}:{}}:{},...t.hotkeys?{hotkeys:{...fo,...t.hotkeys.taken.length?{unavailable:t.hotkeys.taken,warning:`Another app holds ${t.hotkeys.taken.map(r=>fo[r]).join(" and ")}.`}:{}}}:{},...t.replay?{replay:{bufferSec:t.replay.bufferSec,segmentSec:t.replay.segmentSec,dir:t.replay.dir,events:t.replay.events}}:{},note:(t.replay?`Replay buffer running: save_replay keeps the last seconds (up to ${t.replay.bufferSec}s) without stopping it; stop_recording discards the buffer unless save: true (then it writes outputPath).`:"Call stop_recording with this sessionId to finalize the file"+(e.backend==="wgc"?".":" (pause_recording/resume_recording leave stretches out)."))+(t.maxDurationSec>0?` It stops on its own after ${t.maxDurationSec}s (maxDurationSec).`:"")}}import{z as Rd}from"zod";var fe={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},I={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},qi={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},Ad={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1};function B(t){return Rd.looseObject(t)}var K=B({outputPath:Rd.string().describe("Path of the file written.")});import{rmSync as xm,writeFileSync as bv}from"node:fs";import{createReadStream as MS,createWriteStream as CS,existsSync as Xi,mkdirSync as PS,mkdtempSync as IS,readdirSync as Bc,readFileSync as FS,rmSync as Ki,statSync as OS,writeFileSync as Md}from"node:fs";import{stat as Cd,writeFile as NS}from"node:fs/promises";import{pipeline as DS}from"node:stream/promises";import{join as Qe}from"node:path";var Fd=2,LS=3,Ji=4,$n=3600,BS="seg%05d.ts",Od=/^seg(\d{5})\.ts$/,Nd="segments.csv",WS=/^buf-[\w-]+$/,Dd=60;function Ld(t){return t+Dd}function Bd(){return Qe(Pe(),"replay")}function jS(t,e=Fd){return Math.ceil(t/e)+LS}function Wd(t,e=Fd){if(!Number.isInteger(t)||t<Ji||t>$n)throw new l(`replayBufferSec must be an integer from ${Ji} to ${$n} seconds.`);return{dir:Qe(Bd(),`buf-${he()}-${ge(6)}`),bufferSec:t,segmentSec:e,wrap:jS(t,e)}}function jd(t){return Qe(t,Nd)}function Ud(t,e){let r=t.slice(0,-1),n=r.indexOf("-movflags");return n>=0&&r.splice(n,2),[...r,"-force_key_frames",`expr:gte(t,n_forced*${e.segmentSec})`,"-f","segment","-segment_time",String(e.segmentSec),"-segment_wrap",String(e.wrap),"-segment_list",jd(e.dir),"-segment_list_type","csv","-segment_list_size",String(e.wrap),"-segment_format","mpegts","-segment_format_options","flush_packets=1",mn(e.dir,BS)]}function US(t){let e=[];for(let r of t.split(/\r?\n/)){let[n="",o,i]=r.trim().split(","),s=Od.exec(n),a=Number(o),c=Number(i);!s||o===void 0||i===void 0||!Number.isFinite(a)||!Number.isFinite(c)||c<a||e.push({file:n,index:Number(s[1]),start:a,end:c})}return e.sort((r,n)=>r.start-n.start)}function zS(t,e){let r=[],n=0;for(let o=t.length-1;o>=0&&n<e;o--){let i=t[o];r.unshift(i),n+=i.end-i.start}return r}function HS(t,e){let r=t.at(-1),n=r?(r.index+1)%e:0;return`seg${String(n).padStart(5,"0")}.ts`}function GS(t,e,r){let n=r.reencode?Se({quality:r.quality??"standard",audio:r.audio?"aac":"omit"}):["-c","copy"];return["-y","-v","error","-ss",String(_o(Math.max(0,r.startSec))),"-i",t,...n,...Dr,e]}function qS(t,e,r){return wi(t,{from:e,to:r}).map(n=>({...n,t:_o(n.t-e)}))}var _o=t=>Math.round(t*1e3)/1e3;async function Pd(t,e,r){let n=(await Cd(t)).size;return n===0?(await NS(e,""),0):(await DS(MS(t,{start:0,end:n-1}),CS(e),{signal:r}),(await Cd(e)).size)}async function Id(t,e,r){let n=await se(t,["-v","error","-show_entries","format=start_time","-of","csv=p=0",e],15e3,{signal:r}),o=Number.parseFloat(n.stdout.trim());return n.code===0&&Number.isFinite(o)?o:null}async function Wc(t,e){if(!Xi(t.dir))throw new l("This replay buffer has been discarded: its segments are gone.");let r=jd(t.dir),n=Xi(r)?US(FS(r,"utf8")):[],o=zS(n,e.lastSec),i=IS(Qe(t.dir,"save-"));try{let s=[];for(let[R,T]of o.entries()){let M=Qe(i,`${String(R).padStart(5,"0")}.ts`);await Pd(Qe(t.dir,T.file),M,e.signal),s.push(M)}let a=!1;if(e.live!==!1){let R=Qe(t.dir,HS(n,t.wrap)),T=Qe(i,"live.ts");if(Xi(R)&&await Pd(R,T,e.signal)>0){let M=s.at(-1),[H,G]=await Promise.all([Id(e.ffprobe,T,e.signal),M?Id(e.ffprobe,M,e.signal):Promise.resolve(-1/0)]);H!==null&&G!==null&&H>G&&(s.push(T),a=!0)}}if(s.length===0)throw new l("The replay buffer has no footage yet: the first segment is still being written. Try again in a couple of seconds.");let c=Qe(i,"join.txt");Md(c,xo(s));let u=Qe(i,"joined.mp4"),d=pe(e.lastSec+2*t.segmentSec),p=await se(e.ffmpeg,yn(c,u,{quiet:!0}),d,{signal:e.signal});if(p.code!==0)throw new l(`Joining the replay segments failed:
224
224
  ${p.stderr.trim().split(`
225
225
  `).slice(-4).join(`
226
- `)}`);let f=await ne(e.ffprobe,Or(u),3e4,{signal:e.signal}),m=f.code===0?Fr(JSON.parse(f.stdout)):null,h=m?.durationSec??null;if(!h||!(h>0))throw new l("The joined replay has no duration; the segments may be damaged.");let b=Math.max(0,h-e.lastSec),w=await ne(e.ffmpeg,FS(u,e.output,{startSec:b,reencode:e.reencode,quality:e.quality,audio:!!m?.audioCodec}),d,{signal:e.signal});if(w.code!==0)throw new l(`Writing the replay failed:
226
+ `)}`);let f=await se(e.ffprobe,Wr(u),3e4,{signal:e.signal}),m=f.code===0?Br(JSON.parse(f.stdout)):null,h=m?.durationSec??null;if(!h||!(h>0))throw new l("The joined replay has no duration; the segments may be damaged.");let b=Math.max(0,h-e.lastSec),w=await se(e.ffmpeg,GS(u,e.output,{startSec:b,reencode:e.reencode,quality:e.quality,audio:!!m?.audioCodec}),d,{signal:e.signal});if(w.code!==0)throw new l(`Writing the replay failed:
227
227
  ${w.stderr.trim().split(`
228
228
  `).slice(-4).join(`
229
- `)}`);let g=o[0]?.start??n.at(-1)?.end??0,y=Eo(g+b),$=Eo(g+h),S={outputPath:e.output,durationSec:Eo(h-b),fromSec:y,toSec:$,segments:s.length,includesLive:a};if(t.events){let C=t.events.startMs+y*1e3-Od*1e3,M=np(t.events.raw,C),R=OS(hc(M,{startMs:t.events.startMs,frame:t.events.frame}),y,$),{jsonl:P}=$e(e.output);Ad(P,gc(R)),S.eventsPath=P,S.events=an(R)}return S}finally{Yi(i,{recursive:!0,force:!0})}}function jd(t){SS(t.dir,{recursive:!0})}function Ud(t){let e;try{e=Lc(t.dir)}catch{return}for(let r of e)(Id.test(r)||r===Fd)&&Yi(Ke(t.dir,r),{force:!0})}function Ji(t){try{return Yi(t.dir,{recursive:!0,force:!0}),!qi(t.dir)}catch{return!1}}function zd(t){let e=0;try{for(let r of Lc(t.dir))try{let n=kS(Ke(t.dir,r));n.isFile()&&(e+=n.size)}catch{}}catch{}return e}function Hd(t,e=Dd()){let r=new Set([...t].map(i=>i.toLowerCase())),n;try{n=Lc(e)}catch{return 0}let o=0;for(let i of n){let s=Ke(e,i);if(!(!RS.test(i)||r.has(s.toLowerCase())))try{Yi(s,{recursive:!0,force:!0}),o++}catch{}}return o}async function Ki(t,e){if(!e.save)return{saved:!1,discarded:Ji(t)};try{let r=e.tools?.();if(!r)throw new l("ffmpeg is not available to save the replay buffer.");let n=await Bc(t,{...r,lastSec:t.bufferSec,output:e.output,quality:e.quality,live:!1});return{saved:!0,discarded:Ji(t),save:n}}catch(r){return{saved:!1,discarded:!1,error:U(r)}}}var Gd=3;function Vi(t){return`${t}.stop`}function qd(t,e,r){return`Add-Type @"
229
+ `)}`);let g=o[0]?.start??n.at(-1)?.end??0,y=_o(g+b),v=_o(g+h),x={outputPath:e.output,durationSec:_o(h-b),fromSec:y,toSec:v,segments:s.length,includesLive:a};if(t.events){let R=t.events.startMs+y*1e3-Dd*1e3,T=ip(t.events.raw,R),M=qS(gc(T,{startMs:t.events.startMs,frame:t.events.frame}),y,v),{jsonl:H}=ke(e.output);Md(H,bc(M)),x.eventsPath=H,x.events=pn(M)}return x}finally{Ki(i,{recursive:!0,force:!0})}}function zd(t){PS(t.dir,{recursive:!0})}function Hd(t){let e;try{e=Bc(t.dir)}catch{return}for(let r of e)(Od.test(r)||r===Nd)&&Ki(Qe(t.dir,r),{force:!0})}function Yi(t){try{return Ki(t.dir,{recursive:!0,force:!0}),!Xi(t.dir)}catch{return!1}}function Gd(t){let e=0;try{for(let r of Bc(t.dir))try{let n=OS(Qe(t.dir,r));n.isFile()&&(e+=n.size)}catch{}}catch{}return e}function qd(t,e=Bd()){let r=new Set([...t].map(i=>i.toLowerCase())),n;try{n=Bc(e)}catch{return 0}let o=0;for(let i of n){let s=Qe(e,i);if(!(!WS.test(i)||r.has(s.toLowerCase())))try{Ki(s,{recursive:!0,force:!0}),o++}catch{}}return o}async function Vi(t,e){if(!e.save)return{saved:!1,discarded:Yi(t)};try{let r=e.tools?.();if(!r)throw new l("ffmpeg is not available to save the replay buffer.");let n=await Wc(t,{...r,lastSec:t.bufferSec,output:e.output,quality:e.quality,live:!1});return{saved:!0,discarded:Yi(t),save:n}}catch(r){return{saved:!1,discarded:!1,error:z(r)}}}var Xd=3;function Qi(t){return`${t}.stop`}function Jd(t,e,r){return`Add-Type @"
230
230
  using System;using System.Runtime.InteropServices;
231
231
  public class ScNudge{
232
232
  [StructLayout(LayoutKind.Sequential)] public struct RECT{public int L,T,R,B;}
@@ -236,9 +236,9 @@ public class ScNudge{
236
236
  "@
237
237
  $r=New-Object ScNudge+RECT;$r.R=1;$r.B=1
238
238
  ${r?`$p=Get-Process -Id ${r} -ErrorAction SilentlyContinue
239
- `:""}while([ScNudge]::IsWindow([IntPtr]${t})${r?" -and $p -and !$p.HasExited":""}){[void][ScNudge]::RedrawWindow([IntPtr]${t},[ref]$r,[IntPtr]::Zero,0x0105);Start-Sleep -Milliseconds ${e}}`}var Zi=["nvenc","qsv","amf"],es={x264:"libx264",nvenc:"h264_nvenc",qsv:"h264_qsv",amf:"h264_amf"},NS={nvenc:{draft:{preset:"p1",q:30},standard:{preset:"p4",q:25},high:{preset:"p6",q:20}},qsv:{draft:{preset:"veryfast",q:30},standard:{preset:"medium",q:25},high:{preset:"slower",q:20}},amf:{draft:{preset:"speed",q:30},standard:{preset:"balanced",q:25},high:{preset:"quality",q:20}}};function ur(t,e,r={}){if(!yc[e])throw new l(`Unknown quality preset "${e}".`);if(t==="x264")return _e(e);let{preset:n,q:o}=NS[t][e],i=["-c:v",es[t]],s=t==="nvenc"?["-preset",n,"-rc","vbr","-cq",String(o),"-b:v","0"]:t==="qsv"?["-preset",n,"-global_quality",String(o)]:["-quality",n,"-rc","cqp","-qp_i",String(o),"-qp_p",String(o)];return[...i,...s,...r.gpuFrames?[]:["-pix_fmt","nv12"]]}function DS(t){return["-hide_banner","-v","error","-f","lavfi","-i","color=c=black:s=256x256:r=30","-frames:v","3",...ur(t,"draft"),"-f","null","-"]}function Yd(t){return["-hide_banner","-v","error","-f","lavfi","-i",`ddagrab=framerate=10${t?"":",hwdownload,format=bgra"}`,"-frames:v","2",...t?ur(t,"draft",{gpuFrames:!0}):[],"-f","null","-"]}var LS=2e4;function Wc(t){return async e=>{try{return(await ne(t,e,LS)).code===0}catch{return!1}}}var Xd=new Map;function jc(t,e,r,n){let o=`${t}\0${e}`,i=Xd.get(o);return i||(i=n(r),Xd.set(o,i)),i}async function Uc(t,e=Wc(t)){let r=await Promise.all(Zi.map(n=>jc(t,`enc:${n}`,DS(n),e)));return Object.fromEntries(Zi.map((n,o)=>[n,r[o]]))}var Qi={nvenc:{width:4096,height:4096},qsv:{width:4096,height:2304},amf:{width:4096,height:2304}};function BS(t,e){let r=Qi[t];return e.width<=r.width&&e.height<=r.height}async function Kd(t,e,r,n=Wc(r),o){if(t==="x264")return{encoder:"x264",gpuFrames:!1};let i=d=>!o||BS(d,o),s=o?`${o.width}x${o.height}`:"";if(t!=="auto"&&!i(t)){let d=Qi[t];throw new l(`The ${t} encoder (${es[t]}) cannot encode a ${s} frame (at most ${d.width}x${d.height}).`,'Use encoder: "x264" (or "auto", which picks libx264 for it), or record a smaller target.')}let a=await Uc(r,n),c=t==="auto"?Zi.find(d=>a[d]&&i(d)):a[t]?t:void 0;if(!c){if(t==="auto"){let d=Zi.filter(p=>a[p]);return{encoder:"x264",gpuFrames:!1,note:d.length>0?`The capture is ${s}, larger than the hardware encoders here take (${d.map(p=>`${p}: ${Qi[p].width}x${Qi[p].height}`).join(", ")}); using libx264.`:"No hardware encoder passed a trial encode; using libx264."}}throw new l(`The ${t} encoder (${es[t]}) failed a trial encode on this machine.`,'Use encoder: "auto" (falls back to libx264) or "x264"; doctor lists the encoders that work here.')}let u=e==="ddagrab"&&await jc(r,`dda:${c}`,Yd(c),n);return{encoder:c,gpuFrames:u}}async function Vd(t,e,r){let n=await e(t);if(n.settled==="running"||t.encoder==="x264")return{run:n,pick:t};let o={encoder:"x264",gpuFrames:!1};if(r.canFallback&&!await r.canFallback())return{run:n,pick:t};let i=`${t.encoder} (${es[t.encoder]})`,s=r.why(n).trim(),a=`the ${i} encoder exited at start${s?`:
239
+ `:""}while([ScNudge]::IsWindow([IntPtr]${t})${r?" -and $p -and !$p.HasExited":""}){[void][ScNudge]::RedrawWindow([IntPtr]${t},[ref]$r,[IntPtr]::Zero,0x0105);Start-Sleep -Milliseconds ${e}}`}var es=["nvenc","qsv","amf"],ts={x264:"libx264",nvenc:"h264_nvenc",qsv:"h264_qsv",amf:"h264_amf"},XS={nvenc:{draft:{preset:"p1",q:30},standard:{preset:"p4",q:25},high:{preset:"p6",q:20}},qsv:{draft:{preset:"veryfast",q:30},standard:{preset:"medium",q:25},high:{preset:"slower",q:20}},amf:{draft:{preset:"speed",q:30},standard:{preset:"balanced",q:25},high:{preset:"quality",q:20}}};function dr(t,e,r={}){if(!xc[e])throw new l(`Unknown quality preset "${e}".`);if(t==="x264")return Re(e);let{preset:n,q:o}=XS[t][e],i=["-c:v",ts[t]],s=t==="nvenc"?["-preset",n,"-rc","vbr","-cq",String(o),"-b:v","0"]:t==="qsv"?["-preset",n,"-global_quality",String(o)]:["-quality",n,"-rc","cqp","-qp_i",String(o),"-qp_p",String(o)];return[...i,...s,...r.gpuFrames?[]:["-pix_fmt","nv12"]]}function JS(t){return["-hide_banner","-v","error","-f","lavfi","-i","color=c=black:s=256x256:r=30","-frames:v","3",...dr(t,"draft"),"-f","null","-"]}function Vd(t){return["-hide_banner","-v","error","-f","lavfi","-i",`ddagrab=framerate=10${t?"":",hwdownload,format=bgra"}`,"-frames:v","2",...t?dr(t,"draft",{gpuFrames:!0}):[],"-f","null","-"]}var YS=2e4;function jc(t){return async e=>{try{return(await se(t,e,YS)).code===0}catch{return!1}}}var Yd=new Map;function Uc(t,e,r,n){let o=`${t}\0${e}`,i=Yd.get(o);return i||(i=n(r),Yd.set(o,i)),i}async function zc(t,e=jc(t)){let r=await Promise.all(es.map(n=>Uc(t,`enc:${n}`,JS(n),e)));return Object.fromEntries(es.map((n,o)=>[n,r[o]]))}var Zi={nvenc:{width:4096,height:4096},qsv:{width:4096,height:2304},amf:{width:4096,height:2304}};function KS(t,e){let r=Zi[t];return e.width<=r.width&&e.height<=r.height}async function Qd(t,e,r,n=jc(r),o){if(t==="x264")return{encoder:"x264",gpuFrames:!1};let i=d=>!o||KS(d,o),s=o?`${o.width}x${o.height}`:"";if(t!=="auto"&&!i(t)){let d=Zi[t];throw new l(`The ${t} encoder (${ts[t]}) cannot encode a ${s} frame (at most ${d.width}x${d.height}).`,'Use encoder: "x264" (or "auto", which picks libx264 for it), or record a smaller target.')}let a=await zc(r,n),c=t==="auto"?es.find(d=>a[d]&&i(d)):a[t]?t:void 0;if(!c){if(t==="auto"){let d=es.filter(p=>a[p]);return{encoder:"x264",gpuFrames:!1,note:d.length>0?`The capture is ${s}, larger than the hardware encoders here take (${d.map(p=>`${p}: ${Zi[p].width}x${Zi[p].height}`).join(", ")}); using libx264.`:"No hardware encoder passed a trial encode; using libx264."}}throw new l(`The ${t} encoder (${ts[t]}) failed a trial encode on this machine.`,'Use encoder: "auto" (falls back to libx264) or "x264"; doctor lists the encoders that work here.')}let u=e==="ddagrab"&&await Uc(r,`dda:${c}`,Vd(c),n);return{encoder:c,gpuFrames:u}}async function Zd(t,e,r){let n=await e(t);if(n.settled==="running"||t.encoder==="x264")return{run:n,pick:t};let o={encoder:"x264",gpuFrames:!1};if(r.canFallback&&!await r.canFallback())return{run:n,pick:t};let i=`${t.encoder} (${ts[t.encoder]})`,s=r.why(n).trim(),a=`the ${i} encoder exited at start${s?`:
240
240
  ${s}`:""}`;r.beforeRetry?.();let c=await e(o);if(c.settled==="exited")return{run:c,pick:o,failure:a};let u=s.split(`
241
- `).at(-1)??"";return{run:c,pick:{...o,note:`The ${i} encoder exited at start; recording with libx264 instead.${u?` ffmpeg said: ${u}`:""}`},failure:a}}function Qd(t,e=Wc(t)){return jc(t,"dda",Yd(),e)}function WS(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.trim().split(",");if(n.length<7)continue;let o=n.slice(0,6).map(Number);if(o.some(p=>!Number.isInteger(p)))continue;let[i=0,s=0,a=0,c=0,u=0,d=0]=o;u<=0||d<=0||e.push({adapter:i,output:s,x:a,y:c,w:u,h:d,name:n.slice(6).join(",")})}return e}var jS=`
241
+ `).at(-1)??"";return{run:c,pick:{...o,note:`The ${i} encoder exited at start; recording with libx264 instead.${u?` ffmpeg said: ${u}`:""}`},failure:a}}function em(t,e=jc(t)){return Uc(t,"dda",Vd(),e)}function VS(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.trim().split(",");if(n.length<7)continue;let o=n.slice(0,6).map(Number);if(o.some(p=>!Number.isInteger(p)))continue;let[i=0,s=0,a=0,c=0,u=0,d=0]=o;u<=0||d<=0||e.push({adapter:i,output:s,x:a,y:c,w:u,h:d,name:n.slice(6).join(",")})}return e}var QS=`
242
242
  Add-Type -TypeDefinition @"
243
243
  using System; using System.Runtime.InteropServices; using System.Text;
244
244
  public static class ScDxgi {
@@ -263,23 +263,23 @@ public static class ScDxgi {
263
263
  return sb.ToString(); } }
264
264
  "@
265
265
  [ScDxgi]::List()
266
- `,US=5e3,_o=null;function Zd(){if(_o&&Date.now()-_o.at<US)return _o.outputs;let t=st(jS,"DXGI outputs").then(WS);return _o={at:Date.now(),outputs:t},t.catch(()=>{_o=null}),t}var Jd=t=>t-t%2;function em(t,e){let r=a=>t.x>=a.x&&t.y>=a.y&&t.x+t.w<=a.x+a.w&&t.y+t.h<=a.y+a.h,n=e.find(r);if(!n)throw new l(`backend "ddagrab" captures one display, and ${t.x},${t.y} ${t.w}x${t.h} is not inside a single one.`,'Use a monitor:<i> target, a region inside one display, or backend "gdigrab".');if(n.adapter!==0)throw new l(`That display (${n.name||`adapter ${n.adapter} output ${n.output}`}) is driven by a second GPU, which ddagrab cannot reach.`,'Use backend "gdigrab" for it.');let o=Jd(t.w),i=Jd(t.h);if(o<=0||i<=0)throw new l("The capture rectangle is too small to record (needs at least 2x2 px).");return t.x===n.x&&t.y===n.y&&o===n.w&&i===n.h?{output:n.output}:{output:n.output,crop:{x:t.x-n.x,y:t.y-n.y,w:o,h:i}}}function tm(t,e,r){let n=t.crop?`:offset_x=${t.crop.x}:offset_y=${t.crop.y}:video_size=${t.crop.w}x${t.crop.h}`:"",o=r.drawMouse===!1?0:1;return["-f","lavfi","-i",`ddagrab=output_idx=${t.output}:framerate=${e}:draw_mouse=${o}${n}${r.download?",hwdownload,format=bgra":""}`]}import{spawnSync as Hc}from"node:child_process";import{readFileSync as ts,writeFileSync as nm,renameSync as om,existsSync as zS,copyFileSync as HS,openSync as GS,closeSync as qS,unlinkSync as im,statSync as sm,linkSync as XS}from"node:fs";import{basename as JS}from"node:path";var YS=100;function xn(t){return t==="recording"||t==="paused"}function KS(t,e){return t.status==="paused"?{status:"stopped",reaped:!1}:t.status!=="recording"?{status:t.status,reaped:!1}:e?{status:"orphaned",reaped:!0}:{status:"stopped",reaped:!1}}function am(t,e,r){return xn(t.status)&&t.serverPid!==void 0&&t.serverPid!==e&&r}function cm(t,e,r){return t.backend==="wgc"||!am(t,e,r)?null:`Recording ${t.id} belongs to another running screencast-mcp instance (pid ${t.serverPid}). Stop it from the client connected to that instance; closing that instance also finalizes it.`}function Gc(t,e=new Map){let r=t.serverPid;return r===void 0||r===process.pid||!ze(r)?!1:(e.has(r)||e.set(r,pm(r)),VS(t,e.get(r)??null))}function um(){return{serverPid:process.pid,serverStartedAt:new Date(Date.now()-process.uptime()*1e3).toISOString(),serverImage:JS(process.execPath).toLowerCase()}}var lm=5e3;function VS(t,e){if(!e)return!0;if(t.serverImage&&e.image.toLowerCase()!==t.serverImage.toLowerCase())return!1;let r=Date.parse(t.serverStartedAt??t.startedAt);return!(Number.isFinite(r)&&e.startMs>r+lm)}function QS(t){let e=/^(.+)\|(\d+)\s*$/m.exec(t.trim());return e?.[1]&&e[2]?{image:e[1].trim(),startMs:Number(e[2])}:null}function pm(t){if(process.platform!=="win32"||!Number.isInteger(t)||t<=0)return null;let e=`$p = Get-CimInstance Win32_Process -Filter "ProcessId=${t}"; if ($p) { "{0}|{1}" -f $p.Name, ([DateTimeOffset]$p.CreationDate).ToUnixTimeMilliseconds() }`,r=Hc("powershell",["-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",windowsHide:!0,timeout:1e4,killSignal:"SIGKILL"});return r.status===0&&r.stdout?QS(r.stdout):null}function ze(t){if(t===null||!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function dm(t){return t.processImage??(t.backend==="wgc"?"node.exe":"ffmpeg.exe")}function ZS(t,e){return(t.split(/\r?\n/)[0]??"").toLowerCase().startsWith(`"${e.toLowerCase()}"`)}function ev(t,e){if(t===null||process.platform!=="win32")return!1;let r=Hc("tasklist",["/FI",`PID eq ${t}`,"/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0});return r.status!==0||!r.stdout?!1:ZS(r.stdout,e)}function tv(t,e){if(!e)return!0;if(e.image.toLowerCase()!==dm(t).toLowerCase())return!1;let r=t.pidSpawnedAt;return!(typeof r=="number"&&Number.isFinite(r)&&e.startMs>r+lm)}function qc(t){return t.pid===null||!ev(t.pid,dm(t))?!1:t.pidSpawnedAt===void 0||tv(t,pm(t.pid))}function mm(t){let{code:e,backend:r,maxDurationSec:n,elapsedMs:o}=t;return r==="wgc"&&e===Gd?{status:"stopped",endReason:"window_closed"}:e!==0&&e!==null?{status:"failed",endReason:"crashed"}:{status:"stopped",endReason:n>0&&o>=n*1e3-2e3?"max_duration":"stopped"}}function lr(t){if(process.platform==="win32")Hc("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0});else try{process.kill(t,"SIGKILL")}catch{}}function zc(t){let e=t.filter(n=>xn(n.status)),r=t.filter(n=>!xn(n.status)).sort((n,o)=>n.startedAt<o.startedAt?1:-1).slice(0,YS);return[...e,...r]}var rv=3e4,fm=15e3;function nv(t,e,r){return!t||typeof t.at!="number"||e-t.at>rv?!0:typeof t.pid=="number"&&!r}function hm(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function ov(t,e){let r=Date.now()+1e3;for(;;)try{om(t,e);return}catch(n){let o=n.code;if(o!=="EPERM"&&o!=="EBUSY"&&o!=="EACCES"||Date.now()>=r)throw n;hm(15)}}function iv(t,e){let r=`${t}.${process.pid}.${Date.now()}.stale`;try{om(t,r)}catch{return!1}let n=!0;try{ts(r,"utf8")!==e&&(n=!1,XS(r,t))}catch{}try{im(r)}catch{}return n}function rm(t,e,r=fm){let n=`${t}.lock`,o=Date.now()+r,i,s;for(let a=0;;a++)try{let c=GS(n,"wx");s=JSON.stringify({pid:process.pid,at:Date.now(),nonce:Math.random().toString(36).slice(2)}),nm(c,s),qS(c);break}catch(c){let u=c.code;if(!(u==="EEXIST"||u==="EPERM"||u==="EACCES"||u==="EBUSY"))throw new l(`Could not lock the session registry (${n}): ${U(c)}`);if(u==="EEXIST"){let p;try{let f=ts(n,"utf8"),m;try{m=JSON.parse(f)}catch{m={at:sm(n).mtimeMs}}p={raw:f,holder:m}}catch{p=null}if(p&&(i=p.holder?.pid,nv(p.holder,Date.now(),ze(p.holder?.pid??null))&&iv(n,p.raw)))continue}if(Date.now()>=o)throw new l(`The session registry is busy: could not take ${n} within ${r/1e3} s${i!==void 0?` (held by process ${i})`:""}. Nothing was written.`,"Another screencast-mcp server is writing to the same registry. Retry; if no other server is running, delete the .lock file.");hm(Math.min(50,2**Math.min(a,6))*(.5+Math.random()))}try{return e()}finally{try{ts(n,"utf8")===s&&im(n)}catch{}}}var rs=class{constructor(e,r=fm){this.path=e;this.lockWaitMs=r}path;lockWaitMs;records=new Map;pending=new Map;removed=new Set;seen=null;children=new Map;stopping=new Set;listeners=[];onChange(e){this.listeners.push(e)}readDisk(){if(!zS(this.path))return new Map;try{return this.parseDisk()}catch{try{HS(this.path,`${this.path}.bak`),process.stderr.write(`Session registry was unreadable; saved a copy to ${this.path}.bak and starting fresh.
267
- `)}catch{}return new Map}}parseDisk(){let e=JSON.parse(ts(this.path,"utf8"));return new Map(e.map(r=>[r.id,r]))}signature(){try{let e=sm(this.path,{bigint:!0});return`${e.ino}:${e.size}:${e.mtimeNs}`}catch{return null}}overlay(e){for(let[r,n]of this.pending){let o=e.get(r)??this.records.get(r);o&&e.set(r,{...o,...n})}for(let r of this.removed)e.delete(r);return e}refresh(){let e=this.signature();if(e===this.seen)return;let r;try{r=e===null?new Map:this.parseDisk()}catch{return}this.seen=e,this.records=new Map(zc([...this.overlay(r).values()]).map(n=>[n.id,n]))}load(){let e=()=>{let n=this.readDisk();return this.seen=this.signature(),n},r;try{r=rm(this.path,e,this.lockWaitMs)}catch(n){process.stderr.write(`${U(n)} Reading the session registry without the lock.
268
- `),r=e()}this.records=new Map(zc([...this.overlay(r).values()]).map(n=>[n.id,n]))}persist(){rm(this.path,()=>{let e=zc([...this.overlay(this.readDisk()).values()]),r=`${this.path}.${process.pid}.tmp`;nm(r,JSON.stringify(e,null,2)),ov(r,this.path),this.seen=this.signature(),this.records=new Map(e.map(n=>[n.id,n])),this.pending.clear(),this.removed.clear()},this.lockWaitMs);for(let e of this.listeners)try{e()}catch{}}create(e){this.records.set(e.id,e),this.pending.set(e.id,e);try{this.persist()}catch(r){throw this.records.delete(e.id),this.pending.delete(e.id),r}}remove(e){let r=e.flatMap(n=>{let o=this.records.get(n);return o?[o]:[]});for(let n of e)this.removed.add(n),this.pending.delete(n),this.records.delete(n);try{this.persist()}catch(n){for(let o of e)this.removed.delete(o);for(let o of r)this.records.set(o.id,o);throw n}}get(e){return this.refresh(),this.records.get(e)}list(){return this.refresh(),[...this.records.values()].sort((e,r)=>e.startedAt<r.startedAt?1:-1)}update(e,r){let n=this.records.get(e);if(n||(this.refresh(),n=this.records.get(e)),!n)return;let o={...n,...r};return this.records.set(e,o),this.pending.set(e,{...this.pending.get(e),...r}),this.persist(),this.records.get(e)??o}tryUpdate(e,r){try{return this.update(e,r)}catch(n){process.stderr.write(`Could not save session ${e}: ${U(n)}
269
- `);return}}attachChild(e,r){this.children.set(e,r)}getChild(e){return this.children.get(e)}detachChild(e,r){r&&this.children.get(e)!==r||this.children.delete(e)}activeIds(){return[...[...this.children.keys()].filter(e=>this.records.get(e)?.status==="recording"),...[...this.paused].filter(e=>this.records.get(e)?.status==="paused"&&!this.children.has(e))]}paused=new Set;markPaused(e){this.paused.add(e)}ownsPaused(e){return this.paused.has(e)}clearPaused(e){this.paused.delete(e)}markStopping(e){this.stopping.add(e)}isStopping(e){return this.stopping.has(e)}clearStopping(e){this.stopping.delete(e)}reapOrphans(){this.refresh();let e=[],r=new Map;for(let n of this.records.values()){if(!xn(n.status)||am(n,process.pid,Gc(n,r)))continue;let o=ze(n.pid),i=KS(n,o);i.reaped&&n.pid!==null&&(qc(n)&&lr(n.pid),e.push(n.id));let s={status:i.status,...n.stoppedAt?{}:{stoppedAt:new Date().toISOString()},...i.status==="orphaned"?{error:"Reaped on server restart (recording was interrupted)."}:{},...n.status==="paused"?{endReason:"shutdown",error:`The server exited while this recording was paused; its parts were not joined (${n.segments?.parts.map(a=>a.path).join(", ")??n.outputPath}).`}:{},...n.status==="recording"&&(n.segments?.parts.length??0)>0?{endReason:"shutdown",error:`The server exited before this recording's segments were joined; ${n.outputPath} holds only the first one. The parts: ${[...n.segments?.parts.map(a=>a.path)??[],...n.segments?.current?[n.segments.current.path]:[]].join(", ")}.`}:{}};this.records.set(n.id,{...n,...s}),this.pending.set(n.id,{...this.pending.get(n.id),...s})}return this.records.size>0&&this.persist(),e}};async function Xc(t,e){let r=Date.now()+e;for(;Date.now()<r&&ze(t);)await new Promise(n=>setTimeout(n,100))}function gm(t,e){return new Promise(r=>{if(t.exitCode!==null||t.signalCode!==null)return r(!0);let n=setTimeout(()=>r(!1),e);t.once("exit",()=>{clearTimeout(n),r(!0)})})}async function ym(t,e,r){if(!t.stdin||!t.stdin.writable)return!1;t.stdin.write(`q
270
- `),t.stdin.end();let n=await gm(t,r);return!n&&e!==null&&(lr(e),await Xc(e,2e3),await gm(t,2e3)),n}async function av(t,e){let r=t.segments;if(!r)return[];let n=[...r.parts];if(r.current){let o=await se(r.current.path,{ffprobe:e}),i=t.stoppedAt?Date.parse(t.stoppedAt):Date.now(),s=Ic(r.current.path,o,r.current.startMs,i)??0;n.push({...r.current,durationSec:s})}return n}function cv(t){let e=t.segments;return!!e&&(e.parts.length>0||!!t.webcam)}async function Yc(t,e){let r=await av(t,e.ffprobe),n=await fd(t.outputPath,r,{ffmpeg:e.ffmpeg,webcamOutput:t.webcam?Lr(t.outputPath):void 0,webcamCodec:ur(t.encoder??"x264",t.quality,{gpuFrames:!1})});return{patch:{segments:{parts:r},...t.webcam?{webcam:{...t.webcam,error:n.webcamError}}:{}},count:r.length,error:n.error}}var Jc=new WeakMap;function uv(t,e){return Jc.get(t)?.get(e)?.kind??null}function ns(t,e,r){let n=uv(t,e);if(n&&n!==r)throw new l(`Cannot ${r} ${e}: a ${n} of it is in progress.`,"Retry once it finishes (get_session shows the session's status).")}function os(t,e,r,n,o={}){let i=Jc.get(t);i||Jc.set(t,i=new Map);let s=i.get(e);if(s?.kind===r)return s.promise;if(s&&!o.queue)return Promise.reject(new l(`Cannot ${r} ${e}: a ${s.kind} of it is in progress.`,"Retry once it finishes (get_session shows the session's status)."));let a;if(s)a=s.promise.then(()=>n(!0),()=>n(!0));else try{a=n(!1)}catch(d){a=Promise.reject(d)}let c=i,u=a.finally(()=>{c.get(e)?.promise===u&&c.delete(e)});return c.set(e,{kind:r,promise:u}),u}function xm(t,e,r){return os(t,e.id,"pause",()=>lv(t,t.get(e.id)??e,r))}async function lv(t,e,r){let n=t.getChild(e.id),o=cd(e,!!n);if(o)throw new l(`Cannot pause ${e.id}: ${o}.`);ld(e.id),t.markStopping(e.id);try{let i=Date.now(),s=await ym(n,e.pid,r.gracefulMs??8e3);t.detachChild(e.id,n);let a=e.segments.current,c=await r.probe(a.path),u=Ic(a.path,c,a.startMs,i)??0,d=e.segments.parts,p=u>0?[...d,{...a,durationSec:u}]:d;return u<=0&&a.path!==e.outputPath&&wm(a.path,{force:!0}),t.markPaused(e.id),{record:t.update(e.id,{status:"paused",pid:null,segments:{parts:p}}),recordedSec:rt(p),segmentSec:u,graceful:s}}finally{dd(e.id),t.clearStopping(e.id)}}async function Sm(t,e,r=1e4){let n=t.activeIds(),o=n.map(async a=>{let c=t.get(a);if(c)try{await To(t,c,{reason:"shutdown",probe:e,gracefulMs:Math.min(8e3,r)})}catch(u){process.stderr.write(`Stopping ${a} on shutdown failed: ${U(u)}
271
- `)}}),i,s=new Promise(a=>{i=setTimeout(a,r)});return await Promise.race([Promise.allSettled(o),s]),clearTimeout(i),n}function To(t,e,r){return os(t,e.id,"stop",async n=>{if(!n)return bm(t,e,r);let o=t.get(e.id)??e;return o.status!=="recording"&&o.status!=="paused"?{record:o,graceful:!0,durationSec:o.durationSec??null}:bm(t,o,r)},{queue:!0})}async function bm(t,e,r){t.markStopping(e.id);let n=e.backend==="wgc"?Vi(e.outputPath):null;try{let o=!1,i=t.getChild(e.id),s=f=>new l(`Could not stop recording ${e.id}: its process (pid ${f}) is still running.`);if(i&&i.stdin&&i.stdin.writable){if(o=await ym(i,e.pid,r.gracefulMs??8e3),!o&&e.pid!==null&&ze(e.pid))throw s(e.pid)}else if(e.pid!==null&&ze(e.pid)&&qc(e)&&(n&&(sv(n,""),await Xc(e.pid,r.gracefulMs??8e3),o=!ze(e.pid)),ze(e.pid)&&(lr(e.pid),await Xc(e.pid,2e3)),ze(e.pid)))throw s(e.pid);t.detachChild(e.id,i),e.status==="paused"&&(o=!0),Hi(e.id),t.clearPaused(e.id),await Kt(e.id);let a,c={};if(cv(e)){let f=await Yc(e,k());c=f.patch,a={count:f.count,...f.error?{error:f.error}:{}}}let u=e.replay?await Ki(e.replay,{save:r.saveReplay??!1,output:e.outputPath,quality:e.quality,tools:k}):void 0,d=await r.probe(e.outputPath);return{record:t.update(e.id,{...c,status:"stopped",stoppedAt:new Date().toISOString(),durationSec:d??void 0,endReason:r.reason,error:a?.error}),graceful:o,durationSec:d,...u?{replay:u}:{},...a?{segments:a}:{}}}finally{n&&wm(n,{force:!0}),t.clearStopping(e.id)}}import{existsSync as dv,readFileSync as mv,renameSync as fv,writeFileSync as hv}from"node:fs";var is=t=>Math.round(t*1e3)/1e3;function Ao(t,e){let r=0;for(let n of e){if(t<=n.start)break;r+=(Math.min(t,n.end)-n.start)*(n.factor?1-1/n.factor:1)}return r}function ss(t,e){let r=t;for(let n of e)if(n.op==="trim"){if(r<n.start||r>=n.end)return null;r-=n.start}else n.op==="speed"?r/=n.factor:r-=Ao(r,n.spans);return r}function Wr(t,e,r){let n=t,o=e;for(let i of r)if(i.op==="trim"?(n=Math.max(n,i.start)-i.start,o=Math.min(o,i.end)-i.start):i.op==="speed"?(n/=i.factor,o/=i.factor):(n-=Ao(n,i.spans),o-=Ao(o,i.spans)),o<=n)return null;return[n,o]}function km(t,e){return t.flatMap(r=>{let n=Wr(r.start,r.end,e);return n?[{start:is(n[0]),end:is(n[1])}]:[]})}function as(t,e){return t.flatMap(r=>{let n=Wr(r.start,r.end,e);return n&&n[1]-n[0]>=.05?[{...r,start:is(n[0]),end:is(n[1])}]:[]})}var pv=/^(\d+):(\d{2}):(\d{2})\.(\d{2})$/,vm=t=>{let e=t.trim().match(pv);return e?Number(e[1])*3600+Number(e[2])*60+Number(e[3])+Number(e[4])/100:null},$m=t=>{let e=Math.round(t*100),r=n=>String(n).padStart(2,"0");return`${Math.floor(e/36e4)}:${r(Math.floor(e%36e4/6e3))}:${r(Math.floor(e%6e3/100))}.${r(e%100)}`};function Em(t,e){return t.split(/\r?\n/).flatMap(r=>{let n=r.match(/^(Dialogue:\s*[^,]*,)([^,]*),([^,]*),(.*)$/);if(!n)return[r];let[,o,i,s,a]=n,c=vm(i),u=vm(s);if(c===null||u===null)return[r];let d=Wr(c,u,e);return d&&d[1]-d[0]>=.05?[`${o}${$m(d[0])},${$m(d[1])},${a}`]:[]}).join(`
272
- `)}var _m=500,Kc=200,Tm=3,Sn=10,It=t=>Math.round(t*1e3)/1e3;function pr(t){return`${t.replace(/\.[^./\\]+$/,"")}.markers.json`}function Am(t,e){return Math.max(0,It((e-t)/1e3))}function Ro(t,e=Kc){let r=t.replace(/\s+/g," ").trim();return r.length>e?`${r.slice(0,e-1).trimEnd()}\u2026`:r}function us(t,e){if(t.length>=_m)throw new l(`A recording holds at most ${_m} markers.`);let r=Ro(e.label);if(!r)throw new l("A marker needs a non-empty label.");if(!Number.isFinite(e.t)||e.t<0)throw new l("A marker time must be a non-negative number of seconds.");let n={...e,t:It(e.t),label:r},o=t.findIndex(i=>i.t>n.t);return o===-1?[...t,n]:[...t.slice(0,o),n,...t.slice(o)]}function gv(t){let e=t;return!!e&&typeof e.t=="number"&&Number.isFinite(e.t)&&e.t>=0&&typeof e.label=="string"}function bv(t){let e;try{e=JSON.parse(t)}catch{return[]}let r=Array.isArray(e)?e:e?.markers;return Array.isArray(r)?r.filter(gv).sort((n,o)=>n.t-o.t):[]}function Le(t){let e=pr(t);if(!dv(e))return[];try{return bv(mv(e,"utf8"))}catch{return[]}}function dr(t,e,r){let n=pr(t),o=`${n}.${process.pid}.tmp`;return hv(o,JSON.stringify({...r?{sessionId:r}:{},markers:e},null,2)),fv(o,n),n}function Rm(t,e){let r=[...t].sort((n,o)=>n.t-o.t);for(let n of e){if(n.op==="speed"){r=r.map(s=>({...s,t:It(s.t/n.factor)}));continue}if(n.op==="cut"){r=r.map(s=>({...s,t:It(s.t-Ao(s.t,n.spans))}));continue}let o=r.filter(s=>s.t>=n.start&&s.t<n.end).map(s=>({...s,t:It(s.t-n.start)})),i=r.filter(s=>s.t<n.start).at(-1);r=i&&!o.some(s=>s.t<.001)?[{...i,t:0},...o]:o}return r}function ls(t,e,r={}){let n=Math.max(.001,r.minChapterSec??1),o=t.filter(a=>Number.isFinite(a.start)&&a.start>=0&&a.start<e).map((a,c)=>({start:It(a.start),title:Ro(a.title,100)||`Chapter ${c+1}`})).sort((a,c)=>a.start-c.start),i=[];for(let a of o){let c=i.at(-1);c?a.start-c.start>=n&&i.push(a):a.start<n?i.push({...a,start:0}):i.push({start:0,title:r.introTitle??"Intro"},a)}let s=i.at(-1);return i.length>1&&s&&e-s.start<n&&i.pop(),i.map((a,c)=>({start:a.start,end:It(i[c+1]?.start??e),title:a.title}))}function wv(t,e){let r=Math.max(0,Math.floor(t)),n=Math.floor(r/3600),o=Math.floor(r%3600/60),i=String(r%60).padStart(2,"0");return e?`${n}:${String(o).padStart(2,"0")}:${i}`:`${Math.floor(r/60)}:${i}`}function Mm(t,e){let r=e>=3600,n=t.map(s=>`${wv(s.start,r)} ${s.title}`).join(`
273
- `),o=[];t.length<Tm&&o.push(`YouTube needs at least ${Tm} chapters; there are ${t.length}.`),t[0]&&t[0].start!==0&&o.push("YouTube needs the first chapter at 0:00.");let i=t.filter(s=>s.end-s.start<Sn);return i.length>0&&o.push(`YouTube needs every chapter to be at least ${Sn} s long; ${i.length} ${i.length===1?"is":"are"} shorter (${i.map(s=>`"${s.title}"`).join(", ")}). Raise minChapterSec to ${Sn} to merge them.`),{text:n,issues:o}}function yv(t){return t.replace(/[=;#\\\n]/g,e=>`\\${e}`)}function ps(t){let e=[";FFMETADATA1"];for(let r of t)e.push("[CHAPTER]","TIMEBASE=1/1000",`START=${Math.round(r.start*1e3)}`,`END=${Math.round(r.end*1e3)}`,`title=${yv(r.title)}`);return`${e.join(`
266
+ `,ZS=5e3,To=null;function tm(){if(To&&Date.now()-To.at<ZS)return To.outputs;let t=ct(QS,"DXGI outputs").then(VS);return To={at:Date.now(),outputs:t},t.catch(()=>{To=null}),t}var Kd=t=>t-t%2;function rm(t,e){let r=a=>t.x>=a.x&&t.y>=a.y&&t.x+t.w<=a.x+a.w&&t.y+t.h<=a.y+a.h,n=e.find(r);if(!n)throw new l(`backend "ddagrab" captures one display, and ${t.x},${t.y} ${t.w}x${t.h} is not inside a single one.`,'Use a monitor:<i> target, a region inside one display, or backend "gdigrab".');if(n.adapter!==0)throw new l(`That display (${n.name||`adapter ${n.adapter} output ${n.output}`}) is driven by a second GPU, which ddagrab cannot reach.`,'Use backend "gdigrab" for it.');let o=Kd(t.w),i=Kd(t.h);if(o<=0||i<=0)throw new l("The capture rectangle is too small to record (needs at least 2x2 px).");return t.x===n.x&&t.y===n.y&&o===n.w&&i===n.h?{output:n.output}:{output:n.output,crop:{x:t.x-n.x,y:t.y-n.y,w:o,h:i}}}function nm(t,e,r){let n=t.crop?`:offset_x=${t.crop.x}:offset_y=${t.crop.y}:video_size=${t.crop.w}x${t.crop.h}`:"",o=r.drawMouse===!1?0:1;return["-f","lavfi","-i",`ddagrab=output_idx=${t.output}:framerate=${e}:draw_mouse=${o}${n}${r.download?",hwdownload,format=bgra":""}`]}import{spawnSync as Gc}from"node:child_process";import{readFileSync as rs,writeFileSync as im,renameSync as sm,existsSync as ev,copyFileSync as tv,openSync as rv,closeSync as nv,unlinkSync as am,statSync as cm,linkSync as ov}from"node:fs";import{basename as iv}from"node:path";var sv=100;function kn(t){return t==="recording"||t==="paused"}function av(t,e){return t.status==="paused"?{status:"stopped",reaped:!1}:t.status!=="recording"?{status:t.status,reaped:!1}:e?{status:"orphaned",reaped:!0}:{status:"stopped",reaped:!1}}function um(t,e,r){return kn(t.status)&&t.serverPid!==void 0&&t.serverPid!==e&&r}function lm(t,e,r){return t.backend==="wgc"||!um(t,e,r)?null:`Recording ${t.id} belongs to another running screencast-mcp instance (pid ${t.serverPid}). Stop it from the client connected to that instance; closing that instance also finalizes it.`}function qc(t,e=new Map){let r=t.serverPid;return r===void 0||r===process.pid||!Ge(r)?!1:(e.has(r)||e.set(r,mm(r)),cv(t,e.get(r)??null))}function pm(){return{serverPid:process.pid,serverStartedAt:new Date(Date.now()-process.uptime()*1e3).toISOString(),serverImage:iv(process.execPath).toLowerCase()}}var dm=5e3;function cv(t,e){if(!e)return!0;if(t.serverImage&&e.image.toLowerCase()!==t.serverImage.toLowerCase())return!1;let r=Date.parse(t.serverStartedAt??t.startedAt);return!(Number.isFinite(r)&&e.startMs>r+dm)}function uv(t){let e=/^(.+)\|(\d+)\s*$/m.exec(t.trim());return e?.[1]&&e[2]?{image:e[1].trim(),startMs:Number(e[2])}:null}function mm(t){if(process.platform!=="win32"||!Number.isInteger(t)||t<=0)return null;let e=`$p = Get-CimInstance Win32_Process -Filter "ProcessId=${t}"; if ($p) { "{0}|{1}" -f $p.Name, ([DateTimeOffset]$p.CreationDate).ToUnixTimeMilliseconds() }`,r=Gc("powershell",["-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",windowsHide:!0,timeout:1e4,killSignal:"SIGKILL"});return r.status===0&&r.stdout?uv(r.stdout):null}function Ge(t){if(t===null||!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function fm(t){return t.processImage??(t.backend==="wgc"?"node.exe":"ffmpeg.exe")}function lv(t,e){return(t.split(/\r?\n/)[0]??"").toLowerCase().startsWith(`"${e.toLowerCase()}"`)}function pv(t,e){if(t===null||process.platform!=="win32")return!1;let r=Gc("tasklist",["/FI",`PID eq ${t}`,"/FO","CSV","/NH"],{encoding:"utf8",windowsHide:!0});return r.status!==0||!r.stdout?!1:lv(r.stdout,e)}function dv(t,e){if(!e)return!0;if(e.image.toLowerCase()!==fm(t).toLowerCase())return!1;let r=t.pidSpawnedAt;return!(typeof r=="number"&&Number.isFinite(r)&&e.startMs>r+dm)}function Xc(t){return t.pid===null||!pv(t.pid,fm(t))?!1:t.pidSpawnedAt===void 0||dv(t,mm(t.pid))}function hm(t){let{code:e,backend:r,maxDurationSec:n,elapsedMs:o}=t;return r==="wgc"&&e===Xd?{status:"stopped",endReason:"window_closed"}:e!==0&&e!==null?{status:"failed",endReason:"crashed"}:{status:"stopped",endReason:n>0&&o>=n*1e3-2e3?"max_duration":"stopped"}}function mr(t){if(process.platform==="win32")Gc("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0});else try{process.kill(t,"SIGKILL")}catch{}}function Hc(t){let e=t.filter(n=>kn(n.status)),r=t.filter(n=>!kn(n.status)).sort((n,o)=>n.startedAt<o.startedAt?1:-1).slice(0,sv);return[...e,...r]}var mv=3e4,gm=15e3;function fv(t,e,r){return!t||typeof t.at!="number"||e-t.at>mv?!0:typeof t.pid=="number"&&!r}function bm(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function hv(t,e){let r=Date.now()+1e3;for(;;)try{sm(t,e);return}catch(n){let o=n.code;if(o!=="EPERM"&&o!=="EBUSY"&&o!=="EACCES"||Date.now()>=r)throw n;bm(15)}}function gv(t,e){let r=`${t}.${process.pid}.${Date.now()}.stale`;try{sm(t,r)}catch{return!1}let n=!0;try{rs(r,"utf8")!==e&&(n=!1,ov(r,t))}catch{}try{am(r)}catch{}return n}function om(t,e,r=gm){let n=`${t}.lock`,o=Date.now()+r,i,s;for(let a=0;;a++)try{let c=rv(n,"wx");s=JSON.stringify({pid:process.pid,at:Date.now(),nonce:Math.random().toString(36).slice(2)}),im(c,s),nv(c);break}catch(c){let u=c.code;if(!(u==="EEXIST"||u==="EPERM"||u==="EACCES"||u==="EBUSY"))throw new l(`Could not lock the session registry (${n}): ${z(c)}`);if(u==="EEXIST"){let p;try{let f=rs(n,"utf8"),m;try{m=JSON.parse(f)}catch{m={at:cm(n).mtimeMs}}p={raw:f,holder:m}}catch{p=null}if(p&&(i=p.holder?.pid,fv(p.holder,Date.now(),Ge(p.holder?.pid??null))&&gv(n,p.raw)))continue}if(Date.now()>=o)throw new l(`The session registry is busy: could not take ${n} within ${r/1e3} s${i!==void 0?` (held by process ${i})`:""}. Nothing was written.`,"Another screencast-mcp server is writing to the same registry. Retry; if no other server is running, delete the .lock file.");bm(Math.min(50,2**Math.min(a,6))*(.5+Math.random()))}try{return e()}finally{try{rs(n,"utf8")===s&&am(n)}catch{}}}var ns=class{constructor(e,r=gm){this.path=e;this.lockWaitMs=r}path;lockWaitMs;records=new Map;pending=new Map;removed=new Set;seen=null;children=new Map;stopping=new Set;listeners=[];onChange(e){this.listeners.push(e)}readDisk(){if(!ev(this.path))return new Map;try{return this.parseDisk()}catch{try{tv(this.path,`${this.path}.bak`),process.stderr.write(`Session registry was unreadable; saved a copy to ${this.path}.bak and starting fresh.
267
+ `)}catch{}return new Map}}parseDisk(){let e=JSON.parse(rs(this.path,"utf8"));return new Map(e.map(r=>[r.id,r]))}signature(){try{let e=cm(this.path,{bigint:!0});return`${e.ino}:${e.size}:${e.mtimeNs}`}catch{return null}}overlay(e){for(let[r,n]of this.pending){let o=e.get(r)??this.records.get(r);o&&e.set(r,{...o,...n})}for(let r of this.removed)e.delete(r);return e}refresh(){let e=this.signature();if(e===this.seen)return;let r;try{r=e===null?new Map:this.parseDisk()}catch{return}this.seen=e,this.records=new Map(Hc([...this.overlay(r).values()]).map(n=>[n.id,n]))}load(){let e=()=>{let n=this.readDisk();return this.seen=this.signature(),n},r;try{r=om(this.path,e,this.lockWaitMs)}catch(n){process.stderr.write(`${z(n)} Reading the session registry without the lock.
268
+ `),r=e()}this.records=new Map(Hc([...this.overlay(r).values()]).map(n=>[n.id,n]))}persist(){om(this.path,()=>{let e=Hc([...this.overlay(this.readDisk()).values()]),r=`${this.path}.${process.pid}.tmp`;im(r,JSON.stringify(e,null,2)),hv(r,this.path),this.seen=this.signature(),this.records=new Map(e.map(n=>[n.id,n])),this.pending.clear(),this.removed.clear()},this.lockWaitMs);for(let e of this.listeners)try{e()}catch{}}create(e){this.records.set(e.id,e),this.pending.set(e.id,e);try{this.persist()}catch(r){throw this.records.delete(e.id),this.pending.delete(e.id),r}}remove(e){let r=e.flatMap(n=>{let o=this.records.get(n);return o?[o]:[]});for(let n of e)this.removed.add(n),this.pending.delete(n),this.records.delete(n);try{this.persist()}catch(n){for(let o of e)this.removed.delete(o);for(let o of r)this.records.set(o.id,o);throw n}}get(e){return this.refresh(),this.records.get(e)}list(){return this.refresh(),[...this.records.values()].sort((e,r)=>e.startedAt<r.startedAt?1:-1)}update(e,r){let n=this.records.get(e);if(n||(this.refresh(),n=this.records.get(e)),!n)return;let o={...n,...r};return this.records.set(e,o),this.pending.set(e,{...this.pending.get(e),...r}),this.persist(),this.records.get(e)??o}tryUpdate(e,r){try{return this.update(e,r)}catch(n){process.stderr.write(`Could not save session ${e}: ${z(n)}
269
+ `);return}}attachChild(e,r){this.children.set(e,r)}getChild(e){return this.children.get(e)}detachChild(e,r){r&&this.children.get(e)!==r||this.children.delete(e)}activeIds(){return[...[...this.children.keys()].filter(e=>this.records.get(e)?.status==="recording"),...[...this.paused].filter(e=>this.records.get(e)?.status==="paused"&&!this.children.has(e))]}paused=new Set;markPaused(e){this.paused.add(e)}ownsPaused(e){return this.paused.has(e)}clearPaused(e){this.paused.delete(e)}markStopping(e){this.stopping.add(e)}isStopping(e){return this.stopping.has(e)}clearStopping(e){this.stopping.delete(e)}reapOrphans(){this.refresh();let e=[],r=new Map;for(let n of this.records.values()){if(!kn(n.status)||um(n,process.pid,qc(n,r)))continue;let o=Ge(n.pid),i=av(n,o);i.reaped&&n.pid!==null&&(Xc(n)&&mr(n.pid),e.push(n.id));let s={status:i.status,...n.stoppedAt?{}:{stoppedAt:new Date().toISOString()},...i.status==="orphaned"?{error:"Reaped on server restart (recording was interrupted)."}:{},...n.status==="paused"?{endReason:"shutdown",error:`The server exited while this recording was paused; its parts were not joined (${n.segments?.parts.map(a=>a.path).join(", ")??n.outputPath}).`}:{},...n.status==="recording"&&(n.segments?.parts.length??0)>0?{endReason:"shutdown",error:`The server exited before this recording's segments were joined; ${n.outputPath} holds only the first one. The parts: ${[...n.segments?.parts.map(a=>a.path)??[],...n.segments?.current?[n.segments.current.path]:[]].join(", ")}.`}:{}};this.records.set(n.id,{...n,...s}),this.pending.set(n.id,{...this.pending.get(n.id),...s})}return this.records.size>0&&this.persist(),e}};async function Jc(t,e){let r=Date.now()+e;for(;Date.now()<r&&Ge(t);)await new Promise(n=>setTimeout(n,100))}function wm(t,e){return new Promise(r=>{if(t.exitCode!==null||t.signalCode!==null)return r(!0);let n=setTimeout(()=>r(!1),e);t.once("exit",()=>{clearTimeout(n),r(!0)})})}async function Sm(t,e,r){if(!t.stdin||!t.stdin.writable)return!1;t.stdin.write(`q
270
+ `),t.stdin.end();let n=await wm(t,r);return!n&&e!==null&&(mr(e),await Jc(e,2e3),await wm(t,2e3)),n}async function wv(t,e){let r=t.segments;if(!r)return[];let n=[...r.parts];if(r.current){let o=await ue(r.current.path,{ffprobe:e}),i=t.stoppedAt?Date.parse(t.stoppedAt):Date.now(),s=Fc(r.current.path,o,r.current.startMs,i)??0;n.push({...r.current,durationSec:s})}return n}function yv(t){let e=t.segments;return!!e&&(e.parts.length>0||!!t.webcam)}async function Kc(t,e){let r=await wv(t,e.ffprobe),n=await gd(t.outputPath,r,{ffmpeg:e.ffmpeg,webcamOutput:t.webcam?zr(t.outputPath):void 0,webcamCodec:dr(t.encoder??"x264",t.quality,{gpuFrames:!1})});return{patch:{segments:{parts:r},...t.webcam?{webcam:{...t.webcam,error:n.webcamError}}:{}},count:r.length,error:n.error}}var Yc=new WeakMap;function xv(t,e){return Yc.get(t)?.get(e)?.kind??null}function os(t,e,r){let n=xv(t,e);if(n&&n!==r)throw new l(`Cannot ${r} ${e}: a ${n} of it is in progress.`,"Retry once it finishes (get_session shows the session's status).")}function is(t,e,r,n,o={}){let i=Yc.get(t);i||Yc.set(t,i=new Map);let s=i.get(e);if(s?.kind===r)return s.promise;if(s&&!o.queue)return Promise.reject(new l(`Cannot ${r} ${e}: a ${s.kind} of it is in progress.`,"Retry once it finishes (get_session shows the session's status)."));let a;if(s)a=s.promise.then(()=>n(!0),()=>n(!0));else try{a=n(!1)}catch(d){a=Promise.reject(d)}let c=i,u=a.finally(()=>{c.get(e)?.promise===u&&c.delete(e)});return c.set(e,{kind:r,promise:u}),u}function vm(t,e,r){return is(t,e.id,"pause",()=>Sv(t,t.get(e.id)??e,r))}async function Sv(t,e,r){let n=t.getChild(e.id),o=ld(e,!!n);if(o)throw new l(`Cannot pause ${e.id}: ${o}.`);dd(e.id),t.markStopping(e.id);try{let i=Date.now(),s=await Sm(n,e.pid,r.gracefulMs??8e3);t.detachChild(e.id,n);let a=e.segments.current,c=await r.probe(a.path),u=Fc(a.path,c,a.startMs,i)??0,d=e.segments.parts,p=u>0?[...d,{...a,durationSec:u}]:d;return u<=0&&a.path!==e.outputPath&&xm(a.path,{force:!0}),t.markPaused(e.id),{record:t.update(e.id,{status:"paused",pid:null,segments:{parts:p}}),recordedSec:ot(p),segmentSec:u,graceful:s}}finally{fd(e.id),t.clearStopping(e.id)}}async function $m(t,e,r=1e4){let n=t.activeIds(),o=n.map(async a=>{let c=t.get(a);if(c)try{await Ro(t,c,{reason:"shutdown",probe:e,gracefulMs:Math.min(8e3,r)})}catch(u){process.stderr.write(`Stopping ${a} on shutdown failed: ${z(u)}
271
+ `)}}),i,s=new Promise(a=>{i=setTimeout(a,r)});return await Promise.race([Promise.allSettled(o),s]),clearTimeout(i),n}function Ro(t,e,r){return is(t,e.id,"stop",async n=>{if(!n)return ym(t,e,r);let o=t.get(e.id)??e;return o.status!=="recording"&&o.status!=="paused"?{record:o,graceful:!0,durationSec:o.durationSec??null}:ym(t,o,r)},{queue:!0})}async function ym(t,e,r){t.markStopping(e.id);let n=e.backend==="wgc"?Qi(e.outputPath):null;try{let o=!1,i=t.getChild(e.id),s=f=>new l(`Could not stop recording ${e.id}: its process (pid ${f}) is still running.`);if(i&&i.stdin&&i.stdin.writable){if(o=await Sm(i,e.pid,r.gracefulMs??8e3),!o&&e.pid!==null&&Ge(e.pid))throw s(e.pid)}else if(e.pid!==null&&Ge(e.pid)&&Xc(e)&&(n&&(bv(n,""),await Jc(e.pid,r.gracefulMs??8e3),o=!Ge(e.pid)),Ge(e.pid)&&(mr(e.pid),await Jc(e.pid,2e3)),Ge(e.pid)))throw s(e.pid);t.detachChild(e.id,i),e.status==="paused"&&(o=!0),Gi(e.id),t.clearPaused(e.id),await Zt(e.id);let a,c={};if(yv(e)){let f=await Kc(e,k());c=f.patch,a={count:f.count,...f.error?{error:f.error}:{}}}let u=e.replay?await Vi(e.replay,{save:r.saveReplay??!1,output:e.outputPath,quality:e.quality,tools:k}):void 0,d=await r.probe(e.outputPath);return{record:t.update(e.id,{...c,status:"stopped",stoppedAt:new Date().toISOString(),durationSec:d??void 0,endReason:r.reason,error:a?.error}),graceful:o,durationSec:d,...u?{replay:u}:{},...a?{segments:a}:{}}}finally{n&&xm(n,{force:!0}),t.clearStopping(e.id)}}import{existsSync as $v,readFileSync as kv,renameSync as Ev,writeFileSync as _v}from"node:fs";var ss=t=>Math.round(t*1e3)/1e3;function Ao(t,e){let r=0;for(let n of e){if(t<=n.start)break;r+=(Math.min(t,n.end)-n.start)*(n.factor?1-1/n.factor:1)}return r}function as(t,e){let r=t;for(let n of e)if(n.op==="trim"){if(r<n.start||r>=n.end)return null;r-=n.start}else n.op==="speed"?r/=n.factor:r-=Ao(r,n.spans);return r}function Gr(t,e,r){let n=t,o=e;for(let i of r)if(i.op==="trim"?(n=Math.max(n,i.start)-i.start,o=Math.min(o,i.end)-i.start):i.op==="speed"?(n/=i.factor,o/=i.factor):(n-=Ao(n,i.spans),o-=Ao(o,i.spans)),o<=n)return null;return[n,o]}function _m(t,e){return t.flatMap(r=>{let n=Gr(r.start,r.end,e);return n?[{start:ss(n[0]),end:ss(n[1])}]:[]})}function cs(t,e){return t.flatMap(r=>{let n=Gr(r.start,r.end,e);return n&&n[1]-n[0]>=.05?[{...r,start:ss(n[0]),end:ss(n[1])}]:[]})}var vv=/^(\d+):(\d{2}):(\d{2})\.(\d{2})$/,km=t=>{let e=t.trim().match(vv);return e?Number(e[1])*3600+Number(e[2])*60+Number(e[3])+Number(e[4])/100:null},Em=t=>{let e=Math.round(t*100),r=n=>String(n).padStart(2,"0");return`${Math.floor(e/36e4)}:${r(Math.floor(e%36e4/6e3))}:${r(Math.floor(e%6e3/100))}.${r(e%100)}`};function Tm(t,e){return t.split(/\r?\n/).flatMap(r=>{let n=r.match(/^(Dialogue:\s*[^,]*,)([^,]*),([^,]*),(.*)$/);if(!n)return[r];let[,o,i,s,a]=n,c=km(i),u=km(s);if(c===null||u===null)return[r];let d=Gr(c,u,e);return d&&d[1]-d[0]>=.05?[`${o}${Em(d[0])},${Em(d[1])},${a}`]:[]}).join(`
272
+ `)}var Rm=500,Vc=200,Am=3,En=10,Ot=t=>Math.round(t*1e3)/1e3;function fr(t){return`${t.replace(/\.[^./\\]+$/,"")}.markers.json`}function Mm(t,e){return Math.max(0,Ot((e-t)/1e3))}function Mo(t,e=Vc){let r=t.replace(/\s+/g," ").trim();return r.length>e?`${r.slice(0,e-1).trimEnd()}\u2026`:r}function ls(t,e){if(t.length>=Rm)throw new l(`A recording holds at most ${Rm} markers.`);let r=Mo(e.label);if(!r)throw new l("A marker needs a non-empty label.");if(!Number.isFinite(e.t)||e.t<0)throw new l("A marker time must be a non-negative number of seconds.");let n={...e,t:Ot(e.t),label:r},o=t.findIndex(i=>i.t>n.t);return o===-1?[...t,n]:[...t.slice(0,o),n,...t.slice(o)]}function Tv(t){let e=t;return!!e&&typeof e.t=="number"&&Number.isFinite(e.t)&&e.t>=0&&typeof e.label=="string"}function Rv(t){let e;try{e=JSON.parse(t)}catch{return[]}let r=Array.isArray(e)?e:e?.markers;return Array.isArray(r)?r.filter(Tv).sort((n,o)=>n.t-o.t):[]}function We(t){let e=fr(t);if(!$v(e))return[];try{return Rv(kv(e,"utf8"))}catch{return[]}}function hr(t,e,r){let n=fr(t),o=`${n}.${process.pid}.tmp`;return _v(o,JSON.stringify({...r?{sessionId:r}:{},markers:e},null,2)),Ev(o,n),n}function Cm(t,e){let r=[...t].sort((n,o)=>n.t-o.t);for(let n of e){if(n.op==="speed"){r=r.map(s=>({...s,t:Ot(s.t/n.factor)}));continue}if(n.op==="cut"){r=r.map(s=>({...s,t:Ot(s.t-Ao(s.t,n.spans))}));continue}let o=r.filter(s=>s.t>=n.start&&s.t<n.end).map(s=>({...s,t:Ot(s.t-n.start)})),i=r.filter(s=>s.t<n.start).at(-1);r=i&&!o.some(s=>s.t<.001)?[{...i,t:0},...o]:o}return r}function ps(t,e,r={}){let n=Math.max(.001,r.minChapterSec??1),o=t.filter(a=>Number.isFinite(a.start)&&a.start>=0&&a.start<e).map((a,c)=>({start:Ot(a.start),title:Mo(a.title,100)||`Chapter ${c+1}`})).sort((a,c)=>a.start-c.start),i=[];for(let a of o){let c=i.at(-1);c?a.start-c.start>=n&&i.push(a):a.start<n?i.push({...a,start:0}):i.push({start:0,title:r.introTitle??"Intro"},a)}let s=i.at(-1);return i.length>1&&s&&e-s.start<n&&i.pop(),i.map((a,c)=>({start:a.start,end:Ot(i[c+1]?.start??e),title:a.title}))}function Av(t,e){let r=Math.max(0,Math.floor(t)),n=Math.floor(r/3600),o=Math.floor(r%3600/60),i=String(r%60).padStart(2,"0");return e?`${n}:${String(o).padStart(2,"0")}:${i}`:`${Math.floor(r/60)}:${i}`}function Pm(t,e){let r=e>=3600,n=t.map(s=>`${Av(s.start,r)} ${s.title}`).join(`
273
+ `),o=[];t.length<Am&&o.push(`YouTube needs at least ${Am} chapters; there are ${t.length}.`),t[0]&&t[0].start!==0&&o.push("YouTube needs the first chapter at 0:00.");let i=t.filter(s=>s.end-s.start<En);return i.length>0&&o.push(`YouTube needs every chapter to be at least ${En} s long; ${i.length} ${i.length===1?"is":"are"} shorter (${i.map(s=>`"${s.title}"`).join(", ")}). Raise minChapterSec to ${En} to merge them.`),{text:n,issues:o}}function Mv(t){return t.replace(/[=;#\\\n]/g,e=>`\\${e}`)}function ds(t){let e=[";FFMETADATA1"];for(let r of t)e.push("[CHAPTER]","TIMEBASE=1/1000",`START=${Math.round(r.start*1e3)}`,`END=${Math.round(r.end*1e3)}`,`title=${Mv(r.title)}`);return`${e.join(`
274
274
  `)}
275
- `}function ds(t){return t.map(e=>({start:e.t,title:e.label}))}function Cm(t,e,r){let n=[0];for(let o of[...t].sort((i,s)=>s.score-i.score)){if(n.length>=r)break;n.every(i=>Math.abs(i-o.timeSec)>=e)&&n.push(o.timeSec)}return n.sort((o,i)=>o-i).map((o,i)=>({start:o,title:`Scene ${i+1}`}))}function xv(t,e=60){let r=t.replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();if(r.length<=e)return r;let n=r.slice(0,e),o=n.lastIndexOf(" ");return`${(o>e/2?n.slice(0,o):n).trimEnd()}\u2026`}function Pm(t,e={}){let r=e.gapSec??2,n=e.minChapterSec??30,o=[...t].sort((a,c)=>a.start-c.start),i=[],s=-1/0;for(let a of o){let c=i.at(-1);(!c||a.start-s>=r&&a.start-c.start>=n)&&i.push({start:a.start,title:xv(a.text)}),s=Math.max(s,a.end)}return i}var cs=8;function Im(t,e,r,n){let o=n.subtitles??[];if(o.length>cs)throw new l(`At most ${cs} subtitle tracks.`);return["-y","-i",t,"-f","ffmetadata","-i",e,...o.flatMap(i=>["-i",i.file]),"-map","0:v","-map","0:a?",...o.length?o.flatMap((i,s)=>["-map",`${s+2}:s:0`]):["-map","0:s?"],"-map_metadata","0","-map_chapters","1","-c","copy",...o.length?["-c:s",n.container===".mkv"?"copy":"mov_text"]:[],...o.flatMap((i,s)=>[...i.language?[`-metadata:s:s:${s}`,`language=${i.language}`]:[],...i.title?[`-metadata:s:s:${s}`,`title=${i.title}`]:[],...o.length>1||i.default!==void 0?[`-disposition:s:${s}`,i.default?"default":"0"]:[]]),...n.container===".mkv"?[]:["-movflags","+faststart"],r]}function Sv(t){return["-v","quiet","-print_format","json","-show_chapters",t]}function vv(t){let e;try{e=JSON.parse(t)}catch{return[]}return(e.chapters??[]).flatMap((r,n)=>{let o=Number(r.start_time),i=Number(r.end_time);return!Number.isFinite(o)||!Number.isFinite(i)?[]:[{start:It(o),end:It(i),title:r.tags?.title??`Chapter ${n+1}`}]})}async function $v(t,e){let{ffprobe:r}=k(),n=await ne(r,Sv(t),3e4,{signal:e});return n.code===0?vv(n.stdout):[]}async function mr(t,e){let r=Le(t);if(r.length>0)return{markers:r,from:"sidecar"};let n=await $v(t,e);return n.length>0?{markers:n.map(o=>({t:o.start,label:o.title})),from:"chapters"}:{markers:[],from:null}}function ms(t,e,r,n){let o=t.get(e);if(!o)throw new l(`No session with id "${e}".`);let i=n;if(i===void 0&&o.status==="paused")i=rt(o.segments?.parts??[]);else if(i===void 0){if(o.status!=="recording")throw new l(`Session "${e}" is ${o.status}, so there is no "now" to mark.`,"Pass at (video seconds) to mark a stopped recording.");i=Am(o.videoStartMs??Date.parse(o.startedAt),Date.now())}else if(o.durationSec!=null&&i>o.durationSec)throw new l(`at ${i}s is past the end of the recording (${o.durationSec}s).`);let s={t:i,label:r,at:new Date().toISOString()},a=us(o.markers??[],s);t.update(e,{markers:a});let c=pr(o.outputPath),u;try{c=dr(o.outputPath,a,e)}catch(d){u=`Saved in the session, but the sidecar ${c} could not be written: ${U(d)}`}return{t:i,count:a.length,markersPath:c,live:o.status==="recording"||o.status==="paused",...u?{warning:u}:{}}}import{existsSync as kv,readFileSync as Ev}from"node:fs";import{dirname as Fm,join as fs}from"node:path";import{fileURLToPath as _v}from"node:url";var Om="@tmhs/screencast-mcp",Vc=null,Tv=null;function Nm(t){try{return JSON.parse(Ev(t,"utf8"))}catch{return null}}function Av(t){for(let e=t;;){let r=fs(e,"package.json");if(kv(r)&&Nm(r)?.name===Om)return e;let n=Fm(e);if(n===e)return null;e=n}}function Qc(){if(Vc)return Vc;let t=Av(Fm(_v(import.meta.url)));if(!t)throw new l(`Cannot find the ${Om} package root (its package.json).`);return Vc=t}function wt(){return Tv??=Nm(fs(Qc(),"package.json"))?.version??"0.0.0"}function vn(...t){return fs(Qc(),"assets",...t)}function Dm(){return fs(Qc(),"dist","wgcRecorder.js")}async function at(t,e={}){let r=gp(t);if(r.kind==="window"){let n=await Sd(r.title,{exactOnly:e.exactTitle,allowCloaked:e.backend==="wgc"});return{target:{kind:"region",x:n.x,y:n.y,w:n.width,h:n.height},monitors:[],window:n}}return r.kind==="monitor"?{target:r,monitors:await ar()}:r.kind==="region"?(wp(r,await ar()),{target:r,monitors:[]}):{target:r,monitors:await ar()}}var Rv=["virtual-audio-capturer","stereo mix","what u hear","wave out mix","cable output","voicemeeter output"],Mo="System audio capture needs a virtual-audio loopback device, which Windows does not provide natively. Enable 'Stereo Mix' in Sound settings, or install a loopback driver (for example screen-capture-recorder's virtual-audio-capturer, or VB-CABLE). Then pass its name as `device`, or run list_audio_devices to see what is available. Microphone capture is not supported.";function Mv(t){return Lm(t,"audio")}function Cv(t){return Lm(t,"video")}function Lm(t,e){let r=[],n=null;for(let o of t.split(/\r?\n/)){if(/DirectShow audio devices/i.test(o)){n="audio";continue}if(/DirectShow video devices/i.test(o)){n="video";continue}if(/Alternative name/i.test(o))continue;let i=o.match(/"([^"]+)"/);if(!i)continue;let s=/\(audio\)/i.test(o),a=/\(video\)/i.test(o);(e==="audio"?s||!a&&n==="audio":a||!s&&n==="video")&&i[1]&&r.push(i[1])}return[...new Set(r)]}function Zc(t,e){if(e&&e.trim().length>0)return t.includes(e)?e:null;let r=n=>n.toLowerCase();return t.find(n=>Rv.some(o=>r(n).includes(o)))??null}var Pv=12e3,Iv="Enumerating DirectShow audio devices timed out or failed - usually a misbehaving audio driver, or no audio device present. Record without system audio, or fix the device, then retry. "+Mo,hs=null,gs=null;async function eu(t=!1){return!t&&hs?hs:(await Wm(),hs??[])}async function tu(t=!1){return!t&&gs?gs:(await Wm(),gs??[])}async function Bm(t){let e=await tu();if(t&&t.trim().length>0){if(e.includes(t))return t;throw new l(`Video device "${t}" not found. Available dshow video devices: ${e.join(", ")||"none"}.`)}let r=e[0];if(!r)throw new l("No webcam (dshow video device) found.","Connect a camera, then run list_video_devices.");return r}async function Wm(){let{ffmpeg:t}=k(),e;try{e=await ne(t,["-hide_banner","-list_devices","true","-f","dshow","-i","dummy"],Pv)}catch(r){throw new l(`Could not enumerate audio devices (${U(r)}).`,Iv)}hs=Mv(e.stderr),gs=Cv(e.stderr)}async function jm(t){let e=await eu(),r=Zc(e,t);if(r)return r;if(t&&t.trim().length>0){let n=e.length>0?e.join(", "):"none";throw new l(`Audio device "${t}" not found. Available dshow audio devices: ${n}.`,Mo)}throw new l("No system-audio loopback device found.",Mo)}var Co="SCREENCAST_CONFIRM_CAPTURE",ru=300*1e3;function Um(t=process.env){let e=(t[Co]??"").trim().toLowerCase();return["1","true","yes","on","always"].includes(e)?"always":["0","false","no","off","never"].includes(e)?"off":"auto"}function zm(t=process.env){return Um(t)==="always"}function Ft(t,e){return e?`window "${e.matchedTitle}"`:t==="full"?"the full screen (all monitors)":t}async function Ot(t,e,r){let n=Um();if(n==="off")return;if(!t.server.getClientCapabilities()?.elicitation?.form){if(n==="auto")return;throw new l(`Capture blocked: ${Co} requires the user to confirm each capture, but this client does not support MCP elicitation. Nothing was captured.`,`Use a client that supports elicitation, or set ${Co}=auto to capture without confirmation in clients that cannot ask.`)}let o;try{({action:o}=await t.server.elicitInput({message:e,requestedSchema:{type:"object",properties:{}}},{signal:r,timeout:ru}))}catch(i){throw new l(`Capture blocked: the confirmation request failed (${U(i)}). Nothing was captured.`)}if(o!=="accept")throw new l(`Capture ${o==="decline"?"declined":"cancelled"} by the user. Nothing was captured.`)}var bs=null;function re(){return bs||(bs=new rs(pp()),bs.load()),bs}var ou=!1;function Hm(){ou=!0}function ys(){return ou}var ws=0,nu=[];function Gm(){if(ou)throw new l("The server is shutting down; the recording was not started.");ws++;let t=!1;return()=>{if(!t&&(t=!0,ws--,ws===0)){let e=nu;nu=[];for(let r of e)r()}}}function qm(t){return ws===0?Promise.resolve(!0):new Promise(e=>{let r=setTimeout(()=>e(!1),t);r.unref?.(),nu.push(()=>{clearTimeout(r),e(!0)})})}import{existsSync as y0,mkdirSync as x0,mkdtempSync as S0,rmSync as yu,writeFileSync as bf}from"node:fs";import{tmpdir as v0}from"node:os";import{spawn as Fv}from"node:child_process";var Xm=15e3;async function Nt(t,e,r="gdigrab"){if(r==="gdigrab"){await Z(_i(t.target,e,t.monitors),6e4);return}let n=t.window?.hwnd;if(n===void 0)throw new l("backend 'wgc' captures a single window: use a window:<title> target.");if(!ir())throw new l("backend 'wgc' needs FFmpeg 8 or newer with the gfxcapture filter (Windows Graphics Capture).","Check with `ffmpeg -h filter=gfxcapture`. Recent Windows builds (e.g. `winget install Gyan.FFmpeg`) include it. Or use the default backend, which captures what is visible on screen.");let o=Fv("powershell",["-NoProfile","-NonInteractive","-Command",qd(n,100,process.pid)],{stdio:"ignore",windowsHide:!0});o.on("error",()=>{});try{await Z(Sp(n,e),Xm)}catch(i){throw i instanceof l&&/timed out/.test(i.message)?new l(`Windows Graphics Capture got no frame from the window in ${Xm/1e3} s.`,"The window may be hung or protected from capture. Try the default backend with the window in front."):i}finally{o.kill()}}import{join as su}from"node:path";import{readdirSync as Yv}from"node:fs";import{runInNewContext as Ov}from"node:vm";var Nv=[2,4],Dv=1e4;function Lv(t){return{script:qv,payload:JSON.stringify(t)}}async function Ym(t,e){if(process.platform!=="win32")throw new l("find_text uses the Windows OCR engine and runs on Windows only.");let{script:r,payload:n}=Lv(t),o=await st(r,"text (OCR)",{timeoutMs:sr(Hv+Math.max(0,t.length-2)*Gv),payload:n,failure:"Could not run OCR"}),i;try{i=JSON.parse(o)}catch(a){throw new l(`Could not parse OCR output: ${U(a)}`)}return(Array.isArray(i)?i:[i]).map((a,c)=>Bv(a,e[c]??1))}function Bv(t,e){let r=t??{};if(r.error)throw/language|recognizer/i.test(r.error)?new l(`Windows OCR is unavailable: ${r.error}`,"Install an OCR language: Settings > Time & language > Language > (your language) > Options > Optical character recognition."):new l(`OCR failed: ${r.error}`);let n=[];for(let o of r.lines??[]){let i=(Array.isArray(o.words)?o.words:o.words?[o.words]:[]).map(s=>({text:String(s.text??""),x:Math.round((s.x??0)/e),y:Math.round((s.y??0)/e),width:Math.max(1,Math.round((s.width??0)/e)),height:Math.max(1,Math.round((s.height??0)/e))}));i.length!==0&&n.push({text:String(o.text??i.map(s=>s.text).join(" ")),words:i,...Km(i)})}return n}function Km(t){let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,width:n-e,height:o-r}}function Wv(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),n=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);return r<=0||n<=0?0:r*n/Math.min(t.width*t.height,e.width*e.height)}function Vm(t){let e=[];for(let r of t)for(let n of r){let o=e.findIndex(s=>Wv(s,n)>.5),i=e[o];i?n.text.length>i.text.length&&(e[o]=n):e.push(n)}return e.sort((r,n)=>r.y-n.y||r.x-n.x)}function Dt(t){return t.toLowerCase().replace(/[-_\s]+/g,"_").replace(/[l1|]/g,"i").replace(/0/g,"o")}var jr=500,jv=1e3;function Qm(t,e){return t.map(r=>{let n=new RegExp(e,"gi"),o=new Set,i=[];for(let s of[r,r.replace(/-/g,"_"),r.replace(/_/g,"-")])for(let a of s.matchAll(n)){let c=`${a.index}:${a[0].length}`;a[0].length>0&&!o.has(c)&&(o.add(c),i.push([a.index,a.index+a[0].length]))}return i})}var Uv=`JSON.stringify((${Qm.toString()})(texts, query))`,Zm=new Set;function iu(t){return Zm.add(t),t}function $n(t,e,r=jv){try{new RegExp(e,"gi")}catch(n){throw new l(`Invalid regex: ${U(n)}`)}if(Zm.has(e))return Qm(t,e);try{return JSON.parse(Ov(Uv,{texts:t,query:e},{timeout:r}))}catch(n){throw n.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"?new l(`The regex took longer than ${r/1e3} s to run and was stopped.`,"Simplify it: nested quantifiers such as (a+)+ backtrack catastrophically."):n}}function yt(t,e,r=!1){if(e.length>jr)throw new l(`The query is ${e.length} characters; at most ${jr} are allowed.`);let n=t.map(s=>{let a=[],c="";for(let u of s.words)c&&(c+=" "),a.push({start:c.length,end:c.length+u.text.length,word:u}),c+=u.text;return{line:s,spans:a,text:c}}),o=r?$n(n.map(s=>s.text),e):null,i=[];return n.forEach(({line:s,spans:a},c)=>{let u=[];if(o)u=o[c]??[];else{let p=Dt(e);if(!p)return;let f=a.map(h=>Dt(h.word.text)).join("_"),m=0;for(let h=f.indexOf(p,m);h!==-1;h=f.indexOf(p,m))u.push(zv(a,h,h+p.length)),m=h+p.length}let d=new Set;for(let[p,f]of u){let m=a.filter(h=>h.start<f&&h.end>p).map(h=>h.word);m.length===0||m.every(h=>d.has(h))||(m.forEach(h=>d.add(h)),i.push({text:m.map(h=>h.text).join(" "),line:s.text,...Km(m)}))}}),i}function zv(t,e,r){let n=0,o=-1,i=-1;for(let s of t){let a=Dt(s.word.text).length;if(o===-1&&e<n+a&&(o=s.start),r<=n+a+1){i=s.end;break}n+=a+1}return[o===-1?0:o,i===-1?t.at(-1)?.end??0:i]}function xs(t,e,r=4){return t.map(n=>{let o=Math.max(0,n.x-r),i=Math.max(0,n.y-r);return{x:o,y:i,width:Math.min(e.width,n.x+n.width+r)-o,height:Math.min(e.height,n.y+n.height+r)-i}})}function ef(t,e){let r=Dv/Math.max(t,e),n=Nv.map(o=>Math.min(o,Math.floor(r*100)/100)).filter(o=>o>=1);return[...new Set(n.length?n:[Math.min(1,r)])]}var Hv=6e4,Gv=5e3,Jm=2e4,qv=`
275
+ `}function ms(t){return t.map(e=>({start:e.t,title:e.label}))}function Im(t,e,r){let n=[0];for(let o of[...t].sort((i,s)=>s.score-i.score)){if(n.length>=r)break;n.every(i=>Math.abs(i-o.timeSec)>=e)&&n.push(o.timeSec)}return n.sort((o,i)=>o-i).map((o,i)=>({start:o,title:`Scene ${i+1}`}))}function Cv(t,e=60){let r=t.replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim();if(r.length<=e)return r;let n=r.slice(0,e),o=n.lastIndexOf(" ");return`${(o>e/2?n.slice(0,o):n).trimEnd()}\u2026`}function Fm(t,e={}){let r=e.gapSec??2,n=e.minChapterSec??30,o=[...t].sort((a,c)=>a.start-c.start),i=[],s=-1/0;for(let a of o){let c=i.at(-1);(!c||a.start-s>=r&&a.start-c.start>=n)&&i.push({start:a.start,title:Cv(a.text)}),s=Math.max(s,a.end)}return i}var us=8;function Om(t,e,r,n){let o=n.subtitles??[];if(o.length>us)throw new l(`At most ${us} subtitle tracks.`);return["-y","-i",t,"-f","ffmetadata","-i",e,...o.flatMap(i=>["-i",i.file]),"-map","0:v","-map","0:a?",...o.length?o.flatMap((i,s)=>["-map",`${s+2}:s:0`]):["-map","0:s?"],"-map_metadata","0","-map_chapters","1","-c","copy",...o.length?["-c:s",n.container===".mkv"?"copy":"mov_text"]:[],...o.flatMap((i,s)=>[...i.language?[`-metadata:s:s:${s}`,`language=${i.language}`]:[],...i.title?[`-metadata:s:s:${s}`,`title=${i.title}`]:[],...o.length>1||i.default!==void 0?[`-disposition:s:${s}`,i.default?"default":"0"]:[]]),...n.container===".mkv"?[]:["-movflags","+faststart"],r]}function Pv(t){return["-v","quiet","-print_format","json","-show_chapters",t]}function Iv(t){let e;try{e=JSON.parse(t)}catch{return[]}return(e.chapters??[]).flatMap((r,n)=>{let o=Number(r.start_time),i=Number(r.end_time);return!Number.isFinite(o)||!Number.isFinite(i)?[]:[{start:Ot(o),end:Ot(i),title:r.tags?.title??`Chapter ${n+1}`}]})}async function Fv(t,e){let{ffprobe:r}=k(),n=await se(r,Pv(t),3e4,{signal:e});return n.code===0?Iv(n.stdout):[]}async function gr(t,e){let r=We(t);if(r.length>0)return{markers:r,from:"sidecar"};let n=await Fv(t,e);return n.length>0?{markers:n.map(o=>({t:o.start,label:o.title})),from:"chapters"}:{markers:[],from:null}}function fs(t,e,r,n){let o=t.get(e);if(!o)throw new l(`No session with id "${e}".`);let i=n;if(i===void 0&&o.status==="paused")i=ot(o.segments?.parts??[]);else if(i===void 0){if(o.status!=="recording")throw new l(`Session "${e}" is ${o.status}, so there is no "now" to mark.`,"Pass at (video seconds) to mark a stopped recording.");i=Mm(o.videoStartMs??Date.parse(o.startedAt),Date.now())}else if(o.durationSec!=null&&i>o.durationSec)throw new l(`at ${i}s is past the end of the recording (${o.durationSec}s).`);let s={t:i,label:r,at:new Date().toISOString()},a=ls(o.markers??[],s);t.update(e,{markers:a});let c=fr(o.outputPath),u;try{c=hr(o.outputPath,a,e)}catch(d){u=`Saved in the session, but the sidecar ${c} could not be written: ${z(d)}`}return{t:i,count:a.length,markersPath:c,live:o.status==="recording"||o.status==="paused",...u?{warning:u}:{}}}import{existsSync as Ov,readFileSync as Nv}from"node:fs";import{dirname as Nm,join as hs}from"node:path";import{fileURLToPath as Dv}from"node:url";var Dm="@tmhs/screencast-mcp",Qc=null,Lv=null;function Lm(t){try{return JSON.parse(Nv(t,"utf8"))}catch{return null}}function Bv(t){for(let e=t;;){let r=hs(e,"package.json");if(Ov(r)&&Lm(r)?.name===Dm)return e;let n=Nm(e);if(n===e)return null;e=n}}function Zc(){if(Qc)return Qc;let t=Bv(Nm(Dv(import.meta.url)));if(!t)throw new l(`Cannot find the ${Dm} package root (its package.json).`);return Qc=t}function xt(){return Lv??=Lm(hs(Zc(),"package.json"))?.version??"0.0.0"}function _n(...t){return hs(Zc(),"assets",...t)}function Bm(){return hs(Zc(),"dist","wgcRecorder.js")}async function ut(t,e={}){let r=wp(t);if(r.kind==="window"){let n=await $d(r.title,{exactOnly:e.exactTitle,allowCloaked:e.backend==="wgc"});return{target:{kind:"region",x:n.x,y:n.y,w:n.width,h:n.height},monitors:[],window:n}}return r.kind==="monitor"?{target:r,monitors:await lr()}:r.kind==="region"?(xp(r,await lr()),{target:r,monitors:[]}):{target:r,monitors:await lr()}}var Wv=["virtual-audio-capturer","stereo mix","what u hear","wave out mix","cable output","voicemeeter output"],Co="System audio capture needs a virtual-audio loopback device, which Windows does not provide natively. Enable 'Stereo Mix' in Sound settings, or install a loopback driver (for example screen-capture-recorder's virtual-audio-capturer, or VB-CABLE). Then pass its name as `device`, or run list_audio_devices to see what is available. Microphone capture is not supported.";function jv(t){return Wm(t,"audio")}function Uv(t){return Wm(t,"video")}function Wm(t,e){let r=[],n=null;for(let o of t.split(/\r?\n/)){if(/DirectShow audio devices/i.test(o)){n="audio";continue}if(/DirectShow video devices/i.test(o)){n="video";continue}if(/Alternative name/i.test(o))continue;let i=o.match(/"([^"]+)"/);if(!i)continue;let s=/\(audio\)/i.test(o),a=/\(video\)/i.test(o);(e==="audio"?s||!a&&n==="audio":a||!s&&n==="video")&&i[1]&&r.push(i[1])}return[...new Set(r)]}function eu(t,e){if(e&&e.trim().length>0)return t.includes(e)?e:null;let r=n=>n.toLowerCase();return t.find(n=>Wv.some(o=>r(n).includes(o)))??null}var zv=12e3,Hv="Enumerating DirectShow audio devices timed out or failed - usually a misbehaving audio driver, or no audio device present. Record without system audio, or fix the device, then retry. "+Co,gs=null,bs=null;async function tu(t=!1){return!t&&gs?gs:(await Um(),gs??[])}async function ru(t=!1){return!t&&bs?bs:(await Um(),bs??[])}async function jm(t){let e=await ru();if(t&&t.trim().length>0){if(e.includes(t))return t;throw new l(`Video device "${t}" not found. Available dshow video devices: ${e.join(", ")||"none"}.`)}let r=e[0];if(!r)throw new l("No webcam (dshow video device) found.","Connect a camera, then run list_video_devices.");return r}async function Um(){let{ffmpeg:t}=k(),e;try{e=await se(t,["-hide_banner","-list_devices","true","-f","dshow","-i","dummy"],zv)}catch(r){throw new l(`Could not enumerate audio devices (${z(r)}).`,Hv)}gs=jv(e.stderr),bs=Uv(e.stderr)}async function zm(t){let e=await tu(),r=eu(e,t);if(r)return r;if(t&&t.trim().length>0){let n=e.length>0?e.join(", "):"none";throw new l(`Audio device "${t}" not found. Available dshow audio devices: ${n}.`,Co)}throw new l("No system-audio loopback device found.",Co)}var Po="SCREENCAST_CONFIRM_CAPTURE",nu=300*1e3;function Hm(t=process.env){let e=(t[Po]??"").trim().toLowerCase();return["1","true","yes","on","always"].includes(e)?"always":["0","false","no","off","never"].includes(e)?"off":"auto"}function Gm(t=process.env){return Hm(t)==="always"}function Nt(t,e){return e?`window "${e.matchedTitle}"`:t==="full"?"the full screen (all monitors)":t}async function Dt(t,e,r){let n=Hm();if(n==="off")return;if(!t.server.getClientCapabilities()?.elicitation?.form){if(n==="auto")return;throw new l(`Capture blocked: ${Po} requires the user to confirm each capture, but this client does not support MCP elicitation. Nothing was captured.`,`Use a client that supports elicitation, or set ${Po}=auto to capture without confirmation in clients that cannot ask.`)}let o;try{({action:o}=await t.server.elicitInput({message:e,requestedSchema:{type:"object",properties:{}}},{signal:r,timeout:nu}))}catch(i){throw new l(`Capture blocked: the confirmation request failed (${z(i)}). Nothing was captured.`)}if(o!=="accept")throw new l(`Capture ${o==="decline"?"declined":"cancelled"} by the user. Nothing was captured.`)}var ws=null;function oe(){return ws||(ws=new ns(mp()),ws.load()),ws}var iu=!1;function qm(){iu=!0}function xs(){return iu}var ys=0,ou=[];function Xm(){if(iu)throw new l("The server is shutting down; the recording was not started.");ys++;let t=!1;return()=>{if(!t&&(t=!0,ys--,ys===0)){let e=ou;ou=[];for(let r of e)r()}}}function Jm(t){return ys===0?Promise.resolve(!0):new Promise(e=>{let r=setTimeout(()=>e(!1),t);r.unref?.(),ou.push(()=>{clearTimeout(r),e(!0)})})}import{existsSync as M0,mkdirSync as C0,mkdtempSync as P0,rmSync as xu,writeFileSync as yf}from"node:fs";import{tmpdir as I0}from"node:os";import{spawn as Gv}from"node:child_process";var Ym=15e3;async function Lt(t,e,r="gdigrab"){if(r==="gdigrab"){await te(Ti(t.target,e,t.monitors),6e4);return}let n=t.window?.hwnd;if(n===void 0)throw new l("backend 'wgc' captures a single window: use a window:<title> target.");if(!cr())throw new l("backend 'wgc' needs FFmpeg 8 or newer with the gfxcapture filter (Windows Graphics Capture).","Check with `ffmpeg -h filter=gfxcapture`. Recent Windows builds (e.g. `winget install Gyan.FFmpeg`) include it. Or use the default backend, which captures what is visible on screen.");let o=Gv("powershell",["-NoProfile","-NonInteractive","-Command",Jd(n,100,process.pid)],{stdio:"ignore",windowsHide:!0});o.on("error",()=>{});try{await te($p(n,e),Ym)}catch(i){throw i instanceof l&&/timed out/.test(i.message)?new l(`Windows Graphics Capture got no frame from the window in ${Ym/1e3} s.`,"The window may be hung or protected from capture. Try the default backend with the window in front."):i}finally{o.kill()}}import{join as au}from"node:path";import{readdirSync as s0}from"node:fs";import{runInNewContext as qv}from"node:vm";var Xv=[2,4],Jv=1e4;function Yv(t){return{script:n0,payload:JSON.stringify(t)}}async function Vm(t,e){if(process.platform!=="win32")throw new l("find_text uses the Windows OCR engine and runs on Windows only.");let{script:r,payload:n}=Yv(t),o=await ct(r,"text (OCR)",{timeoutMs:ur(t0+Math.max(0,t.length-2)*r0),payload:n,failure:"Could not run OCR"}),i;try{i=JSON.parse(o)}catch(a){throw new l(`Could not parse OCR output: ${z(a)}`)}return(Array.isArray(i)?i:[i]).map((a,c)=>Kv(a,e[c]??1))}function Kv(t,e){let r=t??{};if(r.error)throw/language|recognizer/i.test(r.error)?new l(`Windows OCR is unavailable: ${r.error}`,"Install an OCR language: Settings > Time & language > Language > (your language) > Options > Optical character recognition."):new l(`OCR failed: ${r.error}`);let n=[];for(let o of r.lines??[]){let i=(Array.isArray(o.words)?o.words:o.words?[o.words]:[]).map(s=>({text:String(s.text??""),x:Math.round((s.x??0)/e),y:Math.round((s.y??0)/e),width:Math.max(1,Math.round((s.width??0)/e)),height:Math.max(1,Math.round((s.height??0)/e))}));i.length!==0&&n.push({text:String(o.text??i.map(s=>s.text).join(" ")),words:i,...Qm(i)})}return n}function Qm(t){let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,width:n-e,height:o-r}}function Vv(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),n=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);return r<=0||n<=0?0:r*n/Math.min(t.width*t.height,e.width*e.height)}function Zm(t){let e=[];for(let r of t)for(let n of r){let o=e.findIndex(s=>Vv(s,n)>.5),i=e[o];i?n.text.length>i.text.length&&(e[o]=n):e.push(n)}return e.sort((r,n)=>r.y-n.y||r.x-n.x)}function Bt(t){return t.toLowerCase().replace(/[-_\s]+/g,"_").replace(/[l1|]/g,"i").replace(/0/g,"o")}var qr=500,Qv=1e3;function ef(t,e){return t.map(r=>{let n=new RegExp(e,"gi"),o=new Set,i=[];for(let s of[r,r.replace(/-/g,"_"),r.replace(/_/g,"-")])for(let a of s.matchAll(n)){let c=`${a.index}:${a[0].length}`;a[0].length>0&&!o.has(c)&&(o.add(c),i.push([a.index,a.index+a[0].length]))}return i})}var Zv=`JSON.stringify((${ef.toString()})(texts, query))`,tf=new Set;function su(t){return tf.add(t),t}function Tn(t,e,r=Qv){try{new RegExp(e,"gi")}catch(n){throw new l(`Invalid regex: ${z(n)}`)}if(tf.has(e))return ef(t,e);try{return JSON.parse(qv(Zv,{texts:t,query:e},{timeout:r}))}catch(n){throw n.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"?new l(`The regex took longer than ${r/1e3} s to run and was stopped.`,"Simplify it: nested quantifiers such as (a+)+ backtrack catastrophically."):n}}function St(t,e,r=!1){if(e.length>qr)throw new l(`The query is ${e.length} characters; at most ${qr} are allowed.`);let n=t.map(s=>{let a=[],c="";for(let u of s.words)c&&(c+=" "),a.push({start:c.length,end:c.length+u.text.length,word:u}),c+=u.text;return{line:s,spans:a,text:c}}),o=r?Tn(n.map(s=>s.text),e):null,i=[];return n.forEach(({line:s,spans:a},c)=>{let u=[];if(o)u=o[c]??[];else{let p=Bt(e);if(!p)return;let f=a.map(h=>Bt(h.word.text)).join("_"),m=0;for(let h=f.indexOf(p,m);h!==-1;h=f.indexOf(p,m))u.push(e0(a,h,h+p.length)),m=h+p.length}let d=new Set;for(let[p,f]of u){let m=a.filter(h=>h.start<f&&h.end>p).map(h=>h.word);m.length===0||m.every(h=>d.has(h))||(m.forEach(h=>d.add(h)),i.push({text:m.map(h=>h.text).join(" "),line:s.text,...Qm(m)}))}}),i}function e0(t,e,r){let n=0,o=-1,i=-1;for(let s of t){let a=Bt(s.word.text).length;if(o===-1&&e<n+a&&(o=s.start),r<=n+a+1){i=s.end;break}n+=a+1}return[o===-1?0:o,i===-1?t.at(-1)?.end??0:i]}function Ss(t,e,r=4){return t.map(n=>{let o=Math.max(0,n.x-r),i=Math.max(0,n.y-r);return{x:o,y:i,width:Math.min(e.width,n.x+n.width+r)-o,height:Math.min(e.height,n.y+n.height+r)-i}})}function rf(t,e){let r=Jv/Math.max(t,e),n=Xv.map(o=>Math.min(o,Math.floor(r*100)/100)).filter(o=>o>=1);return[...new Set(n.length?n:[Math.min(1,r)])]}var t0=6e4,r0=5e3,Km=2e4,n0=`
276
276
  $ErrorActionPreference = 'Stop'
277
277
  Add-Type -AssemblyName System.Runtime.WindowsRuntime
278
278
  $null = [Windows.Storage.StorageFile, Windows.Storage, ContentType = WindowsRuntime]
279
279
  $null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
280
280
  $null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime]
281
281
  $asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' })[0]
282
- function Await($op, [Type]$t) { $task = $asTask.MakeGenericMethod($t).Invoke($null, @($op)); if (-not $task.Wait(${Jm})) { throw "The OCR engine did not answer within ${Jm/1e3} s." }; $task.Result }
282
+ function Await($op, [Type]$t) { $task = $asTask.MakeGenericMethod($t).Invoke($null, @($op)); if (-not $task.Wait(${Km})) { throw "The OCR engine did not answer within ${Km/1e3} s." }; $task.Result }
283
283
  $paths = $Payload | ConvertFrom-Json
284
284
  $engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
285
285
  $out = foreach ($p in $paths) {
@@ -297,47 +297,48 @@ $out = foreach ($p in $paths) {
297
297
  } catch { [pscustomobject]@{ error = $_.Exception.Message } }
298
298
  }
299
299
  ConvertTo-Json -InputObject @($out) -Depth 6 -Compress
300
- `;import{availableParallelism as Xv}from"node:os";function Jv(t=Xv()){return Math.min(4,Math.max(2,Math.floor(t/4)))}async function He(t,e,r=Jv()){let n=new Array(t.length),o=0,i=!1,s,a=async()=>{for(;!i&&o<t.length;){let u=o++;try{n[u]=await e(t[u],u)}catch(d){i||(i=!0,s=d)}}},c=Math.max(1,Math.min(Math.floor(r),t.length));if(await Promise.all(Array.from({length:c},a)),i)throw s;return n}function Kv(t,e,r){if(e.length===0||e.length!==r.length)throw new l("Each OCR pass needs one output.");let n=a=>`scale=iw*${a}:ih*${a}:flags=lanczos`,o=["-compression_level","0"];if(e.length===1)return["-y","-v","error","-i",t,"-vf",n(e[0]),...o,r[0]];let i=e.map((a,c)=>`[s${c}]`),s=[`[0:v]split=${e.length}${i.join("")}`,...e.map((a,c)=>`${i[c]}${n(a)}[o${c}]`)].join(";");return["-y","-v","error","-i",t,"-filter_complex",s,...r.flatMap((a,c)=>["-map",`[o${c}]`,...o,a])]}async function ct(t,e,r,n={}){let o=async m=>{let{width:h,height:b}=await L(m);if(!h||!b)throw new l("Could not read the image size.");return{width:h,height:b}},i=n.sameSize&&t[0]?await o(t[0]):null,s=await He(t,async m=>({source:m,...i??await o(m)})),c=(await He(s,async({source:m,width:h,height:b},w)=>{let g=ef(h,b),y=g.map(($,S)=>su(e,`pass${w}-${S}.png`));return await Z(Kv(m,g,y),6e4,{signal:r}),g.map(($,S)=>({out:y[S],scale:$,f:w}))})).flat(),u=c.map(m=>m.out),d=c.map(m=>m.scale),p=c.map(m=>m.f),f=await Ym(u,d);return s.map(({width:m,height:h},b)=>({lines:Vm(f.filter((w,g)=>p[g]===b)),width:m,height:h}))}async function Ss(t,e,r,n){let o=await L(t),i=o.videoDurationSec??o.durationSec,s=e.range?e.range.duration:i,a=Mi(s,1/e.everySec,e.maxFrames);await Z(Ci(t,a.fps,su(r,"scan_%05d.png"),e.maxFrames,!1,e.range),le(o.durationSec),{signal:n});let c=Yv(r).filter(m=>m.startsWith("scan_")).sort().map(m=>su(r,m));if(c.length===0)throw new l("Could not read any frames from the video.");let u=1/a.fps,d=m=>Math.round(m*u*1e3)/1e3,p=s??d(c.length-1)+u;return{frames:(await ct(c,r,n,{sameSize:!0})).map((m,h)=>({...m,t:d(h),path:c[h]??""})),step:u,end:p,clamped:a.clamped}}function Vv(t,e,r){return{start:Math.max(0,Math.round((t-e)*1e3)/1e3),end:Math.min(r,Math.round((t+e)*1e3)/1e3)}}function kn(t,e,r,n="match"){let o=[],i=[];for(let s of t.frames){let a=yt(s.lines,e,r),c=Vv(s.t,t.step,t.end),u=n==="line"?[...new Set(a.map(d=>s.lines.find(p=>p.text===d.line)??d))]:a;for(let d of a)o.push({t:s.t,...d});for(let d of xs(u,s))i.push({...d,...c})}return{matches:o,redactRegions:i}}var En=30,vs=120;var au=600,tf=24*3600,cu=1500,_n=new Map;function $s(t){return t.startsWith("arm-")}function Qv(){return`arm-${ge()}-${be(6)}`}function Po(t){let e=_n.get(t)?.arm;return e?{...e}:void 0}function rf(){return[..._n.values()].map(t=>({...t.arm}))}function uu(t){let e=_n.get(t);return!e||e.arm.status!=="armed"?!1:(e.abort.abort(),e.arm.status="cancelled",!0)}async function nf(t){return await _n.get(t)?.done,Po(t)}function of(){for(let t of _n.keys())uu(t)}function lu(t){return[...t.window?[`${t.window.replace(/^window:/,"the window ")} exists`]:[],...t.text?[`"${t.text}" is on screen`]:[]].join(" and ")}async function pu(t){let e=t.now??Date.now,r=t.sleep??(o=>new Promise(i=>setTimeout(i,o))),n=e();for(;;){if(t.signal.aborted)return"cancelled";let o=!0;for(let i of t.checks)if(!await i().catch(()=>!1)){o=!1;break}if(t.signal.aborted)return"cancelled";if(o)return"met";if(e()-n>=t.timeoutMs)return"timeout";await r(t.intervalMs)}}function sf(t){let e={id:Qv(),status:"armed",conditions:t.conditions,target:t.target,armedAt:new Date().toISOString(),timeoutSec:t.timeoutSec},r=new AbortController,n={arm:e,abort:r};return _n.set(e.id,n),n.done=(async()=>{let o=await pu({checks:t.checks,timeoutMs:t.timeoutSec*1e3,intervalMs:t.intervalMs??cu,signal:r.signal});if(o!=="met"){e.status==="armed"&&(e.status=o);return}if(e.status==="armed"){e.firedAt=new Date().toISOString(),e.status="starting";try{e.sessionId=await t.fire(),e.status="started"}catch(i){e.status="failed",e.error=i instanceof Error?i.message:String(i)}}})(),{...e}}import{open as Zv,stat as af}from"node:fs/promises";import{basename as e0}from"node:path";var cf=5,du=5e4,mu=2e3,t0=250,r0=1<<20;function n0(t,e){let r=t.length?Buffer.concat([t,e]):e,n=[],o=0;for(let i=r.indexOf(10);i!==-1;i=r.indexOf(10,o))n.push(r.subarray(o,i).toString("utf8").replace(/\r$/,"")),o=i+1;return{lines:n,rest:r.subarray(o)}}function o0(t){if(/\b(error|err|fatal|critical|exception|unhandled|panic)\b|\btraceback\b/i.test(t))return"error";if(/\bwarn(ing)?\b/i.test(t))return"warn"}var i0=t=>t.length>mu?`${t.slice(0,mu-1)}\u2026`:t;function uf(t,e){let r=[];for(let n of t){if(!n.line.trim())continue;let o=e.spans?.length?po(n.epochMs,e.spans):(n.epochMs-e.startMs)/1e3;if(o===null||o<0||o>e.endSec)continue;let i=o0(n.line);r.push({t:Math.round(o*1e3)/1e3,source:n.source,line:i0(n.line),...i?{level:i}:{}})}return r.slice(-du)}function lf(t){return t.map(e=>JSON.stringify(e)).join(`
300
+ `;import{availableParallelism as o0}from"node:os";function i0(t=o0()){return Math.min(4,Math.max(2,Math.floor(t/4)))}async function qe(t,e,r=i0()){let n=new Array(t.length),o=0,i=!1,s,a=async()=>{for(;!i&&o<t.length;){let u=o++;try{n[u]=await e(t[u],u)}catch(d){i||(i=!0,s=d)}}},c=Math.max(1,Math.min(Math.floor(r),t.length));if(await Promise.all(Array.from({length:c},a)),i)throw s;return n}function a0(t,e,r){if(e.length===0||e.length!==r.length)throw new l("Each OCR pass needs one output.");let n=a=>`scale=iw*${a}:ih*${a}:flags=lanczos`,o=["-compression_level","0"];if(e.length===1)return["-y","-v","error","-i",t,"-vf",n(e[0]),...o,r[0]];let i=e.map((a,c)=>`[s${c}]`),s=[`[0:v]split=${e.length}${i.join("")}`,...e.map((a,c)=>`${i[c]}${n(a)}[o${c}]`)].join(";");return["-y","-v","error","-i",t,"-filter_complex",s,...r.flatMap((a,c)=>["-map",`[o${c}]`,...o,a])]}async function lt(t,e,r,n={}){let o=async m=>{let{width:h,height:b}=await W(m);if(!h||!b)throw new l("Could not read the image size.");return{width:h,height:b}},i=n.sameSize&&t[0]?await o(t[0]):null,s=await qe(t,async m=>({source:m,...i??await o(m)})),c=(await qe(s,async({source:m,width:h,height:b},w)=>{let g=rf(h,b),y=g.map((v,x)=>au(e,`pass${w}-${x}.png`));return await te(a0(m,g,y),6e4,{signal:r}),g.map((v,x)=>({out:y[x],scale:v,f:w}))})).flat(),u=c.map(m=>m.out),d=c.map(m=>m.scale),p=c.map(m=>m.f),f=await Vm(u,d);return s.map(({width:m,height:h},b)=>({lines:Zm(f.filter((w,g)=>p[g]===b)),width:m,height:h}))}async function Rn(t,e,r,n){let o=await W(t),i=o.videoDurationSec??o.durationSec,s=e.range?e.range.duration:i,a=Ci(s,1/e.everySec,e.maxFrames);await te(Pi(t,a.fps,au(r,"scan_%05d.png"),e.maxFrames,!1,e.range),pe(o.durationSec),{signal:n});let c=s0(r).filter(m=>m.startsWith("scan_")).sort().map(m=>au(r,m));if(c.length===0)throw new l("Could not read any frames from the video.");let u=1/a.fps,d=m=>Math.round(m*u*1e3)/1e3,p=s??d(c.length-1)+u;return{frames:(await lt(c,r,n,{sameSize:!0})).map((m,h)=>({...m,t:d(h),path:c[h]??""})),step:u,end:p,clamped:a.clamped}}function c0(t,e,r){return{start:Math.max(0,Math.round((t-e)*1e3)/1e3),end:Math.min(r,Math.round((t+e)*1e3)/1e3)}}function br(t,e,r,n="match"){let o=[],i=[];for(let s of t.frames){let a=St(s.lines,e,r),c=c0(s.t,t.step,t.end),u=n==="line"?[...new Set(a.map(d=>s.lines.find(p=>p.text===d.line)??d))]:a;for(let d of a)o.push({t:s.t,...d});for(let d of Ss(u,s))i.push({...d,...c})}return{matches:o,redactRegions:i}}var Wt=30,vs=120;var cu=600,nf=24*3600,uu=1500,An=new Map;function $s(t){return t.startsWith("arm-")}function u0(){return`arm-${he()}-${ge(6)}`}function Io(t){let e=An.get(t)?.arm;return e?{...e}:void 0}function of(){return[...An.values()].map(t=>({...t.arm}))}function lu(t){let e=An.get(t);return!e||e.arm.status!=="armed"?!1:(e.abort.abort(),e.arm.status="cancelled",!0)}async function sf(t){return await An.get(t)?.done,Io(t)}function af(){for(let t of An.keys())lu(t)}function pu(t){return[...t.window?[`${t.window.replace(/^window:/,"the window ")} exists`]:[],...t.text?[`"${t.text}" is on screen`]:[]].join(" and ")}async function du(t){let e=t.now??Date.now,r=t.sleep??(o=>new Promise(i=>setTimeout(i,o))),n=e();for(;;){if(t.signal.aborted)return"cancelled";let o=!0;for(let i of t.checks)if(!await i().catch(()=>!1)){o=!1;break}if(t.signal.aborted)return"cancelled";if(o)return"met";if(e()-n>=t.timeoutMs)return"timeout";await r(t.intervalMs)}}function cf(t){let e={id:u0(),status:"armed",conditions:t.conditions,target:t.target,armedAt:new Date().toISOString(),timeoutSec:t.timeoutSec},r=new AbortController,n={arm:e,abort:r};return An.set(e.id,n),n.done=(async()=>{let o=await du({checks:t.checks,timeoutMs:t.timeoutSec*1e3,intervalMs:t.intervalMs??uu,signal:r.signal});if(o!=="met"){e.status==="armed"&&(e.status=o);return}if(e.status==="armed"){e.firedAt=new Date().toISOString(),e.status="starting";try{e.sessionId=await t.fire(),e.status="started"}catch(i){e.status="failed",e.error=i instanceof Error?i.message:String(i)}}})(),{...e}}import{open as l0,stat as uf}from"node:fs/promises";import{basename as p0}from"node:path";var lf=5,mu=5e4,fu=2e3,d0=250,m0=1<<20;function f0(t,e){let r=t.length?Buffer.concat([t,e]):e,n=[],o=0;for(let i=r.indexOf(10);i!==-1;i=r.indexOf(10,o))n.push(r.subarray(o,i).toString("utf8").replace(/\r$/,"")),o=i+1;return{lines:n,rest:r.subarray(o)}}function h0(t){if(/\b(error|err|fatal|critical|exception|unhandled|panic)\b|\btraceback\b/i.test(t))return"error";if(/\bwarn(ing)?\b/i.test(t))return"warn"}var g0=t=>t.length>fu?`${t.slice(0,fu-1)}\u2026`:t;function pf(t,e){let r=[];for(let n of t){if(!n.line.trim())continue;let o=e.spans?.length?mo(n.epochMs,e.spans):(n.epochMs-e.startMs)/1e3;if(o===null||o<0||o>e.endSec)continue;let i=h0(n.line);r.push({t:Math.round(o*1e3)/1e3,source:n.source,line:g0(n.line),...i?{level:i}:{}})}return r.slice(-mu)}function df(t){return t.map(e=>JSON.stringify(e)).join(`
301
301
  `)+(t.length?`
302
- `:"")}function Es(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function Lt(t){return t.replace(/\.[^./\\]+$/,"")+".logs.jsonl"}var ks=class{constructor(e,r=Date.now){this.now=r;this.files=e.map(n=>({path:n.path,label:n.label??e0(n.path),pos:0,ino:null,partial:Buffer.alloc(0)}))}now;files;lines=[];timer=null;polling=Promise.resolve();async mark(){for(let e of this.files)try{let r=await af(e.path);e.pos=r.size,e.ino=r.ino}catch{}}follow(e=t0){this.timer=setInterval(()=>{this.polling=this.polling.then(()=>this.readNew())},e),this.timer.unref()}async readNew(){for(let e of this.files){let r;try{r=await af(e.path)}catch{continue}if((e.ino!==null&&r.ino!==e.ino||r.size<e.pos)&&(e.pos=0,e.partial=Buffer.alloc(0)),e.ino=r.ino,r.size<=e.pos)continue;let n=Math.min(r.size-e.pos,r0),o;try{o=await Zv(e.path,"r");let i=Buffer.alloc(n),{bytesRead:s}=await o.read(i,0,n,e.pos);e.pos+=s;let{lines:a,rest:c}=n0(e.partial,i.subarray(0,s));e.partial=c.length>mu*4?Buffer.alloc(0):Buffer.from(c);let u=this.now();for(let d of a)this.lines.push({epochMs:u,source:e.label,line:d});this.lines.length>du*2&&(this.lines=this.lines.slice(-du))}catch{}finally{await o?.close()}}}async stop(){this.timer&&clearInterval(this.timer),this.timer=null,await this.polling,await this.readNew();let e=this.now();for(let r of this.files)r.partial.length&&this.lines.push({epochMs:e,source:r.label,line:r.partial.toString("utf8").replace(/\r$/,"")}),r.partial=Buffer.alloc(0);return this.lines}};import{spawn as s0}from"node:child_process";import{cpus as pf,freemem as a0,totalmem as c0}from"node:os";var u0=1e3,fu=90;function l0(t,e){let r=0,n=0;return e.forEach((o,i)=>{let s=t[i];if(!s)return;let a=u=>o.times[u]-s.times[u],c=a("user")+a("nice")+a("sys")+a("idle")+a("irq");r+=c-a("idle"),n+=c}),n>0?Math.round(r/n*1e3)/10:0}function p0(t){let[e,r,n]=t.trim().split(",").map(Number);return e!==void 0&&r!==void 0&&n!==void 0&&[e,r,n].every(Number.isFinite)?{epochMs:e,cpuMs:r,rss:n}:null}function d0(t,e,r){let n=e.epochMs-t.epochMs;return!(n>0)||!(r>0)?0:Math.max(0,Math.min(100,Math.round((e.cpuMs-t.cpuMs)/n/r*1e3)/10))}function df(t,e){let r=[];for(let{epochMs:n,...o}of t){let i=e.spans?.length?po(n,e.spans):(n-e.startMs)/1e3;i===null||i<0||i>e.endSec||r.push({t:Math.round(i*1e3)/1e3,...o})}return r}function Tn(t,e){let r=t.filter(u=>u.cpu!==void 0),n=t.filter(u=>u.rssMB!==void 0),o=u=>r.length?u.cpu??0:u.sysCpu,i=[],s=null,a=0;for(let u of t)o(u)>=fu?(s??=u.t,a=u.t):s!==null&&(a-s>=2&&i.push({start:s,end:a}),s=null);s!==null&&a-s>=2&&i.push({start:s,end:a});let c=u=>Math.round(u*10)/10;return{samples:t.length,peakSysCpu:c(Math.max(0,...t.map(u=>u.sysCpu))),...r.length?{peakCpu:c(Math.max(...r.map(u=>u.cpu)))}:{},...n.length?{peakRssMB:c(Math.max(...n.map(u=>u.rssMB))),rssGrowthMB:c(n.at(-1).rssMB-n[0].rssMB)}:{},busy:i,...e?{process:e}:{}}}function mf(t){return t.map(e=>JSON.stringify(e)).join(`
302
+ `:"")}function Es(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function jt(t){return t.replace(/\.[^./\\]+$/,"")+".logs.jsonl"}var ks=class{constructor(e,r=Date.now){this.now=r;this.files=e.map(n=>({path:n.path,label:n.label??p0(n.path),pos:0,ino:null,partial:Buffer.alloc(0)}))}now;files;lines=[];timer=null;polling=Promise.resolve();async mark(){for(let e of this.files)try{let r=await uf(e.path);e.pos=r.size,e.ino=r.ino}catch{}}follow(e=d0){this.timer=setInterval(()=>{this.polling=this.polling.then(()=>this.readNew())},e),this.timer.unref()}async readNew(){for(let e of this.files){let r;try{r=await uf(e.path)}catch{continue}if((e.ino!==null&&r.ino!==e.ino||r.size<e.pos)&&(e.pos=0,e.partial=Buffer.alloc(0)),e.ino=r.ino,r.size<=e.pos)continue;let n=Math.min(r.size-e.pos,m0),o;try{o=await l0(e.path,"r");let i=Buffer.alloc(n),{bytesRead:s}=await o.read(i,0,n,e.pos);e.pos+=s;let{lines:a,rest:c}=f0(e.partial,i.subarray(0,s));e.partial=c.length>fu*4?Buffer.alloc(0):Buffer.from(c);let u=this.now();for(let d of a)this.lines.push({epochMs:u,source:e.label,line:d});this.lines.length>mu*2&&(this.lines=this.lines.slice(-mu))}catch{}finally{await o?.close()}}}async stop(){this.timer&&clearInterval(this.timer),this.timer=null,await this.polling,await this.readNew();let e=this.now();for(let r of this.files)r.partial.length&&this.lines.push({epochMs:e,source:r.label,line:r.partial.toString("utf8").replace(/\r$/,"")}),r.partial=Buffer.alloc(0);return this.lines}};import{spawn as b0}from"node:child_process";import{cpus as mf,freemem as w0,totalmem as y0}from"node:os";var x0=1e3,hu=90;function S0(t,e){let r=0,n=0;return e.forEach((o,i)=>{let s=t[i];if(!s)return;let a=u=>o.times[u]-s.times[u],c=a("user")+a("nice")+a("sys")+a("idle")+a("irq");r+=c-a("idle"),n+=c}),n>0?Math.round(r/n*1e3)/10:0}function v0(t){let[e,r,n]=t.trim().split(",").map(Number);return e!==void 0&&r!==void 0&&n!==void 0&&[e,r,n].every(Number.isFinite)?{epochMs:e,cpuMs:r,rss:n}:null}function $0(t,e,r){let n=e.epochMs-t.epochMs;return!(n>0)||!(r>0)?0:Math.max(0,Math.min(100,Math.round((e.cpuMs-t.cpuMs)/n/r*1e3)/10))}function ff(t,e){let r=[];for(let{epochMs:n,...o}of t){let i=e.spans?.length?mo(n,e.spans):(n-e.startMs)/1e3;i===null||i<0||i>e.endSec||r.push({t:Math.round(i*1e3)/1e3,...o})}return r}function Mn(t,e){let r=t.filter(u=>u.cpu!==void 0),n=t.filter(u=>u.rssMB!==void 0),o=u=>r.length?u.cpu??0:u.sysCpu,i=[],s=null,a=0;for(let u of t)o(u)>=hu?(s??=u.t,a=u.t):s!==null&&(a-s>=2&&i.push({start:s,end:a}),s=null);s!==null&&a-s>=2&&i.push({start:s,end:a});let c=u=>Math.round(u*10)/10;return{samples:t.length,peakSysCpu:c(Math.max(0,...t.map(u=>u.sysCpu))),...r.length?{peakCpu:c(Math.max(...r.map(u=>u.cpu)))}:{},...n.length?{peakRssMB:c(Math.max(...n.map(u=>u.rssMB))),rssGrowthMB:c(n.at(-1).rssMB-n[0].rssMB)}:{},busy:i,...e?{process:e}:{}}}function hf(t){return t.map(e=>JSON.stringify(e)).join(`
303
303
  `)+(t.length?`
304
- `:"")}function An(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function xt(t){return t.replace(/\.[^./\\]+$/,"")+".perf.jsonl"}function m0(t,e,r){return`$ErrorActionPreference='SilentlyContinue';while($true){$p=Get-Process -Id ${t};if(-not $p -or -not (Get-Process -Id ${e})){break};$t=[DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds();[Console]::Out.WriteLine("$t,$($p.TotalProcessorTime.TotalMilliseconds),$($p.WorkingSet64)");[Console]::Out.Flush();Start-Sleep -Milliseconds ${r}}`}var _s=class{constructor(e,r=u0){this.pid=e;this.intervalMs=r}pid;intervalMs;samples=[];timer=null;child=null;proc={};start(){let e=pf(),r=e.length||1;if(this.pid!==void 0){this.child=s0("powershell",["-NoProfile","-NonInteractive","-Command",m0(this.pid,process.pid,this.intervalMs)],{stdio:["ignore","pipe","ignore"],windowsHide:!0}),this.child.on("error",()=>{this.child=null});let n=null,o="";this.child.stdout?.on("data",i=>{o+=i.toString();let s=o.split(/\r?\n/);o=s.pop()??"";for(let a of s){let c=p0(a);c&&(n&&(this.proc={cpu:d0(n,c,r),rssMB:Math.round(c.rss/1048576)}),n=c)}})}this.timer=setInterval(()=>{let n=pf(),o=c0();this.samples.push({epochMs:Date.now(),sysCpu:l0(e,n),sysMem:o>0?Math.round((o-a0())/o*1e3)/10:0,...this.proc}),e=n},this.intervalMs),this.timer.unref()}stop(){return this.timer&&clearInterval(this.timer),this.timer=null,this.child?.kill(),this.child=null,this.samples}};import{spawn as f0}from"node:child_process";import{mkdirSync as h0,rmSync as ff}from"node:fs";function hu(t,e){let r="",n="",o=null,i=new Ni(()=>({sessionId:e}));return t.stderr?.on("data",s=>{let a=s.toString();n=(n+a).slice(-2e3),r.length<8e3&&(r+=a),o===null&&/Output #0/.test(r)&&(o=Date.now()),i.feed(a)}),t.on("error",s=>{n+=`
305
- ${s.message}`}),{head:()=>r,tail:()=>n,outputAt:()=>o}}function Io(t,e=6){return t.tail().trim().split(`
304
+ `:"")}function Cn(t){let e=[];for(let r of t.split(/\r?\n/))if(r.trim())try{e.push(JSON.parse(r))}catch{}return e}function vt(t){return t.replace(/\.[^./\\]+$/,"")+".perf.jsonl"}function k0(t,e,r){return`$ErrorActionPreference='SilentlyContinue';while($true){$p=Get-Process -Id ${t};if(-not $p -or -not (Get-Process -Id ${e})){break};$t=[DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds();[Console]::Out.WriteLine("$t,$($p.TotalProcessorTime.TotalMilliseconds),$($p.WorkingSet64)");[Console]::Out.Flush();Start-Sleep -Milliseconds ${r}}`}var _s=class{constructor(e,r=x0){this.pid=e;this.intervalMs=r}pid;intervalMs;samples=[];timer=null;child=null;proc={};start(){let e=mf(),r=e.length||1;if(this.pid!==void 0){this.child=b0("powershell",["-NoProfile","-NonInteractive","-Command",k0(this.pid,process.pid,this.intervalMs)],{stdio:["ignore","pipe","ignore"],windowsHide:!0}),this.child.on("error",()=>{this.child=null});let n=null,o="";this.child.stdout?.on("data",i=>{o+=i.toString();let s=o.split(/\r?\n/);o=s.pop()??"";for(let a of s){let c=v0(a);c&&(n&&(this.proc={cpu:$0(n,c,r),rssMB:Math.round(c.rss/1048576)}),n=c)}})}this.timer=setInterval(()=>{let n=mf(),o=y0();this.samples.push({epochMs:Date.now(),sysCpu:S0(e,n),sysMem:o>0?Math.round((o-w0())/o*1e3)/10:0,...this.proc}),e=n},this.intervalMs),this.timer.unref()}stop(){return this.timer&&clearInterval(this.timer),this.timer=null,this.child?.kill(),this.child=null,this.samples}};import{spawn as E0}from"node:child_process";import{mkdirSync as _0,rmSync as gf}from"node:fs";function gu(t,e){let r="",n="",o=null,i=new Di(()=>({sessionId:e}));return t.stderr?.on("data",s=>{let a=s.toString();n=(n+a).slice(-2e3),r.length<8e3&&(r+=a),o===null&&/Output #0/.test(r)&&(o=Date.now()),i.feed(a)}),t.on("error",s=>{n+=`
305
+ ${s.message}`}),{head:()=>r,tail:()=>n,outputAt:()=>o}}function Fo(t,e=6){return t.tail().trim().split(`
306
306
  `).slice(-e).join(`
307
- `)}function gu(t,e,r){return new Promise(n=>{let o=setTimeout(()=>n("running"),r==="wgc"?15e3:r==="ddagrab"?2e3:1200);r==="wgc"&&t.stderr?.on("data",()=>{sn(e.head())!==null&&(clearTimeout(o),n("running"))}),t.on("error",()=>{clearTimeout(o),n("exited")}),t.on("exit",()=>{clearTimeout(o),n("exited")})})}function bu(t,e,r){let n=sn(t.head());return n!==null?n:e==="ddagrab"?t.outputAt()??r:r}function wu(t,e,r,n){r.on("exit",o=>{let i=t.getChild(e);if(i&&i!==r)return;t.detachChild(e,r),pd(e)||Hi(e);let s=t.get(e);if(!s||s.status!=="recording"||t.isStopping(e))return;let a=mm({code:o,backend:n.backend,maxDurationSec:n.maxDurationSec,elapsedMs:Date.now()-n.spawnedAt});or(a.status==="failed"?"error":"notice",a.status==="failed"?`Recording ${e} failed: the recorder exited with code ${o}.`:`Recording ${e} ended on its own (${a.endReason}).`,{sessionId:e,...a}),t.tryUpdate(e,{...a,stoppedAt:new Date().toISOString(),...a.status==="failed"?{error:`${n.backend==="wgc"?"The window recorder":"ffmpeg"} exited with code ${o}:
308
- ${Io(n.watch)}`}:{}}),s.segments&&(s.segments.parts.length>0||s.webcam)?b0(t,s).catch(c=>{process.stderr.write(`Joining ${e}'s segments failed: ${U(c)}
309
- `)}):g0(t,s).catch(c=>{process.stderr.write(`Reading ${e}'s duration failed: ${U(c)}
310
- `)})})}async function g0(t,e){let{ffprobe:r}=k(),n=await se(e.outputPath,{ffprobe:r});n!==null&&t.tryUpdate(e.id,{durationSec:n})}async function b0(t,e){let r=k();await Kt(e.id);let{patch:n,error:o}=await Yc(e,r),i=await se(e.outputPath,{ffprobe:r.ffprobe});t.tryUpdate(e.id,{...n,durationSec:i??void 0,...o?{error:o}:{}})}function hf(t,e,r){return os(t,e.id,"resume",()=>w0(t,t.get(e.id)??e,r))}async function w0(t,e,r){let n=ud(e,t.ownsPaused(e.id));if(n)throw new l(`Cannot resume ${e.id}: ${n}.`);let o=e.segments,i=e.capture,s=e.backend??"gdigrab",a=rt(o.parts),c=ad(e.maxDurationSec,a),u=o.parts.length,d=sd(e.outputPath,u),p=i.webcam?Ui(e.outputPath,u):void 0;(u>0||p)&&h0(bt(e.outputPath),{recursive:!0});let f=Ei(i.target,{...i.opts,output:d,maxDurationSec:c,...i.webcam&&p?{webcam:{...i.webcam,output:p}}:{}}),m=Date.now(),h=f0(r,f,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),b=hu(h,e.id),w=()=>{let C=t.getChild(e.id);C&&C!==h||(u>0&&ff(d,{force:!0}),p&&ff(p,{force:!0}))};if(await gu(h,b,s)==="exited")throw w(),new l(`Resume failed (ffmpeg exited immediately); the recording stays paused:
311
- ${Io(b)}`);let g=bu(b,s,m),y=p?sn(b.head(),i.opts.audio?2:1):null;t.attachChild(e.id,h);let $=()=>{t.detachChild(e.id,h),h.pid!==void 0&&lr(h.pid),w()},S;try{S=t.update(e.id,{status:"recording",pid:h.pid??null,pidSpawnedAt:m,videoStartMs:g-a*1e3,segments:{parts:o.parts,current:{path:d,startMs:g,...p?{webcamPath:p,...y!==null?{webcamStartMs:y}:{}}:{}}}})}catch(C){throw $(),new l(`Resume stopped: the session registry could not be written (${U(C)}).`)}if(!S)throw $(),new l(`No session with id "${e.id}".`);return t.clearPaused(e.id),wu(t,e.id,h,{backend:s,maxDurationSec:c,spawnedAt:m,watch:b}),{record:S,recordedSec:a,capSec:c}}import{basename as wf,join as xu}from"node:path";var $0={target:oe.string().describe("full | monitor:<i> (0 = primary) | window:<title> (or window:exe=<app.exe> / window:hwnd=<n>) | region:<x>,<y>,<w>,<h>. With gdigrab a window's rectangle is resolved once at start (visible, on top); it does not follow the window."),exactTitle:oe.boolean().optional().describe("window: targets match the whole title only, never a substring (default false)."),fps:oe.number().int().min(1).max(120).optional().describe(`Frames per second (default ${vi}).`),quality:oe.enum(["draft","standard","high"]).optional().describe(`Encoder preset (default ${$i}).`),audio:oe.object({source:oe.enum(["system","none"]).describe("system = what the machine plays (needs a loopback device); none = video only."),device:oe.string().optional().describe("dshow loopback device (from list_audio_devices); auto-detected if omitted.")}).optional().describe("Audio (default none). No microphone capture."),output:oe.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:oe.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),maxDurationSec:oe.number().int().min(0).max(Ct).optional().describe(`Auto-stop after this many seconds (default ${xc} or SCREENCAST_MAX_RECORDING_SEC; max 7 days; 0 = no cap).`),events:oe.boolean().optional().describe("Also log clicks, scroll, cursor, and typing (video-timed, video pixels) for read_events (default false; ~1 s slower start)."),keys:oe.enum(["masked","shortcuts"]).optional().describe("With events: masked (default) logs typing only as 0.5 s-grid bursts, never keys; shortcuts also names Ctrl/Alt/Win chords. Typed text is never logged."),focus:oe.enum(["app","title"]).optional().describe("Log app switches (implies events); title adds window titles."),logs:oe.array(oe.object({path:oe.string().min(1),label:oe.string().min(1).max(40).optional()})).min(1).max(cf).optional().describe("Log files to follow onto the video clock."),perf:oe.boolean().optional().describe("Sample CPU/memory (and a window's app) to <rec>.perf.jsonl."),hotkeys:oe.boolean().optional().describe("Ctrl+Alt+Shift+M adds a marker, +S stops (implies events)."),elements:oe.boolean().optional().describe('Name the UI element each click hits, e.g. "Save" button (implies events).'),cursor:oe.enum(["os","events"]).optional().describe("events: leave the OS cursor out and log it (implies events) for the cursor tool to redraw."),backend:oe.enum(["gdigrab","wgc","ddagrab"]).optional().describe("gdigrab (default): the screen rectangle. wgc (window: targets, FFmpeg 8+): the window's own surface, even when covered or moved; client area only. ddagrab: one display on the GPU, low CPU."),encoder:oe.enum(["auto","x264","nvenc","qsv","amf"]).optional().describe("auto = first working GPU encoder, else x264 (default with ddagrab; else x264)."),webcam:oe.object({device:oe.string().optional().describe("list_video_devices name (default: first)."),corner:oe.enum(["top_left","top_right","bottom_left","bottom_right"]).optional(),size:oe.number().min(.1).max(.5).optional().describe("Share of width (0.25)."),shape:oe.enum(["rect","circle"]).optional()}).optional().describe("Also record a camera to <output>.webcam.mp4, aligned for overlay."),replayBufferSec:oe.number().int().min(Xi).max(yn).optional().describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab or ddagrab, not wgc."),startWhen:oe.object({window:oe.string().min(1).optional().describe('A window: target that must exist, e.g. "window:Error".'),text:oe.string().min(1).max(200).optional().describe("Text that must be on target (OCR)."),timeoutSec:oe.number().positive().max(tf).optional().describe(`Default ${au}.`)}).optional().describe("Arm: start once these hold (stop_recording disarms)."),stopWhen:oe.object({text:oe.string().min(1).max(200)}).optional().describe("Stop once this text shows (OCR).")};async function yf(t,e,r){let n=await at(t,{exactTitle:e}),o=S0(xu(v0(),"screencast-trigger-"));try{let i=xu(o,"t.png");await Nt(n,i);let[s]=await ct([i],o);return!!s&&yt(s.lines,r).length>0}finally{yu(o,{recursive:!0,force:!0})}}async function k0(t){try{return await at(t.startsWith("window:")?t:`window:${t}`),!0}catch{return!1}}var xf=new WeakSet;function E0(t,e){try{let r=Ti(t,e);return{width:r.w,height:r.h}}catch{return}}function _0(t,e){let r=sn(t.head(),e?2:1);return r!==null?{webcamStartMs:r}:{}}var Su=class{output;webcamRaw;replay;evPaths;logger;child;owned=!0;handOff(){this.owned=!1}async release(){this.owned&&(this.owned=!1,this.child?.pid!==void 0&&this.child.exitCode==null&&lr(this.child.pid),this.logger&&await wi(this.logger),this.evPaths&&yu(this.evPaths.raw,{force:!0}),this.replay&&Ji(this.replay),this.webcamRaw&&this.output&&yu(bt(this.output),{recursive:!0,force:!0}))}};async function T0(t,e){let r=e.encoder!=="x264",n={fps:t.fps,quality:t.quality,monitors:t.monitors,audio:t.audio,drawMouse:!t.hideCursor,...t.dda?{videoInput:tm(t.dda,t.fps,{download:!e.gpuFrames,drawMouse:!t.hideCursor})}:{},...r?{videoCodec:ur(e.encoder,t.quality,{gpuFrames:e.gpuFrames})}:{}},o=t.webcamDevice?{device:t.webcamDevice,...r?{codec:ur(e.encoder,t.quality)}:{}}:void 0,i=Ei(t.target,{...n,output:t.output,maxDurationSec:t.maxDurationSec,...o&&t.webcamRaw?{webcam:{...o,output:t.webcamRaw}}:{}}),s=t.replay?Wd(i,t.replay):i,a=Date.now(),c=t.backend==="wgc"?gf(process.execPath,[Dm(),JSON.stringify({ffmpeg:t.ffmpeg,hwnd:t.window.hwnd,fps:t.fps,encode:[...ur(e.encoder,t.quality),...Si(t.fps)],output:t.output,maxDurationSec:t.maxDurationSec,cursor:!t.hideCursor,...t.audio?{audioDevice:t.audio.device}:{}})],{stdio:["pipe","ignore","pipe"],windowsHide:!0}):gf(t.ffmpeg,s,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),u=hu(c,t.id),d=await gu(c,u,t.backend);return{captureOpts:n,webcam:o,child:c,watch:u,spawnedAt:a,settled:d}}function A0(t,e,r){if(r.replay){let o=new Promise(i=>r.child.once("exit",()=>i()));fo(e,o.then(()=>wi(r.logger)));return}let n=r.frame;n&&fo(e,ko(e).then(async()=>{await wi(r.logger);try{let o=zi(t.get(e)?.segments,r.startMs,Date.now()),i=cp(r.evPaths,{...o,frame:n});t.tryUpdate(e,{events:{path:r.evPaths.jsonl,keys:r.keyMode,count:i.length,summary:an(i)}})}catch(o){t.tryUpdate(e,{events:{path:r.evPaths.jsonl,keys:r.keyMode,error:U(o)}})}}).catch(o=>{process.stderr.write(`Event log for ${e} failed: ${U(o)}
312
- `)}))}function R0(t,e,r){let n=new _s(r.window?.pid);n.start();let o=xt(r.output);t.tryUpdate(e,{perf:{path:o}}),fo(e,ko(e).then(async()=>{try{let i=df(n.stop(),zi(t.get(e)?.segments,r.startMs,Date.now()));bf(o,mf(i));let s=r.window?.pid!==void 0?{pid:r.window.pid,...r.window.exe?{exe:r.window.exe}:{}}:void 0;t.tryUpdate(e,{perf:{path:o,summary:Tn(i,s)}})}catch(i){n.stop(),t.tryUpdate(e,{perf:{path:o,error:U(i)}})}}))}function M0(t,e,r){r.tailer.follow();let n=Lt(r.output),o=r.logs.map(i=>i.label??wf(i.path));t.tryUpdate(e,{logs:{path:n,sources:o}}),fo(e,ko(e).then(async()=>{try{let i=uf(await r.tailer.stop(),zi(t.get(e)?.segments,r.startMs,Date.now()));bf(n,lf(i)),t.tryUpdate(e,{logs:{path:n,sources:o,count:i.length,errors:i.filter(s=>s.level==="error").length}})}catch(i){t.tryUpdate(e,{logs:{path:n,sources:o,error:U(i)}})}}))}function Sf(t,e,r){let n=t.get(e);if(!n||n.status!=="recording"&&n.status!=="paused")return;let{ffprobe:o}=k();To(t,n,{reason:"stopped",probe:i=>se(i,{ffprobe:o})}).catch(i=>process.stderr.write(`${r} stop for ${e} failed: ${U(i)}
313
- `))}function C0(t,e){return r=>{let n=t.get(e);if(!(!n||n.status!=="recording"&&n.status!=="paused")){if(r==="stop")return Sf(t,e,"Hotkey");try{ms(t,e,"hotkey")}catch(o){process.stderr.write(`Hotkey marker for ${e} failed: ${U(o)}
314
- `)}}}}function P0(t,e,r){let n=new AbortController;ko(e).then(()=>n.abort()),pu({checks:[()=>yf(r.target,r.exactTitle,r.text)],timeoutMs:Number.POSITIVE_INFINITY,intervalMs:cu,signal:n.signal}).then(o=>{o==="met"&&Sf(t,e,"stopWhen")})}async function I0(t,e,r,n){try{let o=r.startWhen;if(!o.window&&!o.text)throw new l("startWhen needs window and/or text.");let i=o.timeoutSec??au,s={...o.window?{window:o.window}:{},...o.text?{text:o.text}:{}};await at(r.target,{exactTitle:r.exactTitle,backend:r.backend}),await Ot(t,`When ${lu(s)} (within ${i} s), start recording ${Ft(r.target)}`+(r.events?", logging mouse clicks and typing":"")+"?",n.signal);let a={...r,startWhen:void 0};xf.add(a);let c=sf({conditions:s,target:r.target,timeoutSec:i,checks:[...o.window?[()=>k0(o.window)]:[],...o.text?[()=>yf(r.target,r.exactTitle,o.text)]:[]],fire:async()=>{let u=e.handler,d=await u(a,{...n,signal:new AbortController().signal}),p=d.structuredContent;if(d.isError||!p?.sessionId)throw new Error(d.content.map(f=>f.text??"").join(" ")||"start failed");return p.sessionId}});return v({sessionId:c.id,status:"armed",backend:r.backend??"gdigrab",outputPath:"",waitingFor:lu(s),timeoutSec:i,note:"Nothing is recorded yet. get_session with this id shows when it starts (and its recording's sessionId); stop_recording with it disarms."})}catch(o){return E(o)}}async function F0(t,e,r){let{ffmpeg:n}=k(),o=e.cursor==="events";(o||e.focus||e.elements||e.hotkeys)&&(e.events=!0);let{target:i,monitors:s,window:a}=await at(e.target,{exactTitle:e.exactTitle,backend:e.backend}),c=e.backend??"gdigrab";vd({backend:c,systemAudio:e.audio?.source==="system",replay:e.replayBufferSec!==void 0,webcam:!!e.webcam,logs:!!e.logs,perf:!!e.perf},{windowHwnd:!!a?.hwnd,wgcAvailable:c==="wgc"&&ir()});let u=e.replayBufferSec!==void 0?Ld(e.replayBufferSec):null,d=e.fps??vi,p=e.quality??$i,f=yp(e.maxDurationSec),m=er(e.output,we("recordings"),`rec-${ge()}-${be()}.mp4`,e.overwrite),h=e.audio?.source==="system"?{device:await jm(e.audio.device)}:void 0,b=e.webcam?await Bm(e.webcam.device):void 0,w=c==="ddagrab"?em(Ti(i,s),await Zd()):null;if(!xf.has(e)){let $=$d({target:Ft(e.target,a),replayBufferSec:u?.bufferSec,maxDurationSec:f,audioDevice:h?.device,webcamDevice:b,events:!!e.events,focus:e.focus,elements:e.elements,hotkeys:e.hotkeys,output:m});await Ot(t,$,r.signal)}let g=await Kd(e.encoder??(c==="ddagrab"?"auto":"x264"),c==="ddagrab"?"ddagrab":"gdigrab",n,void 0,c==="wgc"?void 0:E0(i,s)),y=async $=>!w||$.gpuFrames||await Qd(n);if(!await y(g))throw new l("Desktop Duplication (ddagrab) does not capture on this machine (a remote session, or no D3D11 GPU).",'Use backend "gdigrab".');return{ffmpeg:n,hideCursor:o,target:i,monitors:s,window:a,backend:c,replay:u,fps:d,quality:p,maxDurationSec:f,output:m,audio:h,webcamDevice:b,dda:w,firstPick:g,ddaUsable:y}}function O0(t,e,r){let{target:n,monitors:o,window:i,backend:s,output:a,fps:c,quality:u,maxDurationSec:d,replay:p,audio:f,webcamDevice:m}=e,h=bu(r.watch,s,r.spawnedAt),b=t.events?Ti(n,o):null;if(s==="wgc"&&b&&i?.client){let g=/wgc: (\d+)x(\d+)/.exec(r.watch.head());b={x:i.client.x,y:i.client.y,w:g?Number(g[1]):b.w,h:g?Number(g[2]):b.h}}let w=kd({id:r.id,target:t.target,output:a,fps:c,quality:u,pid:r.child.pid??null,spawnedAt:r.spawnedAt,startMs:h,maxDurationSec:d,window:i,backend:s,encoder:r.encoder,...r.evPaths?{events:{jsonl:r.evPaths.jsonl,raw:r.evPaths.raw,keys:r.keyMode,frame:b}}:{},...p?{replay:p}:{},...s!=="wgc"?{capture:{target:n,opts:r.captureOpts,...r.webcam?{webcam:r.webcam}:{}}}:{},...m&&r.webcamRaw?{webcam:{device:m,rawPath:r.webcamRaw,startMs:_0(r.watch,!!f).webcamStartMs,corner:t.webcam?.corner,size:t.webcam?.size,shape:t.webcam?.shape}}:{},processImage:s==="wgc"?wf(process.execPath).toLowerCase():"ffmpeg.exe",identity:um()});return{startMs:h,frame:b,record:w}}function N0(t,e,r){t.attachChild(e.id,r);try{t.create(e)}catch(n){throw t.detachChild(e.id),new l(`Recording stopped: the session registry could not be written (${U(n)}).`)}}function vf(t){let e=t.registerTool("start_recording",{title:"Start Recording",description:"Start a background screen recording. Returns a session id; finalize it with stop_recording. Never auto-starts.",inputSchema:$0,outputSchema:N({sessionId:oe.string(),status:oe.string(),backend:oe.string(),outputPath:oe.string()}),annotations:I},async(r,n)=>{if(r.startWhen)return I0(t,e,r,n);let o=()=>{},i=new Su;try{o=Gm();let s=await F0(t,r,n),{ffmpeg:a,hideCursor:c,target:u,monitors:d,window:p,backend:f,replay:m,fps:h,quality:b,maxDurationSec:w,output:g,audio:y,webcamDevice:$,dda:S,firstPick:C,ddaUsable:M}=s;i.output=g,$&&(i.webcamRaw=Ui(g,0),x0(bt(g),{recursive:!0})),m&&(jd(m),i.replay=m);let R=r.keys??tp,P=r.events?m?{raw:xu(m.dir,"events.raw"),jsonl:""}:$e(g):null;P&&!m&&yi(P,r.overwrite),i.evPaths=P;let j=r.logs?new ks(r.logs):null;await j?.mark();let X=()=>{};i.logger=P?await op(P.raw,R,{...m?{rotateSec:Nd(m.bufferSec)}:{},...r.focus?{focus:r.focus}:{},...r.elements?{elements:!0}:{},...r.hotkeys?{hotkeys:!0,onHotkey:z=>X(z)}:{}}):null;let D=`rec-${ge()}-${be(6)}`,ae={id:D,ffmpeg:a,backend:f,target:u,monitors:d,window:p,fps:h,quality:b,audio:y,hideCursor:c,dda:S,webcamDevice:$,webcamRaw:i.webcamRaw,output:g,maxDurationSec:w,replay:m},ee=await Vd(C,z=>T0(ae,z),{why:z=>Io(z.watch,3),canFallback:()=>M({encoder:"x264",gpuFrames:!1}),beforeRetry:()=>{m&&Ud(m)}}),{run:J,failure:ie,pick:ce}=ee,{child:x,watch:q,spawnedAt:H,captureOpts:de,webcam:G}=J;if(J.settled==="exited")throw new l(`Recording failed to start (${f==="wgc"?"window capture":"ffmpeg"} exited immediately):
315
- ${Io(q)}`+(ie?`
316
- (Retried with libx264 after ${ie})`:""));i.child=x;let{startMs:Q,frame:te,record:T}=O0(r,s,{id:D,child:x,watch:q,spawnedAt:H,captureOpts:de,webcam:G,encoder:ce.encoder,evPaths:P,keyMode:R,webcamRaw:i.webcamRaw}),_=re();N0(_,T,x),i.handOff();let A=i.logger;return A&&P&&A0(_,D,{logger:A,evPaths:P,keyMode:R,startMs:Q,frame:te,replay:m,child:x}),wu(_,D,x,{backend:f,maxDurationSec:w,spawnedAt:H,watch:q}),r.perf&&R0(_,D,{output:g,startMs:Q,window:p}),j&&r.logs&&M0(_,D,{tailer:j,logs:r.logs,output:g,startMs:Q}),r.hotkeys&&(X=C0(_,D)),r.stopWhen&&P0(_,D,{target:r.target,exactTitle:r.exactTitle,text:r.stopWhen.text}),v(Ed({record:T,audioDevice:y?.device,maxDurationSec:w,encoder:ce.encoder,encoderNote:ce.note,...S?{gpuFrames:ce.gpuFrames}:{},webcamDevice:$,window:p,...P?{events:{jsonl:P.jsonl,keys:R}}:{},...r.logs?{logs:{path:Lt(g),missing:r.logs.some(z=>!y0(z.path))}}:{},...r.hotkeys?{hotkeys:{taken:A?sp(A):[]}}:{},...m?{replay:{...m,events:!!P}}:{}}))}catch(s){return await i.release(),E(s)}finally{o()}})}import{z as Rn}from"zod";import{existsSync as Ts}from"node:fs";function $f(t){return{saved:t.saved,discarded:t.discarded,...t.save?{durationSec:t.save.durationSec,eventsPath:t.save.eventsPath}:{},...t.error?{error:t.error,note:"The buffer was kept; call stop_recording with save: true again, or save_replay."}:{}}}async function D0(t,e){if(t.error||!Ts(t.path))return{error:t.error??`No webcam file was written (${t.path}).`};let r=async a=>{try{let c=await L(a);return c.width&&c.height?{width:c.width,height:c.height}:null}catch{return null}},[n,o]=await Promise.all([r(e),r(t.path)]),i=t.shape==="circle",s=n&&o?hd(n,i?{width:1,height:1}:o,t.corner,t.size):null;return{path:t.path,...s?{overlay:{input:e,overlay:t.path,x:s.x,y:s.y,...i?{height:s.height,shape:"circle"}:{width:s.width}},note:"Aligned with the recording: pass `overlay` to the overlay tool (any corner or size works)."}:{}}}var L0={sessionId:Rn.string().min(1).describe("Session id returned by start_recording."),save:Rn.boolean().optional().describe("Replay buffer: write it all to outputPath first (default: discard).")};function kf(t){t.registerTool("stop_recording",{title:"Stop Recording",description:"Stop a recording gracefully so the file is finalized; returns the path and duration.",inputSchema:L0,outputSchema:N({sessionId:Rn.string(),status:Rn.string(),outputPath:Rn.string(),durationSec:Rn.number().nullable()}),annotations:Gi},async e=>{try{let r=re(),n=e.sessionId;if($s(n)){let f=Po(n);if(!f)throw new l(`No armed recording with id "${n}".`);f.status==="starting"&&(f=await nf(n)??f);let m={sessionId:n,outputPath:"",durationSec:null};if(uu(n))return v({...m,status:"cancelled",note:"Disarmed; nothing was recorded."});if(!f.sessionId)return v({...m,status:f.status,...f.error?{error:f.error}:{}});n=f.sessionId}let o=r.get(n);if(!o)throw new l(`No session with id "${e.sessionId}".`);if(o.status!=="recording"&&o.status!=="paused"){let f=o.replay&&Ts(o.replay.dir)?await Ki(o.replay,{save:e.save??!1,output:o.outputPath,quality:o.quality,tools:k}):void 0,m=o.durationSec??null;return m===null&&!o.segments?.parts.length&&Ts(o.outputPath)&&(m=await se(o.outputPath,{ffprobe:k().ffprobe}).catch(()=>null),m!==null&&r.tryUpdate(o.id,{durationSec:m})),v({...f?{replay:$f(f)}:{},sessionId:o.id,status:o.status,outputPath:o.outputPath,durationSec:m,endReason:o.endReason??null,note:o.endReason==="max_duration"?`Recording already ended at its maxDurationSec cap (${o.maxDurationSec}s).`:o.endReason==="window_closed"?"Recording already ended: the recorded window was closed.":"Session was not active; returning its recorded final state."})}let i=cm(o,process.pid,Gc(o));if(i)throw new l(i);let{ffprobe:s}=k(),{record:a,graceful:c,durationSec:u,replay:d,segments:p}=await To(r,o,{reason:"stopped",probe:f=>se(f,{ffprobe:s}),saveReplay:e.save});return v({sessionId:o.id,status:"stopped",outputPath:o.outputPath,durationSec:u??null,finalizedGracefully:c,...d?{replay:$f(d)}:{},...p&&p.count>1?{segmentsJoined:p.count}:{},...p?.error?{segmentsError:p.error}:{},...a?.webcam?{webcam:await D0(a.webcam,o.outputPath)}:{},...a?.events?{eventsPath:a.events.path,events:a.events.summary??{},...a.events.error?{eventsError:a.events.error}:{}}:{},fileExists:Ts(o.outputPath),note:c?"ffmpeg quit cleanly; file finalized.":"Process terminated by pid; fragmented mp4 keeps the file playable.",record:a})}catch(r){return E(r)}})}import{z as hr}from"zod";import{existsSync as jo,lstatSync as uh,readdirSync as lh,rmSync as I$,statSync as F$}from"node:fs";import{dirname as O$,resolve as ph}from"node:path";import{createHash as Uf}from"node:crypto";import{closeSync as f$,existsSync as Mn,openSync as h$,readFileSync as g$,readdirSync as b$,readSync as w$,renameSync as y$,statSync as zf,writeFileSync as x$}from"node:fs";import{basename as Hf,dirname as S$,join as Cn,resolve as Ds}from"node:path";import{closeSync as G0,existsSync as ku,openSync as q0,readSync as X0,statSync as J0}from"node:fs";import{basename as Rs,isAbsolute as Y0,join as Eu}from"node:path";function St(t,e,r){if(t.length<e)throw new Error(`Truncated font: ${r}.`);return t}function B0(t,e){let r=St(t(0,12),12,"header");if(r.toString("latin1",0,4)!=="ttcf"){if(e!==0)throw new Error("Not a font collection; only face 0 exists.");return 0}let n=r.readUInt32BE(8);if(e<0||e>=n)throw new Error(`Face ${e} is out of range (collection has ${n}).`);return St(t(12+e*4,4),4,"collection offsets").readUInt32BE(0)}var As=class{ranges=[];add(e,r){let n=this.ranges[this.ranges.length-1];n&&e<=n[1]+1?n[1]=Math.max(n[1],r):this.ranges.push([e,r])}};function W0(t){let e=St(t,14,"cmap format 4").readUInt16BE(6),r=14,n=r+e+2,o=n+e,i=o+e;St(t,i+e,"cmap format 4 segments");let s=new As;for(let a=0;a<e/2;a++){let c=t.readUInt16BE(r+a*2),u=t.readUInt16BE(n+a*2),d=t.readUInt16BE(o+a*2),p=t.readUInt16BE(i+a*2);if(!(u>c))for(let f=u;f<=c&&f!==65535;f++){let m;if(p===0)m=f+d&65535;else{let h=i+a*2+p+(f-u)*2;m=h+2<=t.length?t.readUInt16BE(h):0,m!==0&&(m=m+d&65535)}m!==0&&s.add(f,f)}}return s.ranges}function j0(t,e){let r=St(t,16,`cmap format ${e}`).readUInt32BE(12);St(t,16+r*12,`cmap format ${e} groups`);let n=[];for(let i=0;i<r;i++){let s=t.readUInt32BE(16+i*12),a=Math.min(t.readUInt32BE(20+i*12),1114111);if(t.readUInt32BE(24+i*12)===0){if(e===13)continue;s++}s<=a&&n.push([s,a])}n.sort((i,s)=>i[0]-s[0]);let o=new As;for(let[i,s]of n)o.add(i,s);return o.ranges}function U0(t,e){return t===3&&e===10?0:t===0&&(e===4||e===6)?1:t===3&&e===1?2:t===0&&e<=3?3:-1}function Ef(t,e=0){let r=B0(t,e),n=St(t(r,12),12,"sfnt header"),o=n.toString("latin1",0,4);if(o!=="\0\0\0"&&o!=="OTTO"&&o!=="true")throw new Error("Not a TrueType/OpenType font.");let i=n.readUInt16BE(4),s=St(t(r+12,i*16),i*16,"table directory"),a=-1;for(let f=0;f<i;f++)s.toString("latin1",f*16,f*16+4)==="cmap"&&(a=s.readUInt32BE(f*16+8));if(a<0)throw new Error("Font has no cmap table.");let u=St(t(a,4),4,"cmap header").readUInt16BE(2),d=St(t(a+4,u*8),u*8,"cmap records"),p=[];for(let f=0;f<u;f++){let m=U0(d.readUInt16BE(f*8),d.readUInt16BE(f*8+2));m>=0&&p.push({rank:m,offset:a+d.readUInt32BE(f*8+4)})}p.sort((f,m)=>f.rank-m.rank);for(let{offset:f}of p){let m=t(f,8);if(m.length<8)continue;let h=m.readUInt16BE(0);if(h===4)return W0(t(f,m.readUInt16BE(2)));if(h===12||h===13)return j0(t(f,m.readUInt32BE(4)),h)}throw new Error("Font has no Unicode cmap subtable this reader understands (formats 4, 12, 13).")}function z0(t,e){let r=0,n=t.length-1;for(;r<=n;){let o=r+n>>1,[i,s]=t[o];if(e<i)n=o-1;else if(e>s)r=o+1;else return!0}return!1}function H0(t){return!(t<32||t>=127&&t<160||t===173||t===847||t===1564||t===65279||t>=8203&&t<=8207||t>=8234&&t<=8238||t>=8288&&t<=8303||t>=65024&&t<=65039||t>=917504&&t<=921599)}function Fo(t,e){let r=new Set,n=[];for(let o of t){let i=o.codePointAt(0);r.has(i)||(r.add(i),H0(i)&&!z0(e,i)&&n.push(o))}return n}var K0={regular:"Inter-Regular.ttf",bold:"Inter-Bold.ttf"};function Bt(t="bold"){return vn("fonts",K0[t])}function ye(t){return t.replace(/\\/g,"/").replace(/:/g,"\\\\:").replace(/'/g,"\\\\\\'").replace(/([,;[\]])/g,"\\$1")}var V0={segoe:{name:"Segoe UI",regular:["segoeui.ttf"],bold:["segoeuib.ttf","segoeui.ttf"]},japanese:{name:"Yu Gothic",regular:["YuGothM.ttc","meiryo.ttc","msgothic.ttc"],bold:["YuGothB.ttc","meiryob.ttc","YuGothM.ttc","msgothic.ttc"]},chineseSimplified:{name:"Microsoft YaHei",regular:["msyh.ttc","simsun.ttc"],bold:["msyhbd.ttc","msyh.ttc","simsun.ttc"]},chineseTraditional:{name:"Microsoft JhengHei",regular:["msjh.ttc","mingliub.ttc"],bold:["msjhbd.ttc","msjh.ttc"]},korean:{name:"Malgun Gothic",regular:["malgun.ttf"],bold:["malgunbd.ttf","malgun.ttf"]},indic:{name:"Nirmala UI",regular:["Nirmala.ttc","Nirmala.ttf"],bold:["NirmalaB.ttf","Nirmala.ttc","Nirmala.ttf"]},thai:{name:"Leelawadee UI",regular:["LeelawUI.ttf","tahoma.ttf"],bold:["LeelaUIb.ttf","LeelawUI.ttf","tahomabd.ttf"]},ethiopic:{name:"Ebrima",regular:["ebrima.ttf"],bold:["ebrimabd.ttf","ebrima.ttf"]},emoji:{name:"Segoe UI Emoji",regular:["seguiemj.ttf"],bold:["seguiemj.ttf"]},symbol:{name:"Segoe UI Symbol",regular:["seguisym.ttf"],bold:["seguisym.ttf"]}},Q0=["segoe","japanese","chineseSimplified","chineseTraditional","korean","indic","thai","ethiopic","emoji","symbol"];function Z0(t){let e=[];return/[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9f]/u.test(t)&&e.push("japanese"),/[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]/u.test(t)&&e.push("korean"),new RegExp("\\p{Script=Han}","u").test(t)&&e.push("chineseSimplified"),[...e,...Q0.filter(r=>!e.includes(r))].map(r=>V0[r])}function e$(t,e){let r=null;for(let n of e){let o=Fo(t,n.coverage);if(o.length===0)return{fontFile:n.path,missing:o};(!r||o.length<r.missing.length)&&(r={fontFile:n.path,missing:o})}return r}function Tf(){return Eu(process.env.WINDIR??process.env.SystemRoot??"C:\\Windows","Fonts")}var _f=new Map;function vu(t){let e=_f.get(t);if(e!==void 0)return e;let r,n=null;try{n=q0(t,"r");let o=n;r=Ef((s,a)=>{let c=Buffer.alloc(a);return c.subarray(0,X0(o,c,0,a,s))})}catch{r=null}finally{n!==null&&G0(n)}return _f.set(t,r),r}function t$(t){if(ku(t)&&J0(t).isFile())return t;if(!Y0(t)&&Rs(t)===t){let e=Eu(Tf(),t);if(ku(e))return e}throw new l(`Font file not found: ${t}`,"Pass a path to a .ttf, .otf or .ttc file, or the file name of a font in C:\\Windows\\Fonts.")}function $u(t){let e=t.replace(/\s+/g," ").trim();return`"${e.length>40?`${e.slice(0,39)}\u2026`:e}"`}function vt(t,e={}){if(e.fontFile){let c=t$(e.fontFile),u=vu(c);if(!u)return{fontFile:c,missing:[],fallback:!1,warning:`Could not read the character map of ${Rs(c)}; glyph coverage of ${$u(t)} was not checked.`};let d=Fo(t,u);return d.length===0?{fontFile:c,missing:d,fallback:!1}:{fontFile:c,missing:d,fallback:!1,warning:`${Rs(c)} has no glyph for ${d.join(" ")} in ${$u(t)}; they render as empty boxes.`}}let r=e.weight??"bold",n=Bt(r),o=vu(n);if(o&&Fo(t,o).length===0)return{fontFile:n,missing:[],fallback:!1};let i=e.fontsDir??Tf(),s=o?[{path:n,coverage:o}]:[];for(let c of Z0(t))for(let u of c[r]){let d=Eu(i,u),p=ku(d)?vu(d):null;if(p){if(Fo(t,p).length===0)return{fontFile:d,missing:[],fallback:!0};s.push({path:d,coverage:p});break}}let a=e$(t,s)??{fontFile:n,missing:[]};return a.missing.length===0?{...a,fallback:a.fontFile!==n}:{...a,fallback:a.fontFile!==n,warning:`No available font draws ${a.missing.join(" ")} in ${$u(t)}; they render as empty boxes (drawn with ${Rs(a.fontFile)}). Pass fontFile with a font that covers them.`}}import{mkdtempSync as r$,rmSync as n$,writeFileSync as o$}from"node:fs";import{join as _u}from"node:path";import{tmpdir as i$}from"node:os";var Oo=12,Af=48,No=320;function Ms(t,e){if(!(t>0))throw new l("Could not read the video's duration.");return Array.from({length:e},(r,n)=>Math.round((n+.5)*t/e*1e3)/1e3)}function Fe(t){let e=Math.round(Math.max(0,t)*10),r=Math.floor(e/36e3),n=Math.floor(e%36e3/600),o=e%600/10;return r>0?`${r}:${String(n).padStart(2,"0")}:${String(Math.floor(o)).padStart(2,"0")}`:`${n}:${o.toFixed(1).padStart(4,"0")}`}function s$(t,e){let r=t<=4?t:Math.ceil(Math.sqrt(t)),n=Math.max(1,Math.min(t,e??r));return{columns:n,rows:Math.ceil(t/n)}}function a$(t,e,r,n,o,i){if(!Number.isInteger(n)||n<64)throw new l("tileWidth must be an integer of at least 64.");let s=Math.max(12,Math.round(n/16)),a=`drawtext=fontfile=${ye(o)}:textfile=${ye(i)}:expansion=none:fontcolor=white:fontsize=${s}:x=6:y=h-text_h-6:box=1:boxcolor=black@0.6:boxborderw=4`;return["-y","-v","error","-ss",String(e),"-i",t,"-frames:v","1","-vf",`scale=${n}:-2,${a}`,...Ee(r)]}function c$(t,e,r){return["-y","-v","error","-framerate","1","-i",t,"-vf",`tile=${e.columns}x${e.rows}:padding=4:margin=4:color=black`,"-frames:v","1",...Ee(r)]}function Rf(t,e,r,n){if(!(e>0))throw new l("Could not read the video's duration.");let o=30,i=Math.max(1e-4,o/e);return["-y","-v","error","-i",t,"-vf",`fps=${i.toFixed(4)},thumbnail=${o},scale='min(${n},iw)':-2`,"-frames:v","1",...Ee(r)]}async function Cs(t,e,r,n,o){let i=s$(e.length,n.columns),s=r$(_u(i$(),"screencast-sheet-"));try{let a=Bt("bold");await He(e,async(c,u)=>{let d=_u(s,`label_${u}.txt`);o$(d,Fe(c));let p=_u(s,`tile_${String(u).padStart(3,"0")}.png`);await Z(a$(t,c,p,n.tileWidth,a,d),6e4,{signal:o})}),await Z(c$(un(s,"tile_%03d.png"),i,r),6e4,{signal:o})}finally{n$(s,{recursive:!0,force:!0})}return i}import{existsSync as Ps}from"node:fs";var Mf=t=>Math.round(t*1e3)/1e3,u$={input_not_seen:"input went to an elevated window or the lock screen, or the hook was removed",helper_stalled:"the event logger paused",helper_stopped:"the event logger stopped"};function Tu(t){return t.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Au(t){let e=Tu(t.role),r=t.app?` in ${t.app}`:"";return t.name?`the "${t.name}" ${e}${r}`:`${/^[aeiou]/.test(e)?"an":"a"} ${e}${r}`}function Cf(t,e,r){let n=e?"double-click":"click",o=t&&t!=="left"?`${t.charAt(0).toUpperCase()}${t.slice(1)} ${n}`:`${n.charAt(0).toUpperCase()}${n.slice(1)}`;return r.element?.name?`${o} ${Au(r.element)}`:r.inFrame?`${o} at (${r.x}, ${r.y})`:`${o} outside the recorded area`}function Ru(t){let e=[],r=[...t].sort((s,a)=>s.t-a.t),n=null,o=null,i=(s,a)=>{let c=s==="vertical"?a>=0?"up":"down":a>=0?"right":"left",u=Math.abs(a);return`Scroll ${c} ${u} notch${u===1?"":"es"}`};for(let s of r)if(!(s.type==="move"||s.type==="up")){if(s.type!=="wheel"&&(o=null),s.type==="down"){let a=n;if(a&&a.e.button===s.button&&s.t-a.e.t<=.5&&Math.abs(s.x-a.e.x)<=6&&Math.abs(s.y-a.e.y)<=6&&a.step.action==="click"&&e.at(-1)===a.step){a.step.action="double_click",a.step.text=Cf(s.button,!0,a.e),n=null;continue}let c={t:s.t,action:"click",text:Cf(s.button,!1,s),x:s.x,y:s.y,button:s.button??"left",inFrame:s.inFrame,...s.element?{element:s.element}:{}};e.push(c),n={e:s,step:c};continue}if(n=null,s.type==="wheel"){let a=s.axis??"vertical",c=s.delta??0;if(o&&o.axis===a&&s.t-o.last<=1&&Math.sign(c)===Math.sign(o.notches)){o.notches+=c,o.last=s.t,o.step.text=i(a,o.notches);continue}let u={t:s.t,action:"scroll",text:i(a,c),x:s.x,y:s.y,inFrame:s.inFrame};e.push(u),o={step:u,axis:a,notches:c,last:s.t}}else if(s.type==="key")e.push({t:s.t,action:"shortcut",text:`Press ${s.keys??"a shortcut"}`,...s.keys?{keys:s.keys}:{}});else if(s.type==="typing"){let a=s.durationSec??0;e.push({t:s.t,action:"typing",text:`Type${a>0?` for ${Mf(a)} s`:""} (keys are not logged)`,durationSec:a})}else if(s.type==="focus"){let a=s.app??"another app";e.push({t:s.t,action:"switch",text:s.title?`Switch to "${s.title}" (${a})`:`Switch to ${a}`})}else if(s.type==="gap"){let a=u$[s.reason??"input_not_seen"],c=Mf(s.durationSec??0);e.push({t:s.t,action:"gap",text:`Input may be missing for ${c} s (${a})`,durationSec:c})}}return e}function Mu(t){return Ru(t).map(({button:e,inFrame:r,keys:n,durationSec:o,element:i,...s})=>s)}var Cu=30,Is=600,Pu=1,Fs=100,Iu=20,Ge=iu(["\\b(?:sk|pk|rk)-[a-z0-9_-]{8,}","\\bgh[pousr]_[a-z0-9]{10,}","\\bgithub_pat_[a-z0-9_]{10,}","\\bxox[abprs]-[a-z0-9-]{8,}","\\bAKIA[0-9A-Z]{12,}","\\bAIza[0-9a-z_-]{20,}","\\beyJ[a-z0-9_-]{8,}\\.[a-z0-9_-]{8,}","(?:api.?key|secret|token|passw(?:or)?d|bearer|authorization)\\s*[:=]?\\s*\\S+"].join("|")),Os=iu("error|exception|fail(?:ed|ure)?|fatal|crash|denied|refused|not found|cannot|can't|unable|invalid|timed? ?out|traceback|panic|unhandled|warning"),Wt={markdown:"report.md",json:"report.json",clip:"clip.mp4",contactSheet:"contact-sheet.png",gif:t=>`repro.${t}`},Do=t=>Math.round(t*1e3)/1e3;function If(t,e={}){if(!(t>0))throw new l("Could not read the recording's duration.");let r=Math.min(e.end??t,t),n=e.clipSec??Cu,o=e.start??Math.max(0,r-n);if(o>=t)throw new l(`start ${o}s is past the end of the ${Do(t)}s recording.`);if(!(r>o))throw new l("end must be after start.");if(r-o>Is)throw new l(`The clip would be ${Do(r-o)}s; at most ${Is}s. Narrow start/end.`);return{start:Do(o),end:Do(r)}}function l$(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),n=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);return r<=0||n<=0?!1:r*n>=.5*Math.min(t.width*t.height,e.width*e.height)}function Ff(t){let e=[];for(let r of[...t].sort((n,o)=>n.start-o.start)){let n=e.find(s=>r.start<=s.end&&l$(s,r));if(!n){e.push({...r});continue}let o=Math.min(n.x,r.x),i=Math.min(n.y,r.y);n.width=Math.max(n.x+n.width,r.x+r.width)-o,n.height=Math.max(n.y+n.height,r.y+r.height)-i,n.x=o,n.y=i,n.start=Math.min(n.start,r.start),n.end=Math.max(n.end,r.end)}return e}var p$="[REDACTED]";function Oe(t,e){if(t.length===0)return[];let r=$n(t,e);return t.map((n,o)=>{let i=[...r[o]??[]].sort((c,u)=>c[0]-u[0]),s="",a=0;for(let[c,u]of i)u<=a||(s+=n.slice(a,Math.max(a,c))+(c>=a?p$:""),a=u);return s+n.slice(a)})}function Of(t,e,r){let n=new Map;for(let a of t){let c=new Set(yt(a.lines,e,!0).map(u=>u.line));for(let u of c){let d=Dt(u),p=n.get(d);p?p.lastSeen=a.t:n.set(d,{text:u,firstSeen:a.t,lastSeen:a.t})}}let o=t.at(-1)?.t,i=[...n.values()].sort((a,c)=>+(c.lastSeen===o)-+(a.lastSeen===o)||a.firstSeen-c.firstSeen).slice(0,Iu);if(!r)return i;let s=Oe(i.map(a=>a.text),r);return i.map((a,c)=>({...a,text:s[c]??a.text}))}var d$=t=>`\`${t.replace(/`/g,"'").replace(/\s+/g," ").trim()}\``,Pf=t=>t.replace(/\|/g,"\\|").replace(/\s*\n\s*/g," ");function Nf(t){let e=[`# ${t.title.replace(/\s*\n\s*/g," ")}`,""],r=`${Fe(t.clip.start)}-${Fe(t.clip.end)}`;if(e.push(`Recorded repro: ${t.clip.width}x${t.clip.height}, clip ${r} of a ${Fe(t.clip.recordingDurationSec)} recording.`,""),(t.actual||t.expected)&&(t.actual&&e.push("**Actual:** "+t.actual.trim(),""),t.expected&&e.push("**Expected:** "+t.expected.trim(),"")),e.push("## Steps to reproduce",""),t.steps.length===0?e.push(`_${t.stepsNote??"No input events in the recording."} Add the steps by hand._`,""):(e.push("From the recording's input event log; times are on the recording's clock, positions in video pixels.",""),t.steps.forEach((i,s)=>e.push(`${s+1}. \`${Fe(i.t)}\` ${i.text}`)),t.stepsOmitted&&e.push("",`_${t.stepsOmitted} more steps not shown (see report.json)._`),e.push("")),e.push("## Error text on screen",""),t.ocr!=="read")e.push("_Not read: Windows OCR is unavailable here._","");else if(t.errors.length===0)e.push("_None found by OCR in the clip._","");else{e.push("Read by OCR (best-effort, may contain misreads); times from the clip start.","");for(let i of t.errors){let s=i.firstSeen===i.lastSeen?Fe(i.firstSeen):`${Fe(i.firstSeen)}-${Fe(i.lastSeen)}`;e.push(`- \`${s}\` ${d$(i.text)}`)}e.push("")}if(t.perf&&t.perf.length>0&&e.push("## Resource usage","",...t.perf.map(i=>`- ${i}`),""),t.logs)if(e.push("## App logs",""),t.logs.length===0)e.push("_No log lines during the clip._","");else{e.push("Lines the app logged during the clip (and the 5 s before it); times from the clip start.","","```text");for(let i of t.logs)e.push(`${i.t<0?"-":""}${Fe(Math.abs(i.t))} [${i.source}] ${i.line.replace(/\x60{3}/g,"'''")}`);e.push("```","")}if(e.push("## Recording",""),t.files.gif&&e.push("<!-- GitHub does not upload local files from --body-file: drag the GIF and clip into the issue, or replace these links with the uploaded URLs. -->",`![Repro](${t.files.gif})`,""),e.push(`- Clip: [${t.files.clip}](${t.files.clip}) (${Do(t.clip.end-t.clip.start)} s)`),t.files.gif&&t.gif){let i=(t.gif.sizeBytes/1e6).toFixed(1);e.push(`- ${t.gif.format==="gif"?"GIF":"WebP"}: [${t.files.gif}](${t.files.gif}) (${i} MB${t.gif.withinBudget?"":", over the size budget"})`)}t.files.contactSheet&&e.push(`- Contact sheet: [${t.files.contactSheet}](${t.files.contactSheet})`),e.push(""),e.push("## Environment","","| | |","|---|---|");for(let[i,s]of t.environment)e.push(`| ${Pf(i)} | ${Pf(s)} |`);e.push("");let n=t.redaction,o=n.found+n.manual;return e.push("<sub>",n.scanned?`Secret scan: OCR every ${n.everySec} s over ${n.framesScanned} frames; ${o} region${o===1?"":"s"} boxed out of the media. OCR is best-effort: review the clip before posting.`:`Not scanned for secrets${n.manual>0?` (${n.manual} region${n.manual===1?"":"s"} boxed out by hand)`:""}: review the clip before posting.`,`Generated by screencast-mcp bug_report, ${t.createdAt}.`,"</sub>",""),e.join(`
317
- `)}async function Ns(t){if(t.sessionId!==void 0){let n=re().get(t.sessionId);if(!n)throw new l(`No session with id "${t.sessionId}".`);if(n.status==="recording"||n.status==="paused")throw new l("The recording is still running; stop_recording it first.");if(await Kt(n.id),!Ps(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path;return{path:n.outputPath,eventsPath:o&&Ps(o)?o:null,record:n}}let e=t.input;if(!Ps(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=$e(e);return{path:e,eventsPath:Ps(r)?r:null}}var m$=40;function Df(t,e,r){let n=t.filter(i=>i.t>=e.start-5&&i.t<=e.end).slice(-m$),o=r?Oe(n.map(i=>i.line),r):n.map(i=>i.line);return n.map((i,s)=>({...i,t:Math.round((i.t-e.start)*1e3)/1e3,line:o[s]??i.line}))}function Lf(t,e,r){let n=t.filter(s=>s.t>=e.start&&s.t<=e.end).map(s=>({...s,t:s.t-e.start}));if(n.length===0)return[];let o=Tn(n),i=r?.exe??"the app";return[...o.peakCpu!==void 0?[`${i} CPU peaked at ${o.peakCpu}% of the machine`]:[],...o.peakRssMB!==void 0?[`${i} memory peaked at ${o.peakRssMB} MB (${o.rssGrowthMB>=0?"+":""}${o.rssGrowthMB} MB over the clip)`]:[],`Machine CPU peaked at ${o.peakSysCpu}%`,...o.busy.map(s=>`CPU pinned (>= 90%) from ${Fe(s.start)} to ${Fe(s.end)}`)]}var Fu=1,Ou=.03,Nu=120,Gf=600,v$=10,Ls=10,qf=50,Bf=200,$$=5,fr=t=>Math.round(t*1e3)/1e3;function Lo(t){return`${t}.index.json`}function Du(t){return`${t.replace(/\.[^./\\]+$/,"")}.index.json`}function Bo(t,e){let r=n=>process.platform==="win32"?Ds(n).toLowerCase():Ds(n);return r(t)===r(e)}function Bs(t,e,r){return typeof t.video=="string"&&Bo(t.video,e)?!0:r!==void 0&&!!t.fingerprint&&Gs(t.fingerprint,r)}function Ws(t,e){let r=Uf("sha1").update(Ds(t).toLowerCase()).digest("hex").slice(0,12),n=Hf(t).replace(/\.[^.]+$/,"");return Cn(e,"indexes",`${n}-${r}.index.json`)}function Xf(t,e){let r=Lo(t);try{return Zt(r),r}catch{return Ws(t,e)}}function js(t,e,r){for(let o of[Lo(t),Ws(t,e)])if(Mn(o))return o;let n=Du(t);if(n!==Lo(t)&&Mn(n)){let o=Wo(n);if(o&&Bs(o,t,r))return n}return null}function Jf(t,e){return t!==null&&Gs(t.fingerprint,e.fingerprint)&&t.sceneThreshold===e.sceneThreshold&&t.maxFrames===e.maxFrames&&(t.ocr||!e.ocrAvailable)}function Yf(t,e=Ge){return t.map(r=>r.ocr.length>0?{...r,ocr:Oe(r.ocr,e)}:r)}var k$=/\.(mp4|mkv|mov|webm|avi|m4v|wmv|flv|gif|ts|mpg|mpeg)$/i,Wf=t=>t.replace(/\.[^.]+$/,"").toLowerCase();function Us(t,e){let r=new Set(e.map(s=>s.toLowerCase())),n=Hf(t);if(r.has(`${n}.srt`.toLowerCase()))return{path:`${t}.srt`,ambiguous:!1};let o=`${n.replace(/\.[^.]+$/,"")}.srt`;return r.has(o.toLowerCase())?e.some(s=>s.toLowerCase()!==n.toLowerCase()&&k$.test(s)&&Wf(s)===Wf(n))?{path:null,ambiguous:!0}:{path:Cn(S$(t),o),ambiguous:!1}:{path:null,ambiguous:!1}}function Kf(t,e,r,n=v$){let o=mn(t.filter(i=>i.timeSec<e),r).map(fr);for(;o.length<r;){let i=-1,s=0;for(let a=0;a<o.length;a++){let c=(o[a+1]??e)-o[a];c>s&&(s=c,i=a)}if(i===-1||s<=n)break;o.splice(i+1,0,fr(o[i]+s/2))}return[...new Set(o)].sort((i,s)=>i-s)}function Vf(t,e){return t.map((r,n)=>({start:r,end:fr(t[n+1]??e)}))}function zs(t){return fr(t.start+Math.min(.25,(t.end-t.start)/2))}function Qf(t){let e=[];for(let r of t){let n=e.at(-1);n&&n.ocr.join(`
307
+ `)}function bu(t,e,r){return new Promise(n=>{let o=setTimeout(()=>n("running"),r==="wgc"?15e3:r==="ddagrab"?2e3:1200);r==="wgc"&&t.stderr?.on("data",()=>{ln(e.head())!==null&&(clearTimeout(o),n("running"))}),t.on("error",()=>{clearTimeout(o),n("exited")}),t.on("exit",()=>{clearTimeout(o),n("exited")})})}function wu(t,e,r){let n=ln(t.head());return n!==null?n:e==="ddagrab"?t.outputAt()??r:r}function yu(t,e,r,n){r.on("exit",o=>{let i=t.getChild(e);if(i&&i!==r)return;t.detachChild(e,r),md(e)||Gi(e);let s=t.get(e);if(!s||s.status!=="recording"||t.isStopping(e))return;let a=hm({code:o,backend:n.backend,maxDurationSec:n.maxDurationSec,elapsedMs:Date.now()-n.spawnedAt});ar(a.status==="failed"?"error":"notice",a.status==="failed"?`Recording ${e} failed: the recorder exited with code ${o}.`:`Recording ${e} ended on its own (${a.endReason}).`,{sessionId:e,...a}),t.tryUpdate(e,{...a,stoppedAt:new Date().toISOString(),...a.status==="failed"?{error:`${n.backend==="wgc"?"The window recorder":"ffmpeg"} exited with code ${o}:
308
+ ${Fo(n.watch)}`}:{}}),s.segments&&(s.segments.parts.length>0||s.webcam)?R0(t,s).catch(c=>{process.stderr.write(`Joining ${e}'s segments failed: ${z(c)}
309
+ `)}):T0(t,s).catch(c=>{process.stderr.write(`Reading ${e}'s duration failed: ${z(c)}
310
+ `)})})}async function T0(t,e){let{ffprobe:r}=k(),n=await ue(e.outputPath,{ffprobe:r});n!==null&&t.tryUpdate(e.id,{durationSec:n})}async function R0(t,e){let r=k();await Zt(e.id);let{patch:n,error:o}=await Kc(e,r),i=await ue(e.outputPath,{ffprobe:r.ffprobe});t.tryUpdate(e.id,{...n,durationSec:i??void 0,...o?{error:o}:{}})}function bf(t,e,r){return is(t,e.id,"resume",()=>A0(t,t.get(e.id)??e,r))}async function A0(t,e,r){let n=pd(e,t.ownsPaused(e.id));if(n)throw new l(`Cannot resume ${e.id}: ${n}.`);let o=e.segments,i=e.capture,s=e.backend??"gdigrab",a=ot(o.parts),c=ud(e.maxDurationSec,a),u=o.parts.length,d=cd(e.outputPath,u),p=i.webcam?zi(e.outputPath,u):void 0;(u>0||p)&&_0(yt(e.outputPath),{recursive:!0});let f=_i(i.target,{...i.opts,output:d,maxDurationSec:c,...i.webcam&&p?{webcam:{...i.webcam,output:p}}:{}}),m=Date.now(),h=E0(r,f,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),b=gu(h,e.id),w=()=>{let R=t.getChild(e.id);R&&R!==h||(u>0&&gf(d,{force:!0}),p&&gf(p,{force:!0}))};if(await bu(h,b,s)==="exited")throw w(),new l(`Resume failed (ffmpeg exited immediately); the recording stays paused:
311
+ ${Fo(b)}`);let g=wu(b,s,m),y=p?ln(b.head(),i.opts.audio?2:1):null;t.attachChild(e.id,h);let v=()=>{t.detachChild(e.id,h),h.pid!==void 0&&mr(h.pid),w()},x;try{x=t.update(e.id,{status:"recording",pid:h.pid??null,pidSpawnedAt:m,videoStartMs:g-a*1e3,segments:{parts:o.parts,current:{path:d,startMs:g,...p?{webcamPath:p,...y!==null?{webcamStartMs:y}:{}}:{}}}})}catch(R){throw v(),new l(`Resume stopped: the session registry could not be written (${z(R)}).`)}if(!x)throw v(),new l(`No session with id "${e.id}".`);return t.clearPaused(e.id),yu(t,e.id,h,{backend:s,maxDurationSec:c,spawnedAt:m,watch:b}),{record:x,recordedSec:a,capSec:c}}import{basename as xf,join as Su}from"node:path";var F0={target:ae.string().describe("full | monitor:<i> (0 = primary) | window:<title> (or window:exe=<app.exe> / window:hwnd=<n>) | region:<x>,<y>,<w>,<h>. With gdigrab a window's rectangle is resolved once at start (visible, on top); it does not follow the window."),exactTitle:ae.boolean().optional().describe("window: targets match the whole title only, never a substring (default false)."),fps:ae.number().int().min(1).max(120).optional().describe(`Frames per second (default ${$i}).`),quality:ae.enum(["draft","standard","high"]).optional().describe(`Encoder preset (default ${ki}).`),audio:ae.object({source:ae.enum(["system","none"]).describe("system = what the machine plays (needs a loopback device); none = video only."),device:ae.string().optional().describe("dshow loopback device (from list_audio_devices); auto-detected if omitted.")}).optional().describe("Audio (default none). No microphone capture."),output:ae.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:ae.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),maxDurationSec:ae.number().int().min(0).max(It).optional().describe(`Auto-stop after this many seconds (default ${Sc} or SCREENCAST_MAX_RECORDING_SEC; max 7 days; 0 = no cap).`),events:ae.boolean().optional().describe("Also log clicks, scroll, cursor, and typing (video-timed, video pixels) for read_events (default false; ~1 s slower start)."),keys:ae.enum(["masked","shortcuts"]).optional().describe("With events: masked (default) logs typing only as 0.5 s-grid bursts, never keys; shortcuts also names Ctrl/Alt/Win chords. Typed text is never logged."),focus:ae.enum(["app","title"]).optional().describe("Log app switches (implies events); title adds window titles."),logs:ae.array(ae.object({path:ae.string().min(1),label:ae.string().min(1).max(40).optional()})).min(1).max(lf).optional().describe("Log files to follow onto the video clock."),perf:ae.boolean().optional().describe("Sample CPU/memory (and a window's app) to <rec>.perf.jsonl."),hotkeys:ae.boolean().optional().describe("Ctrl+Alt+Shift+M adds a marker, +S stops (implies events)."),elements:ae.boolean().optional().describe('Name the UI element each click hits, e.g. "Save" button (implies events).'),cursor:ae.enum(["os","events"]).optional().describe("events: leave the OS cursor out and log it (implies events) for the cursor tool to redraw."),backend:ae.enum(["gdigrab","wgc","ddagrab"]).optional().describe("gdigrab (default): the screen rectangle. wgc (window: targets, FFmpeg 8+): the window's own surface, even when covered or moved; client area only. ddagrab: one display on the GPU, low CPU."),encoder:ae.enum(["auto","x264","nvenc","qsv","amf"]).optional().describe("auto = first working GPU encoder, else x264 (default with ddagrab; else x264)."),webcam:ae.object({device:ae.string().optional().describe("list_video_devices name (default: first)."),corner:ae.enum(["top_left","top_right","bottom_left","bottom_right"]).optional(),size:ae.number().min(.1).max(.5).optional().describe("Share of width (0.25)."),shape:ae.enum(["rect","circle"]).optional()}).optional().describe("Also record a camera to <output>.webcam.mp4, aligned for overlay."),replayBufferSec:ae.number().int().min(Ji).max($n).optional().describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab or ddagrab, not wgc."),startWhen:ae.object({window:ae.string().min(1).optional().describe('A window: target that must exist, e.g. "window:Error".'),text:ae.string().min(1).max(200).optional().describe("Text that must be on target (OCR)."),timeoutSec:ae.number().positive().max(nf).optional().describe(`Default ${cu}.`)}).optional().describe("Arm: start once these hold (stop_recording disarms)."),stopWhen:ae.object({text:ae.string().min(1).max(200)}).optional().describe("Stop once this text shows (OCR).")};async function Sf(t,e,r){let n=await ut(t,{exactTitle:e}),o=P0(Su(I0(),"screencast-trigger-"));try{let i=Su(o,"t.png");await Lt(n,i);let[s]=await lt([i],o);return!!s&&St(s.lines,r).length>0}finally{xu(o,{recursive:!0,force:!0})}}async function O0(t){try{return await ut(t.startsWith("window:")?t:`window:${t}`),!0}catch{return!1}}var vf=new WeakSet;function N0(t,e){try{let r=Ri(t,e);return{width:r.w,height:r.h}}catch{return}}function D0(t,e){let r=ln(t.head(),e?2:1);return r!==null?{webcamStartMs:r}:{}}var vu=class{output;webcamRaw;replay;evPaths;logger;child;owned=!0;handOff(){this.owned=!1}async release(){this.owned&&(this.owned=!1,this.child?.pid!==void 0&&this.child.exitCode==null&&mr(this.child.pid),this.logger&&await yi(this.logger),this.evPaths&&xu(this.evPaths.raw,{force:!0}),this.replay&&Yi(this.replay),this.webcamRaw&&this.output&&xu(yt(this.output),{recursive:!0,force:!0}))}};async function L0(t,e){let r=e.encoder!=="x264",n={fps:t.fps,quality:t.quality,monitors:t.monitors,audio:t.audio,drawMouse:!t.hideCursor,...t.dda?{videoInput:nm(t.dda,t.fps,{download:!e.gpuFrames,drawMouse:!t.hideCursor})}:{},...r?{videoCodec:dr(e.encoder,t.quality,{gpuFrames:e.gpuFrames})}:{}},o=t.webcamDevice?{device:t.webcamDevice,...r?{codec:dr(e.encoder,t.quality)}:{}}:void 0,i=_i(t.target,{...n,output:t.output,maxDurationSec:t.maxDurationSec,...o&&t.webcamRaw?{webcam:{...o,output:t.webcamRaw}}:{}}),s=t.replay?Ud(i,t.replay):i,a=Date.now(),c=t.backend==="wgc"?wf(process.execPath,[Bm(),JSON.stringify({ffmpeg:t.ffmpeg,hwnd:t.window.hwnd,fps:t.fps,encode:[...dr(e.encoder,t.quality),...vi(t.fps)],output:t.output,maxDurationSec:t.maxDurationSec,cursor:!t.hideCursor,...t.audio?{audioDevice:t.audio.device}:{}})],{stdio:["pipe","ignore","pipe"],windowsHide:!0}):wf(t.ffmpeg,s,{stdio:["pipe","ignore","pipe"],windowsHide:!0}),u=gu(c,t.id),d=await bu(c,u,t.backend);return{captureOpts:n,webcam:o,child:c,watch:u,spawnedAt:a,settled:d}}function B0(t,e,r){if(r.replay){let o=new Promise(i=>r.child.once("exit",()=>i()));ho(e,o.then(()=>yi(r.logger)));return}let n=r.frame;n&&ho(e,Eo(e).then(async()=>{await yi(r.logger);try{let o=Hi(t.get(e)?.segments,r.startMs,Date.now()),i=lp(r.evPaths,{...o,frame:n});t.tryUpdate(e,{events:{path:r.evPaths.jsonl,keys:r.keyMode,count:i.length,summary:pn(i)}})}catch(o){t.tryUpdate(e,{events:{path:r.evPaths.jsonl,keys:r.keyMode,error:z(o)}})}}).catch(o=>{process.stderr.write(`Event log for ${e} failed: ${z(o)}
312
+ `)}))}function W0(t,e,r){let n=new _s(r.window?.pid);n.start();let o=vt(r.output);t.tryUpdate(e,{perf:{path:o}}),ho(e,Eo(e).then(async()=>{try{let i=ff(n.stop(),Hi(t.get(e)?.segments,r.startMs,Date.now()));yf(o,hf(i));let s=r.window?.pid!==void 0?{pid:r.window.pid,...r.window.exe?{exe:r.window.exe}:{}}:void 0;t.tryUpdate(e,{perf:{path:o,summary:Mn(i,s)}})}catch(i){n.stop(),t.tryUpdate(e,{perf:{path:o,error:z(i)}})}}))}function j0(t,e,r){r.tailer.follow();let n=jt(r.output),o=r.logs.map(i=>i.label??xf(i.path));t.tryUpdate(e,{logs:{path:n,sources:o}}),ho(e,Eo(e).then(async()=>{try{let i=pf(await r.tailer.stop(),Hi(t.get(e)?.segments,r.startMs,Date.now()));yf(n,df(i)),t.tryUpdate(e,{logs:{path:n,sources:o,count:i.length,errors:i.filter(s=>s.level==="error").length}})}catch(i){t.tryUpdate(e,{logs:{path:n,sources:o,error:z(i)}})}}))}function $f(t,e,r){let n=t.get(e);if(!n||n.status!=="recording"&&n.status!=="paused")return;let{ffprobe:o}=k();Ro(t,n,{reason:"stopped",probe:i=>ue(i,{ffprobe:o})}).catch(i=>process.stderr.write(`${r} stop for ${e} failed: ${z(i)}
313
+ `))}function U0(t,e){return r=>{let n=t.get(e);if(!(!n||n.status!=="recording"&&n.status!=="paused")){if(r==="stop")return $f(t,e,"Hotkey");try{fs(t,e,"hotkey")}catch(o){process.stderr.write(`Hotkey marker for ${e} failed: ${z(o)}
314
+ `)}}}}function z0(t,e,r){let n=new AbortController;Eo(e).then(()=>n.abort()),du({checks:[()=>Sf(r.target,r.exactTitle,r.text)],timeoutMs:Number.POSITIVE_INFINITY,intervalMs:uu,signal:n.signal}).then(o=>{o==="met"&&$f(t,e,"stopWhen")})}async function H0(t,e,r,n){try{let o=r.startWhen;if(!o.window&&!o.text)throw new l("startWhen needs window and/or text.");let i=o.timeoutSec??cu,s={...o.window?{window:o.window}:{},...o.text?{text:o.text}:{}};await ut(r.target,{exactTitle:r.exactTitle,backend:r.backend}),await Dt(t,`When ${pu(s)} (within ${i} s), start recording ${Nt(r.target)}`+(r.events?", logging mouse clicks and typing":"")+"?",n.signal);let a={...r,startWhen:void 0};vf.add(a);let c=cf({conditions:s,target:r.target,timeoutSec:i,checks:[...o.window?[()=>O0(o.window)]:[],...o.text?[()=>Sf(r.target,r.exactTitle,o.text)]:[]],fire:async()=>{let u=e.handler,d=await u(a,{...n,signal:new AbortController().signal}),p=d.structuredContent;if(d.isError||!p?.sessionId)throw new Error(d.content.map(f=>f.text??"").join(" ")||"start failed");return p.sessionId}});return S({sessionId:c.id,status:"armed",backend:r.backend??"gdigrab",outputPath:"",waitingFor:pu(s),timeoutSec:i,note:"Nothing is recorded yet. get_session with this id shows when it starts (and its recording's sessionId); stop_recording with it disarms."})}catch(o){return E(o)}}async function G0(t,e,r){let{ffmpeg:n}=k(),o=e.cursor==="events";(o||e.focus||e.elements||e.hotkeys)&&(e.events=!0);let{target:i,monitors:s,window:a}=await ut(e.target,{exactTitle:e.exactTitle,backend:e.backend}),c=e.backend??"gdigrab";kd({backend:c,systemAudio:e.audio?.source==="system",replay:e.replayBufferSec!==void 0,webcam:!!e.webcam,logs:!!e.logs,perf:!!e.perf},{windowHwnd:!!a?.hwnd,wgcAvailable:c==="wgc"&&cr()});let u=e.replayBufferSec!==void 0?Wd(e.replayBufferSec):null,d=e.fps??$i,p=e.quality??ki,f=Sp(e.maxDurationSec),m=nr(e.output,we("recordings"),`rec-${he()}-${ge()}.mp4`,e.overwrite),h=e.audio?.source==="system"?{device:await zm(e.audio.device)}:void 0,b=e.webcam?await jm(e.webcam.device):void 0,w=c==="ddagrab"?rm(Ri(i,s),await tm()):null;if(!vf.has(e)){let v=Ed({target:Nt(e.target,a),replayBufferSec:u?.bufferSec,maxDurationSec:f,audioDevice:h?.device,webcamDevice:b,events:!!e.events,focus:e.focus,elements:e.elements,hotkeys:e.hotkeys,output:m});await Dt(t,v,r.signal)}let g=await Qd(e.encoder??(c==="ddagrab"?"auto":"x264"),c==="ddagrab"?"ddagrab":"gdigrab",n,void 0,c==="wgc"?void 0:N0(i,s)),y=async v=>!w||v.gpuFrames||await em(n);if(!await y(g))throw new l("Desktop Duplication (ddagrab) does not capture on this machine (a remote session, or no D3D11 GPU).",'Use backend "gdigrab".');return{ffmpeg:n,hideCursor:o,target:i,monitors:s,window:a,backend:c,replay:u,fps:d,quality:p,maxDurationSec:f,output:m,audio:h,webcamDevice:b,dda:w,firstPick:g,ddaUsable:y}}function q0(t,e,r){let{target:n,monitors:o,window:i,backend:s,output:a,fps:c,quality:u,maxDurationSec:d,replay:p,audio:f,webcamDevice:m}=e,h=wu(r.watch,s,r.spawnedAt),b=t.events?Ri(n,o):null;if(s==="wgc"&&b&&i?.client){let g=/wgc: (\d+)x(\d+)/.exec(r.watch.head());b={x:i.client.x,y:i.client.y,w:g?Number(g[1]):b.w,h:g?Number(g[2]):b.h}}let w=_d({id:r.id,target:t.target,output:a,fps:c,quality:u,pid:r.child.pid??null,spawnedAt:r.spawnedAt,startMs:h,maxDurationSec:d,window:i,backend:s,encoder:r.encoder,...r.evPaths?{events:{jsonl:r.evPaths.jsonl,raw:r.evPaths.raw,keys:r.keyMode,frame:b}}:{},...p?{replay:p}:{},...s!=="wgc"?{capture:{target:n,opts:r.captureOpts,...r.webcam?{webcam:r.webcam}:{}}}:{},...m&&r.webcamRaw?{webcam:{device:m,rawPath:r.webcamRaw,startMs:D0(r.watch,!!f).webcamStartMs,corner:t.webcam?.corner,size:t.webcam?.size,shape:t.webcam?.shape}}:{},processImage:s==="wgc"?xf(process.execPath).toLowerCase():"ffmpeg.exe",identity:pm()});return{startMs:h,frame:b,record:w}}function X0(t,e,r){t.attachChild(e.id,r);try{t.create(e)}catch(n){throw t.detachChild(e.id),new l(`Recording stopped: the session registry could not be written (${z(n)}).`)}}function kf(t){let e=t.registerTool("start_recording",{title:"Start Recording",description:"Start a background screen recording. Returns a session id; finalize it with stop_recording. Never auto-starts.",inputSchema:F0,outputSchema:B({sessionId:ae.string(),status:ae.string(),backend:ae.string(),outputPath:ae.string()}),annotations:I},async(r,n)=>{if(r.startWhen)return H0(t,e,r,n);let o=()=>{},i=new vu;try{o=Xm();let s=await G0(t,r,n),{ffmpeg:a,hideCursor:c,target:u,monitors:d,window:p,backend:f,replay:m,fps:h,quality:b,maxDurationSec:w,output:g,audio:y,webcamDevice:v,dda:x,firstPick:R,ddaUsable:T}=s;i.output=g,v&&(i.webcamRaw=zi(g,0),C0(yt(g),{recursive:!0})),m&&(zd(m),i.replay=m);let M=r.keys??np,H=r.events?m?{raw:Su(m.dir,"events.raw"),jsonl:""}:ke(g):null;H&&!m&&xi(H,r.overwrite),i.evPaths=H;let G=r.logs?new ks(r.logs):null;await G?.mark();let L=()=>{};i.logger=H?await sp(H.raw,M,{...m?{rotateSec:Ld(m.bufferSec)}:{},...r.focus?{focus:r.focus}:{},...r.elements?{elements:!0}:{},...r.hotkeys?{hotkeys:!0,onHotkey:D=>L(D)}:{}}):null;let C=`rec-${he()}-${ge(6)}`,ne={id:C,ffmpeg:a,backend:f,target:u,monitors:d,window:p,fps:h,quality:b,audio:y,hideCursor:c,dda:x,webcamDevice:v,webcamRaw:i.webcamRaw,output:g,maxDurationSec:w,replay:m},V=await Zd(R,D=>L0(ne,D),{why:D=>Fo(D.watch,3),canFallback:()=>T({encoder:"x264",gpuFrames:!1}),beforeRetry:()=>{m&&Hd(m)}}),{run:Y,failure:q,pick:Q}=V,{child:$,watch:J,spawnedAt:N,captureOpts:le,webcam:X}=Y;if(Y.settled==="exited")throw new l(`Recording failed to start (${f==="wgc"?"window capture":"ffmpeg"} exited immediately):
315
+ ${Fo(J)}`+(q?`
316
+ (Retried with libx264 after ${q})`:""));i.child=$;let{startMs:ee,frame:ie,record:_}=q0(r,s,{id:C,child:$,watch:J,spawnedAt:N,captureOpts:le,webcam:X,encoder:Q.encoder,evPaths:H,keyMode:M,webcamRaw:i.webcamRaw}),P=oe();X0(P,_,$),i.handOff();let re=i.logger;return re&&H&&B0(P,C,{logger:re,evPaths:H,keyMode:M,startMs:ee,frame:ie,replay:m,child:$}),yu(P,C,$,{backend:f,maxDurationSec:w,spawnedAt:N,watch:J}),r.perf&&W0(P,C,{output:g,startMs:ee,window:p}),G&&r.logs&&j0(P,C,{tailer:G,logs:r.logs,output:g,startMs:ee}),r.hotkeys&&(L=U0(P,C)),r.stopWhen&&z0(P,C,{target:r.target,exactTitle:r.exactTitle,text:r.stopWhen.text}),S(Td({record:_,audioDevice:y?.device,maxDurationSec:w,encoder:Q.encoder,encoderNote:Q.note,...x?{gpuFrames:Q.gpuFrames}:{},webcamDevice:v,window:p,...H?{events:{jsonl:H.jsonl,keys:M}}:{},...r.logs?{logs:{path:jt(g),missing:r.logs.some(D=>!M0(D.path))}}:{},...r.hotkeys?{hotkeys:{taken:re?cp(re):[]}}:{},...m?{replay:{...m,events:!!H}}:{}}))}catch(s){return await i.release(),E(s)}finally{o()}})}import{z as Pn}from"zod";import{existsSync as Ts}from"node:fs";function Ef(t){return{saved:t.saved,discarded:t.discarded,...t.save?{durationSec:t.save.durationSec,eventsPath:t.save.eventsPath}:{},...t.error?{error:t.error,note:"The buffer was kept; call stop_recording with save: true again, or save_replay."}:{}}}async function J0(t,e){if(t.error||!Ts(t.path))return{error:t.error??`No webcam file was written (${t.path}).`};let r=async a=>{try{let c=await W(a);return c.width&&c.height?{width:c.width,height:c.height}:null}catch{return null}},[n,o]=await Promise.all([r(e),r(t.path)]),i=t.shape==="circle",s=n&&o?bd(n,i?{width:1,height:1}:o,t.corner,t.size):null;return{path:t.path,...s?{overlay:{input:e,overlay:t.path,x:s.x,y:s.y,...i?{height:s.height,shape:"circle"}:{width:s.width}},note:"Aligned with the recording: pass `overlay` to the overlay tool (any corner or size works)."}:{}}}var Y0={sessionId:Pn.string().min(1).describe("Session id returned by start_recording."),save:Pn.boolean().optional().describe("Replay buffer: write it all to outputPath first (default: discard).")};function _f(t){t.registerTool("stop_recording",{title:"Stop Recording",description:"Stop a recording gracefully so the file is finalized; returns the path and duration.",inputSchema:Y0,outputSchema:B({sessionId:Pn.string(),status:Pn.string(),outputPath:Pn.string(),durationSec:Pn.number().nullable()}),annotations:qi},async e=>{try{let r=oe(),n=e.sessionId;if($s(n)){let f=Io(n);if(!f)throw new l(`No armed recording with id "${n}".`);f.status==="starting"&&(f=await sf(n)??f);let m={sessionId:n,outputPath:"",durationSec:null};if(lu(n))return S({...m,status:"cancelled",note:"Disarmed; nothing was recorded."});if(!f.sessionId)return S({...m,status:f.status,...f.error?{error:f.error}:{}});n=f.sessionId}let o=r.get(n);if(!o)throw new l(`No session with id "${e.sessionId}".`);if(o.status!=="recording"&&o.status!=="paused"){let f=o.replay&&Ts(o.replay.dir)?await Vi(o.replay,{save:e.save??!1,output:o.outputPath,quality:o.quality,tools:k}):void 0,m=o.durationSec??null;return m===null&&!o.segments?.parts.length&&Ts(o.outputPath)&&(m=await ue(o.outputPath,{ffprobe:k().ffprobe}).catch(()=>null),m!==null&&r.tryUpdate(o.id,{durationSec:m})),S({...f?{replay:Ef(f)}:{},sessionId:o.id,status:o.status,outputPath:o.outputPath,durationSec:m,endReason:o.endReason??null,note:o.endReason==="max_duration"?`Recording already ended at its maxDurationSec cap (${o.maxDurationSec}s).`:o.endReason==="window_closed"?"Recording already ended: the recorded window was closed.":"Session was not active; returning its recorded final state."})}let i=lm(o,process.pid,qc(o));if(i)throw new l(i);let{ffprobe:s}=k(),{record:a,graceful:c,durationSec:u,replay:d,segments:p}=await Ro(r,o,{reason:"stopped",probe:f=>ue(f,{ffprobe:s}),saveReplay:e.save});return S({sessionId:o.id,status:"stopped",outputPath:o.outputPath,durationSec:u??null,finalizedGracefully:c,...d?{replay:Ef(d)}:{},...p&&p.count>1?{segmentsJoined:p.count}:{},...p?.error?{segmentsError:p.error}:{},...a?.webcam?{webcam:await J0(a.webcam,o.outputPath)}:{},...a?.events?{eventsPath:a.events.path,events:a.events.summary??{},...a.events.error?{eventsError:a.events.error}:{}}:{},fileExists:Ts(o.outputPath),note:c?"ffmpeg quit cleanly; file finalized.":"Process terminated by pid; fragmented mp4 keeps the file playable.",record:a})}catch(r){return E(r)}})}import{z as yr}from"zod";import{existsSync as Uo,lstatSync as ph,readdirSync as dh,rmSync as H$,statSync as G$}from"node:fs";import{dirname as q$,resolve as mh}from"node:path";import{createHash as Hf}from"node:crypto";import{closeSync as E$,existsSync as In,openSync as _$,readFileSync as T$,readdirSync as R$,readSync as A$,renameSync as M$,statSync as Gf,writeFileSync as C$}from"node:fs";import{basename as qf,dirname as P$,join as Fn,resolve as Ds}from"node:path";import{closeSync as r$,existsSync as Eu,openSync as n$,readSync as o$,statSync as i$}from"node:fs";import{basename as As,isAbsolute as s$,join as _u}from"node:path";function $t(t,e,r){if(t.length<e)throw new Error(`Truncated font: ${r}.`);return t}function K0(t,e){let r=$t(t(0,12),12,"header");if(r.toString("latin1",0,4)!=="ttcf"){if(e!==0)throw new Error("Not a font collection; only face 0 exists.");return 0}let n=r.readUInt32BE(8);if(e<0||e>=n)throw new Error(`Face ${e} is out of range (collection has ${n}).`);return $t(t(12+e*4,4),4,"collection offsets").readUInt32BE(0)}var Rs=class{ranges=[];add(e,r){let n=this.ranges[this.ranges.length-1];n&&e<=n[1]+1?n[1]=Math.max(n[1],r):this.ranges.push([e,r])}};function V0(t){let e=$t(t,14,"cmap format 4").readUInt16BE(6),r=14,n=r+e+2,o=n+e,i=o+e;$t(t,i+e,"cmap format 4 segments");let s=new Rs;for(let a=0;a<e/2;a++){let c=t.readUInt16BE(r+a*2),u=t.readUInt16BE(n+a*2),d=t.readUInt16BE(o+a*2),p=t.readUInt16BE(i+a*2);if(!(u>c))for(let f=u;f<=c&&f!==65535;f++){let m;if(p===0)m=f+d&65535;else{let h=i+a*2+p+(f-u)*2;m=h+2<=t.length?t.readUInt16BE(h):0,m!==0&&(m=m+d&65535)}m!==0&&s.add(f,f)}}return s.ranges}function Q0(t,e){let r=$t(t,16,`cmap format ${e}`).readUInt32BE(12);$t(t,16+r*12,`cmap format ${e} groups`);let n=[];for(let i=0;i<r;i++){let s=t.readUInt32BE(16+i*12),a=Math.min(t.readUInt32BE(20+i*12),1114111);if(t.readUInt32BE(24+i*12)===0){if(e===13)continue;s++}s<=a&&n.push([s,a])}n.sort((i,s)=>i[0]-s[0]);let o=new Rs;for(let[i,s]of n)o.add(i,s);return o.ranges}function Z0(t,e){return t===3&&e===10?0:t===0&&(e===4||e===6)?1:t===3&&e===1?2:t===0&&e<=3?3:-1}function Tf(t,e=0){let r=K0(t,e),n=$t(t(r,12),12,"sfnt header"),o=n.toString("latin1",0,4);if(o!=="\0\0\0"&&o!=="OTTO"&&o!=="true")throw new Error("Not a TrueType/OpenType font.");let i=n.readUInt16BE(4),s=$t(t(r+12,i*16),i*16,"table directory"),a=-1;for(let f=0;f<i;f++)s.toString("latin1",f*16,f*16+4)==="cmap"&&(a=s.readUInt32BE(f*16+8));if(a<0)throw new Error("Font has no cmap table.");let u=$t(t(a,4),4,"cmap header").readUInt16BE(2),d=$t(t(a+4,u*8),u*8,"cmap records"),p=[];for(let f=0;f<u;f++){let m=Z0(d.readUInt16BE(f*8),d.readUInt16BE(f*8+2));m>=0&&p.push({rank:m,offset:a+d.readUInt32BE(f*8+4)})}p.sort((f,m)=>f.rank-m.rank);for(let{offset:f}of p){let m=t(f,8);if(m.length<8)continue;let h=m.readUInt16BE(0);if(h===4)return V0(t(f,m.readUInt16BE(2)));if(h===12||h===13)return Q0(t(f,m.readUInt32BE(4)),h)}throw new Error("Font has no Unicode cmap subtable this reader understands (formats 4, 12, 13).")}function e$(t,e){let r=0,n=t.length-1;for(;r<=n;){let o=r+n>>1,[i,s]=t[o];if(e<i)n=o-1;else if(e>s)r=o+1;else return!0}return!1}function t$(t){return!(t<32||t>=127&&t<160||t===173||t===847||t===1564||t===65279||t>=8203&&t<=8207||t>=8234&&t<=8238||t>=8288&&t<=8303||t>=65024&&t<=65039||t>=917504&&t<=921599)}function Oo(t,e){let r=new Set,n=[];for(let o of t){let i=o.codePointAt(0);r.has(i)||(r.add(i),t$(i)&&!e$(e,i)&&n.push(o))}return n}var a$={regular:"Inter-Regular.ttf",bold:"Inter-Bold.ttf"};function Ut(t="bold"){return _n("fonts",a$[t])}function ye(t){return t.replace(/\\/g,"/").replace(/:/g,"\\\\:").replace(/'/g,"\\\\\\'").replace(/([,;[\]])/g,"\\$1")}var c$={segoe:{name:"Segoe UI",regular:["segoeui.ttf"],bold:["segoeuib.ttf","segoeui.ttf"]},japanese:{name:"Yu Gothic",regular:["YuGothM.ttc","meiryo.ttc","msgothic.ttc"],bold:["YuGothB.ttc","meiryob.ttc","YuGothM.ttc","msgothic.ttc"]},chineseSimplified:{name:"Microsoft YaHei",regular:["msyh.ttc","simsun.ttc"],bold:["msyhbd.ttc","msyh.ttc","simsun.ttc"]},chineseTraditional:{name:"Microsoft JhengHei",regular:["msjh.ttc","mingliub.ttc"],bold:["msjhbd.ttc","msjh.ttc"]},korean:{name:"Malgun Gothic",regular:["malgun.ttf"],bold:["malgunbd.ttf","malgun.ttf"]},indic:{name:"Nirmala UI",regular:["Nirmala.ttc","Nirmala.ttf"],bold:["NirmalaB.ttf","Nirmala.ttc","Nirmala.ttf"]},thai:{name:"Leelawadee UI",regular:["LeelawUI.ttf","tahoma.ttf"],bold:["LeelaUIb.ttf","LeelawUI.ttf","tahomabd.ttf"]},ethiopic:{name:"Ebrima",regular:["ebrima.ttf"],bold:["ebrimabd.ttf","ebrima.ttf"]},emoji:{name:"Segoe UI Emoji",regular:["seguiemj.ttf"],bold:["seguiemj.ttf"]},symbol:{name:"Segoe UI Symbol",regular:["seguisym.ttf"],bold:["seguisym.ttf"]}},u$=["segoe","japanese","chineseSimplified","chineseTraditional","korean","indic","thai","ethiopic","emoji","symbol"];function l$(t){let e=[];return/[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9f]/u.test(t)&&e.push("japanese"),/[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]/u.test(t)&&e.push("korean"),new RegExp("\\p{Script=Han}","u").test(t)&&e.push("chineseSimplified"),[...e,...u$.filter(r=>!e.includes(r))].map(r=>c$[r])}function p$(t,e){let r=null;for(let n of e){let o=Oo(t,n.coverage);if(o.length===0)return{fontFile:n.path,missing:o};(!r||o.length<r.missing.length)&&(r={fontFile:n.path,missing:o})}return r}function Af(){return _u(process.env.WINDIR??process.env.SystemRoot??"C:\\Windows","Fonts")}var Rf=new Map;function $u(t){let e=Rf.get(t);if(e!==void 0)return e;let r,n=null;try{n=n$(t,"r");let o=n;r=Tf((s,a)=>{let c=Buffer.alloc(a);return c.subarray(0,o$(o,c,0,a,s))})}catch{r=null}finally{n!==null&&r$(n)}return Rf.set(t,r),r}function d$(t){if(Eu(t)&&i$(t).isFile())return t;if(!s$(t)&&As(t)===t){let e=_u(Af(),t);if(Eu(e))return e}throw new l(`Font file not found: ${t}`,"Pass a path to a .ttf, .otf or .ttc file, or the file name of a font in C:\\Windows\\Fonts.")}function ku(t){let e=t.replace(/\s+/g," ").trim();return`"${e.length>40?`${e.slice(0,39)}\u2026`:e}"`}function kt(t,e={}){if(e.fontFile){let c=d$(e.fontFile),u=$u(c);if(!u)return{fontFile:c,missing:[],fallback:!1,warning:`Could not read the character map of ${As(c)}; glyph coverage of ${ku(t)} was not checked.`};let d=Oo(t,u);return d.length===0?{fontFile:c,missing:d,fallback:!1}:{fontFile:c,missing:d,fallback:!1,warning:`${As(c)} has no glyph for ${d.join(" ")} in ${ku(t)}; they render as empty boxes.`}}let r=e.weight??"bold",n=Ut(r),o=$u(n);if(o&&Oo(t,o).length===0)return{fontFile:n,missing:[],fallback:!1};let i=e.fontsDir??Af(),s=o?[{path:n,coverage:o}]:[];for(let c of l$(t))for(let u of c[r]){let d=_u(i,u),p=Eu(d)?$u(d):null;if(p){if(Oo(t,p).length===0)return{fontFile:d,missing:[],fallback:!0};s.push({path:d,coverage:p});break}}let a=p$(t,s)??{fontFile:n,missing:[]};return a.missing.length===0?{...a,fallback:a.fontFile!==n}:{...a,fallback:a.fontFile!==n,warning:`No available font draws ${a.missing.join(" ")} in ${ku(t)}; they render as empty boxes (drawn with ${As(a.fontFile)}). Pass fontFile with a font that covers them.`}}import{mkdtempSync as m$,rmSync as f$,writeFileSync as h$}from"node:fs";import{join as Tu}from"node:path";import{tmpdir as g$}from"node:os";var No=12,Mf=48,Do=320;function Ms(t,e){if(!(t>0))throw new l("Could not read the video's duration.");return Array.from({length:e},(r,n)=>Math.round((n+.5)*t/e*1e3)/1e3)}function Ne(t){let e=Math.round(Math.max(0,t)*10),r=Math.floor(e/36e3),n=Math.floor(e%36e3/600),o=e%600/10;return r>0?`${r}:${String(n).padStart(2,"0")}:${String(Math.floor(o)).padStart(2,"0")}`:`${n}:${o.toFixed(1).padStart(4,"0")}`}function b$(t,e){let r=t<=4?t:Math.ceil(Math.sqrt(t)),n=Math.max(1,Math.min(t,e??r));return{columns:n,rows:Math.ceil(t/n)}}function w$(t,e,r,n,o,i){if(!Number.isInteger(n)||n<64)throw new l("tileWidth must be an integer of at least 64.");let s=Math.max(12,Math.round(n/16)),a=`drawtext=fontfile=${ye(o)}:textfile=${ye(i)}:expansion=none:fontcolor=white:fontsize=${s}:x=6:y=h-text_h-6:box=1:boxcolor=black@0.6:boxborderw=4`;return["-y","-v","error","-ss",String(e),"-i",t,"-frames:v","1","-vf",`scale=${n}:-2,${a}`,...Te(r)]}function y$(t,e,r){return["-y","-v","error","-framerate","1","-i",t,"-vf",`tile=${e.columns}x${e.rows}:padding=4:margin=4:color=black`,"-frames:v","1",...Te(r)]}function Cf(t,e,r,n){if(!(e>0))throw new l("Could not read the video's duration.");let o=30,i=Math.max(1e-4,o/e);return["-y","-v","error","-i",t,"-vf",`fps=${i.toFixed(4)},thumbnail=${o},scale='min(${n},iw)':-2`,"-frames:v","1",...Te(r)]}async function Cs(t,e,r,n,o){let i=b$(e.length,n.columns),s=m$(Tu(g$(),"screencast-sheet-"));try{let a=Ut("bold");await qe(e,async(c,u)=>{let d=Tu(s,`label_${u}.txt`);h$(d,Ne(c));let p=Tu(s,`tile_${String(u).padStart(3,"0")}.png`);await te(w$(t,c,p,n.tileWidth,a,d),6e4,{signal:o})}),await te(y$(mn(s,"tile_%03d.png"),i,r),6e4,{signal:o})}finally{f$(s,{recursive:!0,force:!0})}return i}import{existsSync as Ps}from"node:fs";var Pf=t=>Math.round(t*1e3)/1e3,x$={input_not_seen:"input went to an elevated window or the lock screen, or the hook was removed",helper_stalled:"the event logger paused",helper_stopped:"the event logger stopped"};function Ru(t){return t.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function Au(t){let e=Ru(t.role),r=t.app?` in ${t.app}`:"";return t.name?`the "${t.name}" ${e}${r}`:`${/^[aeiou]/.test(e)?"an":"a"} ${e}${r}`}function If(t,e,r){let n=e?"double-click":"click",o=t&&t!=="left"?`${t.charAt(0).toUpperCase()}${t.slice(1)} ${n}`:`${n.charAt(0).toUpperCase()}${n.slice(1)}`;return r.element?.name?`${o} ${Au(r.element)}`:r.inFrame?`${o} at (${r.x}, ${r.y})`:`${o} outside the recorded area`}function Mu(t){let e=[],r=[...t].sort((s,a)=>s.t-a.t),n=null,o=null,i=(s,a)=>{let c=s==="vertical"?a>=0?"up":"down":a>=0?"right":"left",u=Math.abs(a);return`Scroll ${c} ${u} notch${u===1?"":"es"}`};for(let s of r)if(!(s.type==="move"||s.type==="up")){if(s.type!=="wheel"&&(o=null),s.type==="down"){let a=n;if(a&&a.e.button===s.button&&s.t-a.e.t<=.5&&Math.abs(s.x-a.e.x)<=6&&Math.abs(s.y-a.e.y)<=6&&a.step.action==="click"&&e.at(-1)===a.step){a.step.action="double_click",a.step.text=If(s.button,!0,a.e),n=null;continue}let c={t:s.t,action:"click",text:If(s.button,!1,s),x:s.x,y:s.y,button:s.button??"left",inFrame:s.inFrame,...s.element?{element:s.element}:{}};e.push(c),n={e:s,step:c};continue}if(n=null,s.type==="wheel"){let a=s.axis??"vertical",c=s.delta??0;if(o&&o.axis===a&&s.t-o.last<=1&&Math.sign(c)===Math.sign(o.notches)){o.notches+=c,o.last=s.t,o.step.text=i(a,o.notches);continue}let u={t:s.t,action:"scroll",text:i(a,c),x:s.x,y:s.y,inFrame:s.inFrame};e.push(u),o={step:u,axis:a,notches:c,last:s.t}}else if(s.type==="key")e.push({t:s.t,action:"shortcut",text:`Press ${s.keys??"a shortcut"}`,...s.keys?{keys:s.keys}:{}});else if(s.type==="typing"){let a=s.durationSec??0;e.push({t:s.t,action:"typing",text:`Type${a>0?` for ${Pf(a)} s`:""} (keys are not logged)`,durationSec:a})}else if(s.type==="focus"){let a=s.app??"another app";e.push({t:s.t,action:"switch",text:s.title?`Switch to "${s.title}" (${a})`:`Switch to ${a}`})}else if(s.type==="gap"){let a=x$[s.reason??"input_not_seen"],c=Pf(s.durationSec??0);e.push({t:s.t,action:"gap",text:`Input may be missing for ${c} s (${a})`,durationSec:c})}}return e}function Cu(t){return Mu(t).map(({button:e,inFrame:r,keys:n,durationSec:o,element:i,...s})=>s)}var Pu=30,Is=600,Iu=1,Fs=100,Fu=20,De=su(["\\b(?:sk|pk|rk)-[a-z0-9_-]{8,}","\\bgh[pousr]_[a-z0-9]{10,}","\\bgithub_pat_[a-z0-9_]{10,}","\\bxox[abprs]-[a-z0-9-]{8,}","\\bAKIA[0-9A-Z]{12,}","\\bAIza[0-9a-z_-]{20,}","\\beyJ[a-z0-9_-]{8,}\\.[a-z0-9_-]{8,}","(?:api.?key|secret|token|passw(?:or)?d|bearer|authorization)\\s*[:=]?\\s*\\S+"].join("|")),Os=su("error|exception|fail(?:ed|ure)?|fatal|crash|denied|refused|not found|cannot|can't|unable|invalid|timed? ?out|traceback|panic|unhandled|warning"),zt={markdown:"report.md",json:"report.json",clip:"clip.mp4",contactSheet:"contact-sheet.png",gif:t=>`repro.${t}`},Lo=t=>Math.round(t*1e3)/1e3;function Of(t,e={}){if(!(t>0))throw new l("Could not read the recording's duration.");let r=Math.min(e.end??t,t),n=e.clipSec??Pu,o=e.start??Math.max(0,r-n);if(o>=t)throw new l(`start ${o}s is past the end of the ${Lo(t)}s recording.`);if(!(r>o))throw new l("end must be after start.");if(r-o>Is)throw new l(`The clip would be ${Lo(r-o)}s; at most ${Is}s. Narrow start/end.`);return{start:Lo(o),end:Lo(r)}}function S$(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),n=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);return r<=0||n<=0?!1:r*n>=.5*Math.min(t.width*t.height,e.width*e.height)}function Nf(t){let e=[];for(let r of[...t].sort((n,o)=>n.start-o.start)){let n=e.find(s=>r.start<=s.end&&S$(s,r));if(!n){e.push({...r});continue}let o=Math.min(n.x,r.x),i=Math.min(n.y,r.y);n.width=Math.max(n.x+n.width,r.x+r.width)-o,n.height=Math.max(n.y+n.height,r.y+r.height)-i,n.x=o,n.y=i,n.start=Math.min(n.start,r.start),n.end=Math.max(n.end,r.end)}return e}var v$="[REDACTED]";function Le(t,e){if(t.length===0)return[];let r=Tn(t,e);return t.map((n,o)=>{let i=[...r[o]??[]].sort((c,u)=>c[0]-u[0]),s="",a=0;for(let[c,u]of i)u<=a||(s+=n.slice(a,Math.max(a,c))+(c>=a?v$:""),a=u);return s+n.slice(a)})}function Df(t,e,r){let n=new Map;for(let a of t){let c=new Set(St(a.lines,e,!0).map(u=>u.line));for(let u of c){let d=Bt(u),p=n.get(d);p?p.lastSeen=a.t:n.set(d,{text:u,firstSeen:a.t,lastSeen:a.t})}}let o=t.at(-1)?.t,i=[...n.values()].sort((a,c)=>+(c.lastSeen===o)-+(a.lastSeen===o)||a.firstSeen-c.firstSeen).slice(0,Fu);if(!r)return i;let s=Le(i.map(a=>a.text),r);return i.map((a,c)=>({...a,text:s[c]??a.text}))}var $$=t=>`\`${t.replace(/`/g,"'").replace(/\s+/g," ").trim()}\``,Ff=t=>t.replace(/\|/g,"\\|").replace(/\s*\n\s*/g," ");function Lf(t){let e=[`# ${t.title.replace(/\s*\n\s*/g," ")}`,""],r=`${Ne(t.clip.start)}-${Ne(t.clip.end)}`;if(e.push(`Recorded repro: ${t.clip.width}x${t.clip.height}, clip ${r} of a ${Ne(t.clip.recordingDurationSec)} recording.`,""),(t.actual||t.expected)&&(t.actual&&e.push("**Actual:** "+t.actual.trim(),""),t.expected&&e.push("**Expected:** "+t.expected.trim(),"")),e.push("## Steps to reproduce",""),t.steps.length===0?e.push(`_${t.stepsNote??"No input events in the recording."} Add the steps by hand._`,""):(e.push("From the recording's input event log; times are on the recording's clock, positions in video pixels.",""),t.steps.forEach((i,s)=>e.push(`${s+1}. \`${Ne(i.t)}\` ${i.text}`)),t.stepsOmitted&&e.push("",`_${t.stepsOmitted} more steps not shown (see report.json)._`),e.push("")),e.push("## Error text on screen",""),t.ocr!=="read")e.push("_Not read: Windows OCR is unavailable here._","");else if(t.errors.length===0)e.push("_None found by OCR in the clip._","");else{e.push("Read by OCR (best-effort, may contain misreads); times from the clip start.","");for(let i of t.errors){let s=i.firstSeen===i.lastSeen?Ne(i.firstSeen):`${Ne(i.firstSeen)}-${Ne(i.lastSeen)}`;e.push(`- \`${s}\` ${$$(i.text)}`)}e.push("")}if(t.perf&&t.perf.length>0&&e.push("## Resource usage","",...t.perf.map(i=>`- ${i}`),""),t.logs)if(e.push("## App logs",""),t.logs.length===0)e.push("_No log lines during the clip._","");else{e.push("Lines the app logged during the clip (and the 5 s before it); times from the clip start.","","```text");for(let i of t.logs)e.push(`${i.t<0?"-":""}${Ne(Math.abs(i.t))} [${i.source}] ${i.line.replace(/\x60{3}/g,"'''")}`);e.push("```","")}if(e.push("## Recording",""),t.files.gif&&e.push("<!-- GitHub does not upload local files from --body-file: drag the GIF and clip into the issue, or replace these links with the uploaded URLs. -->",`![Repro](${t.files.gif})`,""),e.push(`- Clip: [${t.files.clip}](${t.files.clip}) (${Lo(t.clip.end-t.clip.start)} s)`),t.files.gif&&t.gif){let i=(t.gif.sizeBytes/1e6).toFixed(1);e.push(`- ${t.gif.format==="gif"?"GIF":"WebP"}: [${t.files.gif}](${t.files.gif}) (${i} MB${t.gif.withinBudget?"":", over the size budget"})`)}t.files.contactSheet&&e.push(`- Contact sheet: [${t.files.contactSheet}](${t.files.contactSheet})`),e.push(""),e.push("## Environment","","| | |","|---|---|");for(let[i,s]of t.environment)e.push(`| ${Ff(i)} | ${Ff(s)} |`);e.push("");let n=t.redaction,o=n.found+n.manual;return e.push("<sub>",n.scanned?`Secret scan: OCR every ${n.everySec} s over ${n.framesScanned} frames; ${o} region${o===1?"":"s"} boxed out of the media. OCR is best-effort: review the clip before posting.`:`Not scanned for secrets${n.manual>0?` (${n.manual} region${n.manual===1?"":"s"} boxed out by hand)`:""}: review the clip before posting.`,`Generated by screencast-mcp bug_report, ${t.createdAt}.`,"</sub>",""),e.join(`
317
+ `)}async function Ns(t){if(t.sessionId!==void 0){let n=oe().get(t.sessionId);if(!n)throw new l(`No session with id "${t.sessionId}".`);if(n.status==="recording"||n.status==="paused")throw new l("The recording is still running; stop_recording it first.");if(await Zt(n.id),!Ps(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path;return{path:n.outputPath,eventsPath:o&&Ps(o)?o:null,record:n}}let e=t.input;if(!Ps(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=ke(e);return{path:e,eventsPath:Ps(r)?r:null}}var k$=40;function Bf(t,e,r){let n=t.filter(i=>i.t>=e.start-5&&i.t<=e.end).slice(-k$),o=r?Le(n.map(i=>i.line),r):n.map(i=>i.line);return n.map((i,s)=>({...i,t:Math.round((i.t-e.start)*1e3)/1e3,line:o[s]??i.line}))}function Wf(t,e,r){let n=t.filter(s=>s.t>=e.start&&s.t<=e.end).map(s=>({...s,t:s.t-e.start}));if(n.length===0)return[];let o=Mn(n),i=r?.exe??"the app";return[...o.peakCpu!==void 0?[`${i} CPU peaked at ${o.peakCpu}% of the machine`]:[],...o.peakRssMB!==void 0?[`${i} memory peaked at ${o.peakRssMB} MB (${o.rssGrowthMB>=0?"+":""}${o.rssGrowthMB} MB over the clip)`]:[],`Machine CPU peaked at ${o.peakSysCpu}%`,...o.busy.map(s=>`CPU pinned (>= 90%) from ${Ne(s.start)} to ${Ne(s.end)}`)]}var Ou=1,Nu=.03,Du=120,Xf=600,I$=10,Ls=10,Jf=50,jf=200,F$=5,wr=t=>Math.round(t*1e3)/1e3;function Bo(t){return`${t}.index.json`}function Lu(t){return`${t.replace(/\.[^./\\]+$/,"")}.index.json`}function Wo(t,e){let r=n=>process.platform==="win32"?Ds(n).toLowerCase():Ds(n);return r(t)===r(e)}function Bs(t,e,r){return typeof t.video=="string"&&Wo(t.video,e)?!0:r!==void 0&&!!t.fingerprint&&Gs(t.fingerprint,r)}function Ws(t,e){let r=Hf("sha1").update(Ds(t).toLowerCase()).digest("hex").slice(0,12),n=qf(t).replace(/\.[^.]+$/,"");return Fn(e,"indexes",`${n}-${r}.index.json`)}function Yf(t,e){let r=Bo(t);try{return rr(r),r}catch{return Ws(t,e)}}function js(t,e,r){for(let o of[Bo(t),Ws(t,e)])if(In(o))return o;let n=Lu(t);if(n!==Bo(t)&&In(n)){let o=jo(n);if(o&&Bs(o,t,r))return n}return null}function Kf(t,e){return t!==null&&Gs(t.fingerprint,e.fingerprint)&&t.sceneThreshold===e.sceneThreshold&&t.maxFrames===e.maxFrames&&(t.ocr||!e.ocrAvailable)}function Vf(t,e=De){return t.map(r=>r.ocr.length>0?{...r,ocr:Le(r.ocr,e)}:r)}var O$=/\.(mp4|mkv|mov|webm|avi|m4v|wmv|flv|gif|ts|mpg|mpeg)$/i,Uf=t=>t.replace(/\.[^.]+$/,"").toLowerCase();function Us(t,e){let r=new Set(e.map(s=>s.toLowerCase())),n=qf(t);if(r.has(`${n}.srt`.toLowerCase()))return{path:`${t}.srt`,ambiguous:!1};let o=`${n.replace(/\.[^.]+$/,"")}.srt`;return r.has(o.toLowerCase())?e.some(s=>s.toLowerCase()!==n.toLowerCase()&&O$.test(s)&&Uf(s)===Uf(n))?{path:null,ambiguous:!0}:{path:Fn(P$(t),o),ambiguous:!1}:{path:null,ambiguous:!1}}function Qf(t,e,r,n=I$){let o=bn(t.filter(i=>i.timeSec<e),r).map(wr);for(;o.length<r;){let i=-1,s=0;for(let a=0;a<o.length;a++){let c=(o[a+1]??e)-o[a];c>s&&(s=c,i=a)}if(i===-1||s<=n)break;o.splice(i+1,0,wr(o[i]+s/2))}return[...new Set(o)].sort((i,s)=>i-s)}function Zf(t,e){return t.map((r,n)=>({start:r,end:wr(t[n+1]??e)}))}function zs(t){return wr(t.start+Math.min(.25,(t.end-t.start)/2))}function eh(t){let e=[];for(let r of t){let n=e.at(-1);n&&n.ocr.join(`
318
318
  `)===r.ocr.join(`
319
- `)&&!r.events&&!r.markers&&!r.transcript?n.end=r.end:e.push({...r,ocr:[...r.ocr]})}return e}function Zf(t){let e=[];for(let r of t){let n=`at ${Math.round(r.x)},${Math.round(r.y)}`,o=null;if(r.type==="down"){let i=r.element;o=`click ${r.button??"left"} ${n}`+(i?` ${Tu(i.role)}${i.name?` ${i.name}`:""}${i.app?` ${i.app}`:""}`:"")}else r.type==="key"?o=`shortcut ${r.keys??"key"}`:r.type==="typing"?o=`typing ${fr(r.durationSec??0)} s`:r.type==="wheel"?o=`scroll ${(r.delta??0)>0?"up":"down"} ${n}`:r.type==="gap"?o=`event gap (${r.reason??"unknown"})`:r.type==="focus"&&(o=`switch to ${r.app??"app"}${r.title?` ${r.title}`:""}`);o&&e.push({t:fr(r.t),text:o})}return e}function eh(t){return t.map(e=>({t:fr(e.t),text:e.label}))}function th(t){return t.map(e=>({t:fr(e.start),text:e.text.replace(/\s+/g," ").trim()})).filter(e=>e.text)}function zr(t,e,r){let n=t.map(o=>{let{[r]:i,...s}=o;return s});if(n.length===0)return n;for(let o of[...e].sort((i,s)=>i.t-s.t)){let i=n.findIndex(a=>o.t>=a.start&&o.t<a.end);i===-1&&(i=o.t<n[0].start?0:n.length-1);let s=n[i];(s[r]??=[]).push(o)}return n}function Hs(t){let e=zf(t),r=Uf("sha1"),n=64*1024,o=h$(t,"r");try{let i=Buffer.alloc(n);for(let s of e.size>n?[0,e.size-n]:[0]){let a=w$(o,i,0,n,s);r.update(i.subarray(0,a))}}finally{f$(o)}return{size:e.size,mtimeMs:Math.round(e.mtimeMs),sample:r.digest("hex")}}function Gs(t,e){return t.size===e.size&&t.mtimeMs===e.mtimeMs&&t.sample===e.sample}function E$(t){try{let e=JSON.parse(t);return e?.version!==Fu||!Array.isArray(e.segments)||!e.fingerprint?null:e}catch{return null}}function Wo(t){try{return E$(g$(t,"utf8"))}catch{return null}}var Ur=new Map,_$=64;function Lu(t){let e;try{e=zf(t)}catch{return Ur.delete(t),null}let r=Ur.get(t);if(r&&r.size===e.size&&r.mtimeMs===e.mtimeMs)return r.index;let n=Wo(t);return n?(Ur.size>=_$&&Ur.delete(Ur.keys().next().value),Ur.set(t,{size:e.size,mtimeMs:e.mtimeMs,index:n}),n):(Ur.delete(t),null)}function rh(t,e){let r=`${t}.${process.pid}.tmp`;x$(r,JSON.stringify(e)),y$(r,t)}function T$(t){let e=t.replace(/\s+/g," ").trim();return e.length>Bf?`${e.slice(0,Bf-1)}\u2026`:e}function A$(t){let e=[];return t.segments.forEach((r,n)=>{for(let o of r.ocr)e.push({seg:n,source:"screen",t:r.start,text:o});for(let[o,i]of[["event",r.events],["marker",r.markers],["transcript",r.transcript],["log",r.logs]])for(let s of i??[])e.push({seg:n,source:o,t:s.t,text:s.text})}),e}function nh(t,e){if(t.trim().length===0)throw new l("query must not be empty.");if(t.length>jr)throw new l(`The query is ${t.length} characters; at most ${jr} are allowed.`);if(!e&&!/[\p{L}\p{N}]/u.test(Dt(t)))throw new l("query needs at least one letter or digit.","For punctuation, use regex: true.");e&&$n([""],t)}var jf=new WeakMap;function R$(t,e){let r=jf.get(t);r||jf.set(t,r=new Map);let n=r.get(e);if(n)return n;let o=A$(t),i=e?Oe(o.map(c=>c.text),e):o.map(c=>c.text),s=o.map((c,u)=>({...c,text:i[u]??""})),a={items:s,norm:s.map(c=>Dt(c.text))};return r.set(e,a),a}function Bu(t,e,r={}){if(nh(e,r.regex===!0),r.video!==void 0&&!Bs(t,r.video,r.fingerprint))throw new l(`The index found is for ${t.video}, not ${r.video}.`,"Run index_recording on this recording.");let n=r.secretPattern===void 0?Ge:r.secretPattern,{items:o,norm:i}=R$(t,n??""),s=new Map,a=(p,f)=>{let m=s.get(p.seg)??{score:0,matches:[]};m.score+=f,m.matches.push(p),s.set(p.seg,m)};if(r.regex){let p=$n(o.map(f=>f.text),e);o.forEach((f,m)=>{(p[m]??[]).length>0&&a(f,2)})}else{let p=Dt(e.trim()),f=p.split("_").filter(Boolean);if(o.forEach((m,h)=>{i[h].includes(p)&&a(m,2)}),f.length>1){let m=new Map;o.forEach((h,b)=>{let w=m.get(h.seg);w?w.push(b):m.set(h.seg,[b])});for(let[h,b]of m)if(!s.has(h)&&f.every(w=>b.some(g=>i[g].includes(w)))){for(let w of b)f.some(g=>i[w].includes(g))&&a(o[w],0);s.get(h).score=1}}}return{hits:[...s.entries()].map(([p,f])=>({seg:p,...f})).sort((p,f)=>f.score-p.score||t.segments[p.seg].start-t.segments[f.seg].start).slice(0,r.limit??Ls).map(p=>{let f=t.segments[p.seg],m=p.matches.slice(0,$$).map(h=>({source:h.source,t:h.t,text:T$(h.text)}));return{start:f.start,end:f.end,t:Math.min(...p.matches.map(h=>h.t)),score:p.score,matches:m}}),total:s.size}}var M$=20;function C$(t){return[Cn(t,"recordings"),Cn(t,"edits"),Cn(t,"edits","indexes")]}function oh(t){let e=[];for(let r of C$(t)){let n;try{n=b$(r)}catch{continue}for(let o of n)o.endsWith(".index.json")&&e.push(Cn(r,o))}return e}function ih(t,e,r={}){nh(e,r.regex===!0);let n=new Map;for(let c of t){let u=Ds(c.index.video).toLowerCase(),d=n.get(u);(!d||c.index.createdAt>d.index.createdAt)&&n.set(u,c)}let o=r.limit??Ls,i=[],s=[],a=0;for(let c of n.values()){let u=Bu(c.index,e,{regex:r.regex,limit:o});if(u.total!==0){a+=u.total,i.push({video:c.index.video,indexPath:c.indexPath,total:u.total,best:u.hits[0].score});for(let d of u.hits)s.push({video:c.index.video,...d})}}return i.sort((c,u)=>u.best-c.best||u.total-c.total),s.sort((c,u)=>u.score-c.score),{hits:s.slice(0,o),total:a,recordings:i.slice(0,M$),searched:n.size}}async function qs(t){if(t.input===void 0==(t.sessionId===void 0))throw new l("Provide exactly one of: input (a recording path) or sessionId.");if(t.sessionId!==void 0){let n=re().get(t.sessionId);if(!n)throw new l(`No session with id "${t.sessionId}".`);if(n.status==="recording"||n.status==="paused")throw new l("The recording is still running; stop_recording it first.");if(await Kt(n.id),!Mn(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path,i=n.markers?.length?n.markers:Le(n.outputPath);return{path:n.outputPath,eventsPath:o&&Mn(o)?o:null,markers:i}}let e=t.input;if(!Mn(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=$e(e);return{path:e,eventsPath:Mn(r)?r:null,markers:Le(e)}}import{basename as sh}from"node:path";function ah(t,e,r){let n=$e(t),o=Us(t,e),i=[n.jsonl,n.raw,`${n.raw}.stop`,Lr(t),Lo(t),Ws(t,r),pr(t),Lt(t),xt(t),Vi(t),...o.path&&!o.ambiguous?[o.path]:[]];return{files:[...new Set(i)].filter(s=>sh(s)!==sh(t)),dirs:[bt(t)]}}var P$=/\.(mp4|m4v|mkv|mov|webm|avi|gif|webp)$/i;function ch(t){if(Qt(t,"Recording"),!P$.test(t))throw new l(`${t} is not a video or GIF, so it is not deleted.`,"delete_recording only removes recordings and their sidecars.");if(![Me(),...Mr()??[]].some(r=>ht(t,r)&&!ht(r,t)))throw new l(`Recording ${t} is outside SCREENCAST_HOME and the allowed directories, so it is not deleted. Add its folder to SCREENCAST_ALLOWED_DIRS or the client's workspace roots, or delete it yourself.`)}var N$={sessionId:hr.string().min(1).optional().describe("Session id of the recording to delete."),input:hr.string().min(1).optional().describe("Or the recording's path.")};function dh(t){try{let e=F$(t);return e.isDirectory()?lh(t).reduce((r,n)=>r+dh(ph(t,n)),0):e.size}catch{return 0}}async function D$(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form){if(zm())throw new l(`Not deleted: ${Co} requires the user to confirm, but this client does not support MCP elicitation.`);return!1}let n;try{({action:n}=await t.server.elicitInput({message:e,requestedSchema:{type:"object",properties:{}}},{signal:r,timeout:ru}))}catch(o){throw new l(`Not deleted: the confirmation request failed (${U(o)}).`)}if(n!=="accept")throw new l(`Not deleted: ${n==="decline"?"declined":"cancelled"} by the user.`);return!0}function mh(t){t.registerTool("delete_recording",{title:"Delete Recording",description:"Delete a finished recording with its sidecars (event log, webcam, transcript, index, markers, pause parts) and registry entries; reports bytes freed. Asks the user first when the client supports it. Edits made from it are kept.",inputSchema:N$,outputSchema:N({outputPath:hr.string(),deleted:hr.array(hr.string()),bytesFreed:hr.number(),sessionsRemoved:hr.array(hr.string())}),annotations:Td},async(e,r)=>{try{if(!!e.sessionId==!!e.input)throw new l("Give exactly one of sessionId or input.");let n=re(),o;if(e.sessionId){let g=n.get(e.sessionId);if(!g)throw new l(`No session with id "${e.sessionId}".`);o=g.outputPath}else o=ph(e.input);ch(o);let i=n.list().filter(g=>Bo(g.outputPath,o)),s=i.find(g=>xn(g.status));if(s)throw new l(`Recording ${s.id} is still ${s.status}; stop it first.`);let a=[];try{a=lh(O$(o))}catch{}if(jo(o)&&!uh(o).isFile())throw new l(`${o} is not a file, so it is not deleted.`,"delete_recording only removes a recording and its sidecars.");let c=ah(o,a,we("edits")),u=[o,...c.files].filter(g=>jo(g)&&uh(g).isFile()),d=c.dirs.filter(g=>jo(g)),p=[...u,...d];if(p.length===0&&i.length===0)throw new l(`Nothing to delete: ${o} does not exist.`);let f=await D$(t,`Delete ${o} and ${p.length-(jo(o)?1:0)} sidecar file(s)? This cannot be undone.`,r.signal);if(!f&&i.length===0&&!ht(o,Me()))throw new l(`Not deleted: ${o} is not a recording this server made, and this client cannot ask you to confirm.`,"Pass the recording's sessionId, use a client that supports MCP elicitation, or delete the file yourself.");let m=0,h=[],b=[];for(let g of p){let y=dh(g);try{I$(g,{recursive:d.includes(g),force:!0}),h.push(g),m+=y}catch($){b.push(`${g}: ${U($)}`)}}let w=jo(o)?[]:i.map(g=>g.id);return w.length>0&&n.remove(w),v({outputPath:o,deleted:h,bytesFreed:m,sessionsRemoved:w,confirmedByUser:f,...b.length>0?{failed:b,note:"Some files could not be deleted (in use?); the registry entry was kept if the recording remains."}:{}})}catch(n){return E(n)}})}import{z as gr}from"zod";import{existsSync as L$}from"node:fs";function F(t,e="Input file"){if(!L$(t))throw new l(`${e} not found: ${t}`)}function B(t,e,r,n={}){return n.anyContainer||Nr(t),er(t,we(n.dir??"edits"),`${e}-${ge()}-${be()}${r}`,n.overwrite)}var B$={sessionId:gr.string().min(1).describe("Session id of a replay buffer."),lastSec:gr.number().positive().max(yn).optional().describe("Seconds back from now (default and max: the buffer length)."),output:gr.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:gr.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),reencode:gr.boolean().optional().describe("Frame-exact re-encode. Default: instant stream copy that may hide up to 2 s of earlier frames.")};function fh(t){t.registerTool("save_replay",{title:"Save Replay",description:"Save the last N seconds of a replay buffer (start_recording replayBufferSec) to an mp4; the buffer keeps running.",inputSchema:B$,outputSchema:N({sessionId:gr.string(),outputPath:gr.string(),durationSec:gr.number()}),annotations:I},async(e,r)=>{try{let n=re().get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(!n.replay)throw new l(`Session "${e.sessionId}" is not a replay buffer.`,"Start one with start_recording { replayBufferSec: 60 }; for an ordinary recording use stop_recording and trim.");let{ffmpeg:o,ffprobe:i}=k(),s=n.replay,a=Math.min(e.lastSec??s.bufferSec,s.bufferSec),c=B(e.output,"replay",".mp4",{overwrite:e.overwrite,dir:"recordings",anyContainer:!0});s.events&&yi($e(c),e.overwrite);let u=Date.now(),d=await Bc(s,{ffmpeg:o,ffprobe:i,lastSec:a,output:c,reencode:e.reencode,quality:n.quality,live:n.status==="recording",signal:r.signal}),p=Date.now()-u;or("info",`Saved ${d.durationSec}s of replay ${n.id} to ${c}.`,{sessionId:n.id,outputPath:c,durationSec:d.durationSec});let f=d.durationSec+.25<a;return v({sessionId:n.id,...d,requestedSec:e.lastSec??null,bufferSec:s.bufferSec,bufferRunning:n.status==="recording",bufferDiskBytes:zd(s),elapsedMs:p,note:(e.lastSec!==void 0&&e.lastSec>s.bufferSec?`Capped at the buffer length (${s.bufferSec}s). `:"")+(f?"The buffer held less footage than requested (it started recently). ":"")+(d.includesLive?"":"The clip ends at the last completed segment, up to 2 s before now. ")+(n.status==="recording"?"The buffer keeps running; stop_recording discards it unless save: true.":"This buffer is no longer recording; stop_recording discards it.")})}catch(n){return E(n)}})}import{z as Xs}from"zod";var hh=t=>Math.round(t*1e3)/1e3;function gh(t){t.registerTool("pause_recording",{title:"Pause Recording",description:"Pause a recording; until resume_recording nothing is captured, and the gap is left out of the file, events, and markers.",inputSchema:{sessionId:Xs.string().min(1).describe("From start_recording.")},outputSchema:N({sessionId:Xs.string(),status:Xs.string(),recordedSec:Xs.number()}),annotations:Gi},async e=>{try{let r=re(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(ns(r,n.id,"pause"),n.status==="paused")return v({sessionId:n.id,status:"paused",recordedSec:hh(rt(n.segments?.parts??[])),note:"Already paused."});let{ffprobe:o}=k(),i=await xm(r,n,{probe:s=>se(s,{ffprobe:o})});return v({sessionId:n.id,status:"paused",recordedSec:hh(i.recordedSec),segments:i.record?.segments?.parts.length??0,note:"Nothing is captured until resume_recording; stop_recording joins what was recorded."})}catch(r){return E(r)}})}import{z as Js}from"zod";var bh=t=>Math.round(t*1e3)/1e3;function wh(t){t.registerTool("resume_recording",{title:"Resume Recording",description:"Resume a paused recording (same target and settings).",inputSchema:{sessionId:Js.string().min(1).describe("From start_recording.")},outputSchema:N({sessionId:Js.string(),status:Js.string(),recordedSec:Js.number()}),annotations:I},async e=>{try{let r=re(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(ns(r,n.id,"resume"),n.status==="recording")return v({sessionId:n.id,status:"recording",recordedSec:bh(rt(n.segments?.parts??[])),note:"Already recording."});let{ffmpeg:o}=k(),i=await hf(r,n,o);return or("notice",`Recording ${n.id} resumed.`,{sessionId:n.id}),v({sessionId:n.id,status:"recording",recordedSec:bh(i.recordedSec),pid:i.record.pid,...i.capSec>0?{remainingSec:i.capSec}:{}})}catch(r){return E(r)}})}import{z as yh}from"zod";function xh(t){t.registerTool("list_video_devices",{title:"List Video Devices",description:"List DirectShow cameras for start_recording's webcam.device.",inputSchema:{},outputSchema:N({devices:yh.array(yh.string())}),annotations:he},async()=>{try{k();let e=await tu(!0);return v({devices:e,note:e.length?`start_recording { webcam: { device: "${e[0]}" } } records it.`:"No camera found."})}catch(e){return E(e)}})}import{z as Pn}from"zod";function Sh(t){t.registerTool("list_sessions",{title:"List Sessions",description:"List all recording sessions (active and finished) with their status, target, output path, and whether the process is still alive.",inputSchema:{},outputSchema:N({count:Pn.number().int(),sessions:Pn.array(N({id:Pn.string(),status:Pn.string(),outputPath:Pn.string(),alive:Pn.boolean()}))}),annotations:he},async()=>{try{let e=re().list().map(n=>({...n,alive:n.status==="recording"&&ze(n.pid)})),r=rf();return v({count:e.length,sessions:e,...r.length?{armed:r}:{}})}catch(e){return E(e)}})}import{z as In}from"zod";import{existsSync as W$}from"node:fs";var j$={sessionId:In.string().min(1).describe("Session id returned by start_recording.")};function vh(t){t.registerTool("get_session",{title:"Get Session",description:"Inspect a single recording session by id, including live status and whether its output file exists on disk.",inputSchema:j$,outputSchema:N({id:In.string(),status:In.string(),outputPath:In.string(),alive:In.boolean(),fileExists:In.boolean()}),annotations:he},async e=>{try{if($s(e.sessionId)){let n=Po(e.sessionId);if(!n)throw new l(`No armed recording with id "${e.sessionId}".`);return v({...n,outputPath:"",alive:!1,fileExists:!1,...n.sessionId?{note:`It started recording ${n.sessionId}; get_session that id for it.`}:{}})}let r=re().get(e.sessionId);if(!r)throw new l(`No session with id "${e.sessionId}".`);return v({...r,alive:r.status==="recording"&&ze(r.pid),fileExists:W$(r.outputPath)})}catch(r){return E(r)}})}import{z as Be}from"zod";import{existsSync as U$,readFileSync as z$}from"node:fs";var $h=200,H$=5e3,G$={sessionId:Be.string().min(1).optional().describe("Session id of a recording started with events: true."),input:Be.string().optional().describe("Or a recording path, or its .events.jsonl."),from:Be.number().min(0).optional().describe("Earliest video second."),to:Be.number().min(0).optional().describe("Latest video second."),types:Be.array(Be.enum(mc)).optional().describe("down/up (mouse buttons; clicks are down), move (sampled cursor), wheel, key (shortcut), typing (burst), gap (events may be missing)."),inFrameOnly:Be.boolean().optional().describe("Drop events whose cursor was outside the recorded area."),limit:Be.number().int().min(1).max(H$).optional().describe(`Most events to return (default ${$h}).`)};function kh(t){t.registerTool("read_events",{title:"Read Input Events",description:"Read the input events (clicks, scroll, cursor, shortcuts, typing bursts) of a recording made with events: true, in video seconds and pixels; e.g. types: ['down'], then sample_frames there.",inputSchema:G$,outputSchema:N({eventsPath:Be.string(),total:Be.number().int(),matched:Be.number().int(),returned:Be.number().int(),summary:Be.record(Be.string(),Be.number())}),annotations:he},async e=>{try{let r;if(e.sessionId){let a=re().get(e.sessionId);if(!a)throw new l(`No session with id "${e.sessionId}".`);if(!a.events)throw new l(`Session "${e.sessionId}" was recorded without an event log. Start the recording with events: true.`);if(a.status==="recording"||a.status==="paused")throw new l("The recording is still running; its event log is written when it stops.");r=a.events.path}else if(e.input)r=e.input.endsWith(".jsonl")?e.input:$e(e.input).jsonl;else throw new l("Pass sessionId or input.");if(!U$(r))throw new l(`No event log at ${r}. Record with start_recording events: true.`);let n=je(z$(r,"utf8")),o=bi(n,e),i=e.limit??$h,s=rp(n);return v({eventsPath:r,total:n.length,matched:o.length,returned:Math.min(i,o.length),summary:an(n),...s.length>0?{truncated:!0,gaps:s,warning:"The log is missing events in the gaps listed: Windows removed the input hook, input went to an elevated window or the lock screen, or the helper stopped. Do not read silence there as no activity."}:{},events:o.slice(0,i),...o.length>i?{note:`${o.length-i} more matched; narrow from/to or types, or raise limit.`}:{}})}catch(r){return E(r)}})}import{z as Fn}from"zod";var q$={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},X$={label:Fn.string().min(1).max(Kc).describe('e.g. "bug appears".'),sessionId:Fn.string().min(1).optional().describe("Recording to mark (a stopped one needs at)."),input:Fn.string().min(1).optional().describe("Or a video path (needs at)."),at:Fn.number().min(0).optional().describe("Video second (default: now, while recording).")};function Eh(t){t.registerTool("add_marker",{title:"Add Marker",description:"Mark a labelled moment on a recording, live or at a second. Kept in the session and a sidecar; chapters and pipeline turn markers into chapters.",inputSchema:X$,outputSchema:N({count:Fn.number().int(),markersPath:Fn.string()}),annotations:q$},async e=>{try{if(!e.sessionId&&!e.input)throw new l("Pass sessionId or input.");if(e.sessionId){let i=ms(re(),e.sessionId,e.label,e.at);return v({sessionId:e.sessionId,marker:{t:Math.round(i.t*1e3)/1e3,label:Ro(e.label)},count:i.count,markersPath:i.markersPath,...i.live?{live:!0}:{},...i.warning?{warning:i.warning}:{}})}let r=e.input;if(e.at===void 0)throw new l("Pass at (video seconds) to mark a file.");F(r),Zt(pr(r));let n=us(Le(r),{t:e.at,label:e.label,at:new Date().toISOString()}),o=dr(r,n);return v({marker:{t:Math.round(e.at*1e3)/1e3,label:Ro(e.label)},count:n.length,markersPath:o})}catch(r){return E(r)}})}import{z as ve}from"zod";import{extname as K$,join as Fh}from"node:path";import{existsSync as V$,mkdtempSync as Q$,readFileSync as Z$,rmSync as ek,writeFileSync as tk}from"node:fs";import{tmpdir as rk}from"node:os";import{existsSync as J$}from"node:fs";var Ks="SCREENCAST_WHISPER_MODEL",_h=`Download a whisper.cpp model (ggml-base.en.bin is a good start; ggml-tiny.en.bin is fastest) from https://huggingface.co/ggerganov/whisper.cpp and pass its path as model, or set ${Ks}.`;function br(t,e=process.env){let r=t??e[Ks];if(!r||r.trim().length===0)throw new l("No whisper model given.",_h);if(!J$(r))throw new l(`Whisper model not found: ${r}`,_h);return r}function On(t,e,r,n="auto",o=!1){if(!/^[a-z]{2,3}$|^auto$/.test(n))throw new l(`language must be a code like "en" or "auto", got "${n}".`);return["-y","-v","error","-i",t,"-vn","-af",`aresample=16000,whisper=model=${ye(e)}:language=${n}:format=srt:destination=${ye(r)}:use_gpu=false`+(o?":max_len=1":""),"-f","null","-"]}function Mh(t){let e=[];for(let r of t){let n=e[e.length-1];n&&!/[\p{L}\p{N}]/u.test(r.text)?n.text+=r.text.trim():e.push({...r})}return e}var Th=/(\d+):(\d{2}):(\d{2})[,.](\d{3})/,Ah=t=>Number(t[1])*3600+Number(t[2])*60+Number(t[3])+Number(t[4])/1e3;function Rh(t){let e=Math.round(t*1e3),r=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),o=Math.floor(e%6e4/1e3),i=(s,a=2)=>String(s).padStart(a,"0");return`${i(r)}:${i(n)}:${i(o)},${i(e%1e3,3)}`}function We(t,e={}){let r=[];for(let n of t.replace(/\r\n/g,`
319
+ `)&&!r.events&&!r.markers&&!r.transcript?n.end=r.end:e.push({...r,ocr:[...r.ocr]})}return e}function th(t){let e=[];for(let r of t){let n=`at ${Math.round(r.x)},${Math.round(r.y)}`,o=null;if(r.type==="down"){let i=r.element;o=`click ${r.button??"left"} ${n}`+(i?` ${Ru(i.role)}${i.name?` ${i.name}`:""}${i.app?` ${i.app}`:""}`:"")}else r.type==="key"?o=`shortcut ${r.keys??"key"}`:r.type==="typing"?o=`typing ${wr(r.durationSec??0)} s`:r.type==="wheel"?o=`scroll ${(r.delta??0)>0?"up":"down"} ${n}`:r.type==="gap"?o=`event gap (${r.reason??"unknown"})`:r.type==="focus"&&(o=`switch to ${r.app??"app"}${r.title?` ${r.title}`:""}`);o&&e.push({t:wr(r.t),text:o})}return e}function rh(t){return t.map(e=>({t:wr(e.t),text:e.label}))}function nh(t){return t.map(e=>({t:wr(e.start),text:e.text.replace(/\s+/g," ").trim()})).filter(e=>e.text)}function Jr(t,e,r){let n=t.map(i=>{let{[r]:s,...a}=i;return a});if(n.length===0)return n;let o=i=>{let s=0,a=n.length-1,c=-1;for(;s<=a;){let u=s+a>>1;n[u].start<=i?(c=u,s=u+1):a=u-1}return c!==-1&&i<n[c].end?c:-1};for(let i of[...e].sort((s,a)=>s.t-a.t)){let s=o(i.t);s===-1&&(s=i.t<n[0].start?0:n.length-1);let a=n[s];(a[r]??=[]).push(i)}return n}function Hs(t){let e=Gf(t),r=Hf("sha1"),n=64*1024,o=_$(t,"r");try{let i=Buffer.alloc(n);for(let s of e.size>n?[0,e.size-n]:[0]){let a=A$(o,i,0,n,s);r.update(i.subarray(0,a))}}finally{E$(o)}return{size:e.size,mtimeMs:Math.round(e.mtimeMs),sample:r.digest("hex")}}function Gs(t,e){return t.size===e.size&&t.mtimeMs===e.mtimeMs&&t.sample===e.sample}function N$(t){try{let e=JSON.parse(t);return e?.version!==Ou||!Array.isArray(e.segments)||!e.fingerprint?null:e}catch{return null}}function jo(t){try{return N$(T$(t,"utf8"))}catch{return null}}var Xr=new Map,D$=64;function Bu(t){let e;try{e=Gf(t)}catch{return Xr.delete(t),null}let r=Xr.get(t);if(r&&r.size===e.size&&r.mtimeMs===e.mtimeMs)return r.index;let n=jo(t);return n?(Xr.size>=D$&&Xr.delete(Xr.keys().next().value),Xr.set(t,{size:e.size,mtimeMs:e.mtimeMs,index:n}),n):(Xr.delete(t),null)}function oh(t,e){let r=`${t}.${process.pid}.tmp`;C$(r,JSON.stringify(e)),M$(r,t)}function L$(t){let e=t.replace(/\s+/g," ").trim();return e.length>jf?`${e.slice(0,jf-1)}\u2026`:e}function B$(t){let e=[];return t.segments.forEach((r,n)=>{for(let o of r.ocr)e.push({seg:n,source:"screen",t:r.start,text:o});for(let[o,i]of[["event",r.events],["marker",r.markers],["transcript",r.transcript],["log",r.logs]])for(let s of i??[])e.push({seg:n,source:o,t:s.t,text:s.text})}),e}function ih(t,e){if(t.trim().length===0)throw new l("query must not be empty.");if(t.length>qr)throw new l(`The query is ${t.length} characters; at most ${qr} are allowed.`);if(!e&&!/[\p{L}\p{N}]/u.test(Bt(t)))throw new l("query needs at least one letter or digit.","For punctuation, use regex: true.");e&&Tn([""],t)}var zf=new WeakMap;function W$(t,e){let r=zf.get(t);r||zf.set(t,r=new Map);let n=r.get(e);if(n)return n;let o=B$(t),i=e?Le(o.map(c=>c.text),e):o.map(c=>c.text),s=o.map((c,u)=>({...c,text:i[u]??""})),a={items:s,norm:s.map(c=>Bt(c.text))};return r.set(e,a),a}function Wu(t,e,r={}){if(ih(e,r.regex===!0),r.video!==void 0&&!Bs(t,r.video,r.fingerprint))throw new l(`The index found is for ${t.video}, not ${r.video}.`,"Run index_recording on this recording.");let n=r.secretPattern===void 0?De:r.secretPattern,{items:o,norm:i}=W$(t,n??""),s=new Map,a=(p,f)=>{let m=s.get(p.seg)??{score:0,matches:[]};m.score+=f,m.matches.push(p),s.set(p.seg,m)};if(r.regex){let p=Tn(o.map(f=>f.text),e);o.forEach((f,m)=>{(p[m]??[]).length>0&&a(f,2)})}else{let p=Bt(e.trim()),f=p.split("_").filter(Boolean);if(o.forEach((m,h)=>{i[h].includes(p)&&a(m,2)}),f.length>1){let m=new Map;o.forEach((h,b)=>{let w=m.get(h.seg);w?w.push(b):m.set(h.seg,[b])});for(let[h,b]of m)if(!s.has(h)&&f.every(w=>b.some(g=>i[g].includes(w)))){for(let w of b)f.some(g=>i[w].includes(g))&&a(o[w],0);s.get(h).score=1}}}return{hits:[...s.entries()].map(([p,f])=>({seg:p,...f})).sort((p,f)=>f.score-p.score||t.segments[p.seg].start-t.segments[f.seg].start).slice(0,r.limit??Ls).map(p=>{let f=t.segments[p.seg],m=p.matches.slice(0,F$).map(h=>({source:h.source,t:h.t,text:L$(h.text)}));return{start:f.start,end:f.end,t:Math.min(...p.matches.map(h=>h.t)),score:p.score,matches:m}}),total:s.size}}var j$=20;function U$(t){return[Fn(t,"recordings"),Fn(t,"edits"),Fn(t,"edits","indexes")]}function sh(t){let e=[];for(let r of U$(t)){let n;try{n=R$(r)}catch{continue}for(let o of n)o.endsWith(".index.json")&&e.push(Fn(r,o))}return e}function ah(t,e,r={}){ih(e,r.regex===!0);let n=new Map;for(let c of t){let u=Ds(c.index.video).toLowerCase(),d=n.get(u);(!d||c.index.createdAt>d.index.createdAt)&&n.set(u,c)}let o=r.limit??Ls,i=[],s=[],a=0;for(let c of n.values()){let u=Wu(c.index,e,{regex:r.regex,limit:o});if(u.total!==0){a+=u.total,i.push({video:c.index.video,indexPath:c.indexPath,total:u.total,best:u.hits[0].score});for(let d of u.hits)s.push({video:c.index.video,...d})}}return i.sort((c,u)=>u.best-c.best||u.total-c.total),s.sort((c,u)=>u.score-c.score),{hits:s.slice(0,o),total:a,recordings:i.slice(0,j$),searched:n.size}}async function qs(t){if(t.input===void 0==(t.sessionId===void 0))throw new l("Provide exactly one of: input (a recording path) or sessionId.");if(t.sessionId!==void 0){let n=oe().get(t.sessionId);if(!n)throw new l(`No session with id "${t.sessionId}".`);if(n.status==="recording"||n.status==="paused")throw new l("The recording is still running; stop_recording it first.");if(await Zt(n.id),!In(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path,i=n.markers?.length?n.markers:We(n.outputPath);return{path:n.outputPath,eventsPath:o&&In(o)?o:null,markers:i}}let e=t.input;if(!In(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=ke(e);return{path:e,eventsPath:In(r)?r:null,markers:We(e)}}import{basename as ch}from"node:path";function uh(t,e,r){let n=ke(t),o=Us(t,e),i=[n.jsonl,n.raw,`${n.raw}.stop`,zr(t),Bo(t),Ws(t,r),fr(t),jt(t),vt(t),Qi(t),...o.path&&!o.ambiguous?[o.path]:[]];return{files:[...new Set(i)].filter(s=>ch(s)!==ch(t)),dirs:[yt(t)]}}var z$=/\.(mp4|m4v|mkv|mov|webm|avi|gif|webp)$/i;function lh(t){if(tr(t,"Recording"),!z$.test(t))throw new l(`${t} is not a video or GIF, so it is not deleted.`,"delete_recording only removes recordings and their sidecars.");if(![Pe(),...Or()??[]].some(r=>bt(t,r)&&!bt(r,t)))throw new l(`Recording ${t} is outside SCREENCAST_HOME and the allowed directories, so it is not deleted. Add its folder to SCREENCAST_ALLOWED_DIRS or the client's workspace roots, or delete it yourself.`)}var X$={sessionId:yr.string().min(1).optional().describe("Session id of the recording to delete."),input:yr.string().min(1).optional().describe("Or the recording's path.")};function fh(t){try{let e=G$(t);return e.isDirectory()?dh(t).reduce((r,n)=>r+fh(mh(t,n)),0):e.size}catch{return 0}}async function J$(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form){if(Gm())throw new l(`Not deleted: ${Po} requires the user to confirm, but this client does not support MCP elicitation.`);return!1}let n;try{({action:n}=await t.server.elicitInput({message:e,requestedSchema:{type:"object",properties:{}}},{signal:r,timeout:nu}))}catch(o){throw new l(`Not deleted: the confirmation request failed (${z(o)}).`)}if(n!=="accept")throw new l(`Not deleted: ${n==="decline"?"declined":"cancelled"} by the user.`);return!0}function hh(t){t.registerTool("delete_recording",{title:"Delete Recording",description:"Delete a finished recording with its sidecars (event log, webcam, transcript, index, markers, pause parts) and registry entries; reports bytes freed. Asks the user first when the client supports it. Edits made from it are kept.",inputSchema:X$,outputSchema:B({outputPath:yr.string(),deleted:yr.array(yr.string()),bytesFreed:yr.number(),sessionsRemoved:yr.array(yr.string())}),annotations:Ad},async(e,r)=>{try{if(!!e.sessionId==!!e.input)throw new l("Give exactly one of sessionId or input.");let n=oe(),o;if(e.sessionId){let g=n.get(e.sessionId);if(!g)throw new l(`No session with id "${e.sessionId}".`);o=g.outputPath}else o=mh(e.input);lh(o);let i=n.list().filter(g=>Wo(g.outputPath,o)),s=i.find(g=>kn(g.status));if(s)throw new l(`Recording ${s.id} is still ${s.status}; stop it first.`);let a=[];try{a=dh(q$(o))}catch{}if(Uo(o)&&!ph(o).isFile())throw new l(`${o} is not a file, so it is not deleted.`,"delete_recording only removes a recording and its sidecars.");let c=uh(o,a,we("edits")),u=[o,...c.files].filter(g=>Uo(g)&&ph(g).isFile()),d=c.dirs.filter(g=>Uo(g)),p=[...u,...d];if(p.length===0&&i.length===0)throw new l(`Nothing to delete: ${o} does not exist.`);let f=await J$(t,`Delete ${o} and ${p.length-(Uo(o)?1:0)} sidecar file(s)? This cannot be undone.`,r.signal);if(!f&&i.length===0&&!bt(o,Pe()))throw new l(`Not deleted: ${o} is not a recording this server made, and this client cannot ask you to confirm.`,"Pass the recording's sessionId, use a client that supports MCP elicitation, or delete the file yourself.");let m=0,h=[],b=[];for(let g of p){let y=fh(g);try{H$(g,{recursive:d.includes(g),force:!0}),h.push(g),m+=y}catch(v){b.push(`${g}: ${z(v)}`)}}let w=Uo(o)?[]:i.map(g=>g.id);return w.length>0&&n.remove(w),S({outputPath:o,deleted:h,bytesFreed:m,sessionsRemoved:w,confirmedByUser:f,...b.length>0?{failed:b,note:"Some files could not be deleted (in use?); the registry entry was kept if the recording remains."}:{}})}catch(n){return E(n)}})}import{z as xr}from"zod";import{existsSync as Y$}from"node:fs";function O(t,e="Input file"){if(!Y$(t))throw new l(`${e} not found: ${t}`)}function j(t,e,r,n={}){return n.anyContainer||jr(t),nr(t,we(n.dir??"edits"),`${e}-${he()}-${ge()}${r}`,n.overwrite)}var K$={sessionId:xr.string().min(1).describe("Session id of a replay buffer."),lastSec:xr.number().positive().max($n).optional().describe("Seconds back from now (default and max: the buffer length)."),output:xr.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:xr.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),reencode:xr.boolean().optional().describe("Frame-exact re-encode. Default: instant stream copy that may hide up to 2 s of earlier frames.")};function gh(t){t.registerTool("save_replay",{title:"Save Replay",description:"Save the last N seconds of a replay buffer (start_recording replayBufferSec) to an mp4; the buffer keeps running.",inputSchema:K$,outputSchema:B({sessionId:xr.string(),outputPath:xr.string(),durationSec:xr.number()}),annotations:I},async(e,r)=>{try{let n=oe().get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(!n.replay)throw new l(`Session "${e.sessionId}" is not a replay buffer.`,"Start one with start_recording { replayBufferSec: 60 }; for an ordinary recording use stop_recording and trim.");let{ffmpeg:o,ffprobe:i}=k(),s=n.replay,a=Math.min(e.lastSec??s.bufferSec,s.bufferSec),c=j(e.output,"replay",".mp4",{overwrite:e.overwrite,dir:"recordings",anyContainer:!0});s.events&&xi(ke(c),e.overwrite);let u=Date.now(),d=await Wc(s,{ffmpeg:o,ffprobe:i,lastSec:a,output:c,reencode:e.reencode,quality:n.quality,live:n.status==="recording",signal:r.signal}),p=Date.now()-u;ar("info",`Saved ${d.durationSec}s of replay ${n.id} to ${c}.`,{sessionId:n.id,outputPath:c,durationSec:d.durationSec});let f=d.durationSec+.25<a;return S({sessionId:n.id,...d,requestedSec:e.lastSec??null,bufferSec:s.bufferSec,bufferRunning:n.status==="recording",bufferDiskBytes:Gd(s),elapsedMs:p,note:(e.lastSec!==void 0&&e.lastSec>s.bufferSec?`Capped at the buffer length (${s.bufferSec}s). `:"")+(f?"The buffer held less footage than requested (it started recently). ":"")+(d.includesLive?"":"The clip ends at the last completed segment, up to 2 s before now. ")+(n.status==="recording"?"The buffer keeps running; stop_recording discards it unless save: true.":"This buffer is no longer recording; stop_recording discards it.")})}catch(n){return E(n)}})}import{z as Xs}from"zod";var bh=t=>Math.round(t*1e3)/1e3;function wh(t){t.registerTool("pause_recording",{title:"Pause Recording",description:"Pause a recording; until resume_recording nothing is captured, and the gap is left out of the file, events, and markers.",inputSchema:{sessionId:Xs.string().min(1).describe("From start_recording.")},outputSchema:B({sessionId:Xs.string(),status:Xs.string(),recordedSec:Xs.number()}),annotations:qi},async e=>{try{let r=oe(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(os(r,n.id,"pause"),n.status==="paused")return S({sessionId:n.id,status:"paused",recordedSec:bh(ot(n.segments?.parts??[])),note:"Already paused."});let{ffprobe:o}=k(),i=await vm(r,n,{probe:s=>ue(s,{ffprobe:o})});return S({sessionId:n.id,status:"paused",recordedSec:bh(i.recordedSec),segments:i.record?.segments?.parts.length??0,note:"Nothing is captured until resume_recording; stop_recording joins what was recorded."})}catch(r){return E(r)}})}import{z as Js}from"zod";var yh=t=>Math.round(t*1e3)/1e3;function xh(t){t.registerTool("resume_recording",{title:"Resume Recording",description:"Resume a paused recording (same target and settings).",inputSchema:{sessionId:Js.string().min(1).describe("From start_recording.")},outputSchema:B({sessionId:Js.string(),status:Js.string(),recordedSec:Js.number()}),annotations:I},async e=>{try{let r=oe(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(os(r,n.id,"resume"),n.status==="recording")return S({sessionId:n.id,status:"recording",recordedSec:yh(ot(n.segments?.parts??[])),note:"Already recording."});let{ffmpeg:o}=k(),i=await bf(r,n,o);return ar("notice",`Recording ${n.id} resumed.`,{sessionId:n.id}),S({sessionId:n.id,status:"recording",recordedSec:yh(i.recordedSec),pid:i.record.pid,...i.capSec>0?{remainingSec:i.capSec}:{}})}catch(r){return E(r)}})}import{z as Sh}from"zod";function vh(t){t.registerTool("list_video_devices",{title:"List Video Devices",description:"List DirectShow cameras for start_recording's webcam.device.",inputSchema:{},outputSchema:B({devices:Sh.array(Sh.string())}),annotations:fe},async()=>{try{k();let e=await ru(!0);return S({devices:e,note:e.length?`start_recording { webcam: { device: "${e[0]}" } } records it.`:"No camera found."})}catch(e){return E(e)}})}import{z as Et}from"zod";function $h(t){t.registerTool("list_sessions",{title:"List Sessions",description:"List recording sessions, newest first: id, status, target, output path, duration, and whether the recorder is alive. A summary each unless full; get_session gives one in full.",inputSchema:{status:Et.array(Et.enum(["recording","paused","stopped","failed","orphaned"])).min(1).optional().describe("Only these."),limit:Et.number().int().min(1).max(100).optional().describe("At most this many (default all)."),full:Et.boolean().optional().describe("Whole records.")},outputSchema:B({count:Et.number().int(),sessions:Et.array(B({id:Et.string(),status:Et.string(),outputPath:Et.string(),alive:Et.boolean()}))}),annotations:fe},async e=>{try{let r=oe().list(),o=r.filter(s=>!e.status||e.status.includes(s.status)).sort((s,a)=>a.startedAt.localeCompare(s.startedAt)).slice(0,e.limit??1/0).map(s=>{let a=s.status==="recording"&&Ge(s.pid);return e.full?{...s,alive:a}:{id:s.id,status:s.status,target:s.target,outputPath:s.outputPath,startedAt:s.startedAt,...s.stoppedAt?{stoppedAt:s.stoppedAt}:{},durationSec:s.durationSec??null,...s.endReason?{endReason:s.endReason}:{},...s.error?{error:s.error.split(`
320
+ `)[0]}:{},alive:a}}),i=of();return S({count:o.length,...o.length<r.length?{total:r.length}:{},sessions:o,...i.length?{armed:i}:{}})}catch(r){return E(r)}})}import{z as On}from"zod";import{existsSync as V$}from"node:fs";var Q$={sessionId:On.string().min(1).describe("Session id returned by start_recording.")};function kh(t){t.registerTool("get_session",{title:"Get Session",description:"Inspect a single recording session by id, including live status and whether its output file exists on disk.",inputSchema:Q$,outputSchema:B({id:On.string(),status:On.string(),outputPath:On.string(),alive:On.boolean(),fileExists:On.boolean()}),annotations:fe},async e=>{try{if($s(e.sessionId)){let n=Io(e.sessionId);if(!n)throw new l(`No armed recording with id "${e.sessionId}".`);return S({...n,outputPath:"",alive:!1,fileExists:!1,...n.sessionId?{note:`It started recording ${n.sessionId}; get_session that id for it.`}:{}})}let r=oe().get(e.sessionId);if(!r)throw new l(`No session with id "${e.sessionId}".`);return S({...r,alive:r.status==="recording"&&Ge(r.pid),fileExists:V$(r.outputPath)})}catch(r){return E(r)}})}import{z as je}from"zod";import{existsSync as Z$,readFileSync as ek}from"node:fs";var Eh=200,tk=5e3,rk={sessionId:je.string().min(1).optional().describe("Session id of a recording started with events: true."),input:je.string().optional().describe("Or a recording path, or its .events.jsonl."),from:je.number().min(0).optional().describe("Earliest video second."),to:je.number().min(0).optional().describe("Latest video second."),types:je.array(je.enum(fc)).optional().describe("down/up (mouse buttons; clicks are down), move (sampled cursor), wheel, key (shortcut), typing (burst), gap (events may be missing)."),inFrameOnly:je.boolean().optional().describe("Drop events whose cursor was outside the recorded area."),limit:je.number().int().min(1).max(tk).optional().describe(`Most events to return (default ${Eh}).`)};function _h(t){t.registerTool("read_events",{title:"Read Input Events",description:"Read the input events (clicks, scroll, cursor, shortcuts, typing bursts) of a recording made with events: true, in video seconds and pixels; e.g. types: ['down'], then sample_frames there.",inputSchema:rk,outputSchema:B({eventsPath:je.string(),total:je.number().int(),matched:je.number().int(),returned:je.number().int(),summary:je.record(je.string(),je.number())}),annotations:fe},async e=>{try{let r;if(e.sessionId){let a=oe().get(e.sessionId);if(!a)throw new l(`No session with id "${e.sessionId}".`);if(!a.events)throw new l(`Session "${e.sessionId}" was recorded without an event log. Start the recording with events: true.`);if(a.status==="recording"||a.status==="paused")throw new l("The recording is still running; its event log is written when it stops.");r=a.events.path}else if(e.input)r=e.input.endsWith(".jsonl")?e.input:ke(e.input).jsonl;else throw new l("Pass sessionId or input.");if(!Z$(r))throw new l(`No event log at ${r}. Record with start_recording events: true.`);let n=ze(ek(r,"utf8")),o=wi(n,e),i=e.limit??Eh,s=op(n);return S({eventsPath:r,total:n.length,matched:o.length,returned:Math.min(i,o.length),summary:pn(n),...s.length>0?{truncated:!0,gaps:s,warning:"The log is missing events in the gaps listed: Windows removed the input hook, input went to an elevated window or the lock screen, or the helper stopped. Do not read silence there as no activity."}:{},events:o.slice(0,i),...o.length>i?{note:`${o.length-i} more matched; narrow from/to or types, or raise limit.`}:{}})}catch(r){return E(r)}})}import{z as Nn}from"zod";var nk={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},ok={label:Nn.string().min(1).max(Vc).describe('e.g. "bug appears".'),sessionId:Nn.string().min(1).optional().describe("Recording to mark (a stopped one needs at)."),input:Nn.string().min(1).optional().describe("Or a video path (needs at)."),at:Nn.number().min(0).optional().describe("Video second (default: now, while recording).")};function Th(t){t.registerTool("add_marker",{title:"Add Marker",description:"Mark a labelled moment on a recording, live or at a second. Kept in the session and a sidecar; chapters and pipeline turn markers into chapters.",inputSchema:ok,outputSchema:B({count:Nn.number().int(),markersPath:Nn.string()}),annotations:nk},async e=>{try{if(!e.sessionId&&!e.input)throw new l("Pass sessionId or input.");if(e.sessionId){let i=fs(oe(),e.sessionId,e.label,e.at);return S({sessionId:e.sessionId,marker:{t:Math.round(i.t*1e3)/1e3,label:Mo(e.label)},count:i.count,markersPath:i.markersPath,...i.live?{live:!0}:{},...i.warning?{warning:i.warning}:{}})}let r=e.input;if(e.at===void 0)throw new l("Pass at (video seconds) to mark a file.");O(r),rr(fr(r));let n=ls(We(r),{t:e.at,label:e.label,at:new Date().toISOString()}),o=hr(r,n);return S({marker:{t:Math.round(e.at*1e3)/1e3,label:Mo(e.label)},count:n.length,markersPath:o})}catch(r){return E(r)}})}import{z as ve}from"zod";import{extname as ak,join as Nh}from"node:path";import{existsSync as ck,mkdtempSync as uk,readFileSync as lk,rmSync as pk,writeFileSync as dk}from"node:fs";import{tmpdir as mk}from"node:os";import{existsSync as ik}from"node:fs";var Ks="SCREENCAST_WHISPER_MODEL",Rh=`Download a whisper.cpp model (ggml-base.en.bin is a good start; ggml-tiny.en.bin is fastest) from https://huggingface.co/ggerganov/whisper.cpp and pass its path as model, or set ${Ks}.`;function Sr(t,e=process.env){let r=t??e[Ks];if(!r||r.trim().length===0)throw new l("No whisper model given.",Rh);if(!ik(r))throw new l(`Whisper model not found: ${r}`,Rh);return r}function Dn(t,e,r,n="auto",o=!1){if(!/^[a-z]{2,3}$|^auto$/.test(n))throw new l(`language must be a code like "en" or "auto", got "${n}".`);return["-y","-v","error","-i",t,"-vn","-af",`aresample=16000,whisper=model=${ye(e)}:language=${n}:format=srt:destination=${ye(r)}:use_gpu=false`+(o?":max_len=1":""),"-f","null","-"]}function Ph(t){let e=[];for(let r of t){let n=e[e.length-1];n&&!/[\p{L}\p{N}]/u.test(r.text)?n.text+=r.text.trim():e.push({...r})}return e}var Ah=/(\d+):(\d{2}):(\d{2})[,.](\d{3})/,Mh=t=>Number(t[1])*3600+Number(t[2])*60+Number(t[3])+Number(t[4])/1e3;function Ch(t){let e=Math.round(t*1e3),r=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),o=Math.floor(e%6e4/1e3),i=(s,a=2)=>String(s).padStart(a,"0");return`${i(r)}:${i(n)}:${i(o)},${i(e%1e3,3)}`}function Ue(t,e={}){let r=[];for(let n of t.replace(/\r\n/g,`
320
321
  `).split(/\n\s*\n/)){let o=n.split(`
321
- `).map(m=>m.trim()).filter(m=>m.length>0),i=o.findIndex(m=>m.includes("-->")),s=o[i];if(s===void 0)continue;let[a,c]=s.split("-->"),u=a?.match(Th),d=c?.match(Th);if(!u||!d)continue;let p=o.slice(i+1).join(`
322
- `);if(!p)continue;let f=e.index&&i>0&&/^\d+$/.test(o[i-1])?Number(o[i-1]):void 0;r.push({start:Ah(u),end:Ah(d),text:p,...f!==void 0&&{index:f}})}return r}function ut(t){let e=[...t].sort((r,n)=>r.start-n.start);return e.map((r,n)=>{let o=e[n+1],i=o?Math.min(r.end,o.start):r.end;return{...r,end:i}}).filter(r=>r.end>r.start)}function nt(t){return t.map((e,r)=>`${r+1}
323
- ${Rh(e.start)} --> ${Rh(e.end)}
322
+ `).map(m=>m.trim()).filter(m=>m.length>0),i=o.findIndex(m=>m.includes("-->")),s=o[i];if(s===void 0)continue;let[a,c]=s.split("-->"),u=a?.match(Ah),d=c?.match(Ah);if(!u||!d)continue;let p=o.slice(i+1).join(`
323
+ `);if(!p)continue;let f=e.index&&i>0&&/^\d+$/.test(o[i-1])?Number(o[i-1]):void 0;r.push({start:Mh(u),end:Mh(d),text:p,...f!==void 0&&{index:f}})}return r}function pt(t){let e=[...t].sort((r,n)=>r.start-n.start);return e.map((r,n)=>{let o=e[n+1],i=o?Math.min(r.end,o.start):r.end;return{...r,end:i}}).filter(r=>r.end>r.start)}function it(t){return t.map((e,r)=>`${r+1}
324
+ ${Ch(e.start)} --> ${Ch(e.end)}
324
325
  ${e.text}
325
326
  `).join(`
326
- `)}var Vs=["clean","social"],Y$={clean:"FontName=Inter,FontSize=16,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=1.5,Shadow=0,MarginV=16",social:"FontName=Inter,Bold=1,FontSize=22,PrimaryColour=&H00FFFFFF,BackColour=&H99000000,BorderStyle=3,Outline=6,Shadow=0,MarginV=40"};function Wu(t,e,r="clean"){let n=r===null?null:Y$[r];if(n===void 0)throw new l(`Unknown caption style "${r}".`);return`subtitles=filename=${ye(t)}:fontsdir=${ye(e)}`+(n?`:force_style='${n}'`:"")}function Ch(t,e,r,n,o="clean",i="standard"){return["-y","-i",t,"-vf",Wu(e,n,o),..._e(i),"-c:a","copy",r]}var Ys=1e3;function Ph(t,e){if(e.length!==t.length)throw new l(`Got ${e.length} translations for ${t.length} cues.`,"Translate every cue, in order, one string per cue (merge or split nothing).");return t.map((r,n)=>{let o=e[n].replace(/\r\n/g,`
327
+ `)}var Vs=["clean","social"],sk={clean:"FontName=Inter,FontSize=16,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=1.5,Shadow=0,MarginV=16",social:"FontName=Inter,Bold=1,FontSize=22,PrimaryColour=&H00FFFFFF,BackColour=&H99000000,BorderStyle=3,Outline=6,Shadow=0,MarginV=40"};function ju(t,e,r="clean"){let n=r===null?null:sk[r];if(n===void 0)throw new l(`Unknown caption style "${r}".`);return`subtitles=filename=${ye(t)}:fontsdir=${ye(e)}`+(n?`:force_style='${n}'`:"")}function Ih(t,e,r,n,o="clean",i="standard"){return["-y","-i",t,"-vf",ju(e,n,o),...Re(i),"-c:a","copy",r]}var Ys=1e3;function Fh(t,e){if(e.length!==t.length)throw new l(`Got ${e.length} translations for ${t.length} cues.`,"Translate every cue, in order, one string per cue (merge or split nothing).");return t.map((r,n)=>{let o=e[n].replace(/\r\n/g,`
327
328
  `).trim();if(!o)throw new l(`Translation ${n+1} is empty.`);if(o.length>Ys)throw new l(`Translation ${n+1} is over ${Ys} characters.`);return{start:r.start,end:r.end,text:o.replace(/\n\s*\n/g,`
328
- `)}})}function Ih(t,e){return t.replace(/\.srt$/i,"")+`.${e}.srt`}var nk=new Set([".mp4",".mkv",".mov"]),ok=12,ik={input:ve.string().min(1).optional().describe("Path to the video."),sessionId:ve.string().min(1).optional().describe("Or a stopped recording's id."),from:ve.enum(["markers","scenes","transcript"]).optional().describe("markers (default; add_marker, else the file's chapters), scenes (screen changes), or transcript (SRT sections)."),chapters:ve.array(ve.object({start:ve.number().min(0),title:ve.string().min(1).max(100)})).min(1).max(200).optional().describe("Or explicit { start, title } chapters."),transcript:ve.string().optional().describe("The .srt for from: transcript."),minChapterSec:ve.number().min(0).optional().describe(`Shortest chapter (default 1; scenes ${Sn}, transcript 30).`),subtitles:ve.string().optional().describe("Also mux this .srt/.vtt/.ass as a soft subtitle track."),subtitleLanguage:ve.string().regex(/^[a-z]{3}$/).optional().describe('ISO 639-2, e.g. "eng".'),subtitleTracks:ve.array(ve.object({file:ve.string().min(1),language:ve.string().regex(/^[a-z]{3}$/).optional(),title:ve.string().max(60).optional(),default:ve.boolean().optional()})).min(1).max(cs).optional().describe("Or several tracks, e.g. one per language (translate_subtitles makes them)."),textOnly:ve.boolean().optional().describe("Return chapters and YouTube text only; write no file."),output:ve.string().optional().describe("Optional .mp4/.mkv/.mov path. Defaults under SCREENCAST_HOME/edits."),overwrite:ve.boolean().optional().describe("Allow replacing an existing output file.")};function Oh(t){t.registerTool("chapters",{title:"Chapters",description:"Write chapters (markers, scene changes, transcript, or a list) into an mp4/mkv/mov copy without re-encoding; returns YouTube chapter text. Can mux an SRT as soft subtitles.",inputSchema:ik,outputSchema:N({chapters:ve.array(N({start:ve.number(),end:ve.number(),title:ve.string()})),youtube:ve.string()}),annotations:I},async(e,r)=>{try{k();let n=e.input,o;if(e.sessionId){let y=re().get(e.sessionId);if(!y)throw new l(`No session with id "${e.sessionId}".`);if(y.status==="recording"||y.status==="paused")throw new l("The recording is still running; stop it first.");n??=y.outputPath,o=y.markers}if(!n)throw new l("Pass input or sessionId.");if(F(n),e.subtitles&&e.subtitleTracks)throw new l("Pass subtitles or subtitleTracks, not both.");let i=e.subtitleTracks??(e.subtitles?[{file:e.subtitles,...e.subtitleLanguage?{language:e.subtitleLanguage}:{}}]:[]);for(let y of[e.transcript,...i.map($=>$.file)])if(y!==void 0&&!V$(y))throw new l(`File not found: ${y}`);for(let y of i)if(!/\.(srt|vtt|ass|ssa)$/i.test(y.file))throw new l(`Subtitles must be .srt, .vtt, or .ass files, not ${y.file}.`);let a=(await L(n)).durationSec;if(!a||a<=0)throw new l(`Could not read the duration of ${n}.`);let c=e.chapters?"list":e.from??"markers",u,d=1,p=c;if(e.chapters)u=e.chapters;else if(c==="scenes"){d=Sn;let{ffmpeg:y}=k(),$=await ne(y,rr(n,gt),le(a),{signal:r.signal});if($.code!==0)throw new l(`Scene scan failed (exit ${$.code}): ${$.stderr.trim().slice(-400)}`);u=Cm(nr($.stdout),e.minChapterSec??d,ok)}else if(c==="transcript"){if(!e.transcript)throw new l("from: transcript needs transcript (an .srt path).");if(d=30,u=Pm(We(Z$(e.transcript,"utf8")),{minChapterSec:e.minChapterSec??d}),u.length===0)throw new l(`No cues in ${e.transcript}.`)}else{let y=o??[];if(y.length===0){let $=await mr(n,r.signal);y=$.markers,$.from==="chapters"&&(p="embedded chapters")}if(y.length===0)throw new l(`No markers for ${n}.`,"Add some with add_marker, or use from: scenes / transcript, or pass chapters.");u=ds(y)}let f=ls(u,a,{minChapterSec:e.minChapterSec??d});if(f.length===0)throw new l("No chapter falls inside the video.");let m=Mm(f,a),h={source:p,chapters:f,youtube:m.text,...m.issues.length>0?{youtubeIssues:m.issues}:{}};if(e.textOnly)return v(h);let b=e.output?K$(e.output).toLowerCase():V(n);if(!nk.has(b))throw new l(`Chapters can be written to .mp4, .mkv, or .mov, not ${b||"a file without an extension"}.`);let w=B(e.output,"chapters",b,{overwrite:e.overwrite,anyContainer:!0}),g=Q$(Fh(rk(),"screencast-chapters-"));try{let y=Fh(g,"chapters.txt");tk(y,ps(f)),await W(Im(n,y,w,{container:b,subtitles:i}),{output:w,durationSec:a,extra:r})}finally{ek(g,{recursive:!0,force:!0})}return v({outputPath:w,...h,...e.subtitles?{subtitleTrack:{...i[0],codec:b===".mkv"?"copy":"mov_text"}}:{},...e.subtitleTracks?{subtitleTracks:i.map(y=>({...y,codec:b===".mkv"?"copy":"mov_text"}))}:{}})}catch(n){return E(n)}})}import{z as lt}from"zod";import{existsSync as ck,readFileSync as qh,rmSync as uk}from"node:fs";var Uo="ui://screencast/player",Qs="text/html;profile=mcp-app",Dh={ui:{resourceUri:Uo},"ui/resourceUri":Uo},Nh="io.modelcontextprotocol/ui";function Lh(t){let e=t,r=e?.extensions?.[Nh]??e?.experimental?.[Nh];return!r||typeof r!="object"?!1:!Array.isArray(r.mimeTypes)||r.mimeTypes.includes(Qs)}var Zs=120,Bh=300,sk=4,ju=640,ak=.01;function Wh(t,e=Zs){if(!(t>0))throw new l("The video has no duration to review.");let r=Math.max(1,Math.min(e,Math.ceil(t*sk))),n=Number((t/r).toFixed(6));return{count:r,intervalSec:n,sceneGapSec:Number(Math.max(.25,n/4).toFixed(6))}}function jh(t,e,r,n,o=ak){let i=e.intervalSec,s=`isnan(prev_t)+gt(floor((t-start_t)/${i})\\,floor((prev_t-start_t)/${i}))`,a=`gt(scene\\,${o})*not(${s})*(isnan(prev_selected_t)+gte(t-prev_selected_t\\,${e.sceneGapSec}))`;return["-v","error","-i",t,"-an","-vf",`scale='min(${r},iw)':-2,split[g][s];[g]select='${s}',metadata=add:key=kind:value=grid[g1];[s]select='${a}',metadata=add:key=kind:value=scene[s1];[g1][s1]interleave,metadata=print:file=${ye(n)}`,"-fps_mode","passthrough","-q:v","6","-f","image2pipe","-c:v","mjpeg","-"]}function Uh(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.match(/pts_time:\s*(-?[\d.]+)/);if(n){e.push({timeSec:Number(n[1]),scene:!1,score:0});continue}let o=e.at(-1);if(!o)continue;r==="kind=scene"&&(o.scene=!0);let i=r.match(/^lavfi\.scene_score=([\d.]+)/);i&&(o.score=Number(i[1]))}return e}function zh(t,e){let r=t.map((o,i)=>({f:o,i})).filter(o=>o.f.scene).sort((o,i)=>i.f.score-o.f.score).slice(0,Math.max(0,e)),n=new Set(r.map(o=>o.i));return t.flatMap((o,i)=>!o.scene||n.has(i)?[i]:[])}function Hh(t){let e=[],r=-1;for(let n=0;n+1<t.length;n++){if(t[n]!==255)continue;let o=t[n+1];o===216&&r<0?r=n:o===217&&r>=0&&(e.push(t.subarray(r,n+2)),r=-1,n++)}return e}var Gh=t=>qh(vn("ui",t),"utf8");function lk(){let t=Gh("player.js");if(/<\/script/i.test(t))throw new l("player.js must not contain a closing script tag.");return Gh("player.html").replace('<script src="player.js"></script>',()=>`<script>
329
- ${t}</script>`)}function pk(t){if(t.sessionId){let e=re().get(t.sessionId);if(!e)throw new l(`No session with id "${t.sessionId}".`);if(e.status==="recording"||e.status==="paused")throw new l("The recording is still running; stop it first.");return e.outputPath}if(t.input)return t.input;throw new l("Pass input or sessionId.")}function dk(t){return t&&t.length>0?{markers:t.map(({t:e,label:r})=>({t:e,label:r}))}:{}}function Xh(t){t.registerResource("review-player",Uo,{title:"Recording review player",description:"Interactive player: scrub, trim, and draw redaction boxes on a recording.",mimeType:Qs},async()=>({contents:[{uri:Uo,mimeType:Qs,text:lk(),_meta:{ui:{prefersBorder:!0}}}]})),t.registerTool("review_recording",{title:"Review Recording",description:"Open a recording for a person to review: in MCP Apps clients an inline player to scrub, trim, and redact, then export; elsewhere just the video's details.",inputSchema:{input:lt.string().optional().describe("Path to the video."),sessionId:lt.string().optional().describe("Or the session id of a stopped recording.")},outputSchema:N({input:lt.string(),durationSec:lt.number().nullable(),width:lt.number().nullable(),height:lt.number().nullable(),fps:lt.number().nullable(),hasAudio:lt.boolean()}),annotations:he,_meta:Dh},async n=>{try{k();let o=pk(n);F(o);let i=await L(o);return v({input:o,durationSec:i.durationSec,width:i.width,height:i.height,fps:i.fps,hasAudio:i.audioCodec!==null,...dk(n.sessionId?re().get(n.sessionId)?.markers??Le(o):Le(o)),note:"Clients with MCP Apps show an inline review player for this result. Without it, look with contact_sheet or sample_frames, then trim and redact with pipeline."})}catch(o){return E(o)}});let e=t.registerTool("player_frames",{title:"Player Frames",description:"Preview frames for the review player: JPEGs on an even grid over the video plus frames at scene changes, with their real times. Used by the inline player; agents should use sample_frames or contact_sheet instead.",inputSchema:{input:lt.string().min(1).describe("Path to the video."),maxFrames:lt.number().int().min(1).max(Bh).optional().describe(`Frames on the even grid (default ${Zs}); scene-change frames come on top, up to as many again.`),width:lt.number().int().min(64).max(1280).optional().describe(`Frame width (default ${ju}).`)},annotations:he,_meta:{ui:{visibility:["app"]}}},async(n,o)=>{try{k(),F(n.input);let i=await L(n.input),s=i.durationSec??0,a=Wh(s,n.maxFrames??Zs),c=Ue(".txt"),u,d;try{let g=await Dr(jh(n.input,a,n.width??ju,c),le(s),{signal:o.signal});u=Hh(g),d=Uh(ck(c)?qh(c,"utf8"):"").slice(0,u.length)}finally{uk(c,{force:!0})}let[p]=d;if(!p)throw new l("ffmpeg returned no preview frames.");let f=zh(d,a.count).flatMap(g=>{let y=d[g],$=u[g];return y&&$?[{frame:y,jpeg:$}]:[]}),m=p.timeSec,h=[];try{h=(await mr(n.input,o.signal)).markers.map(({t:g,label:y})=>({t:g,label:y}))}catch{}let b=f.map(({frame:g})=>Math.round((g.timeSec-m)*1e3)/1e3),w=f.flatMap(({frame:g},y)=>g.scene?[y]:[]);return{content:[{type:"text",text:JSON.stringify({input:n.input,durationSec:s,width:i.width,height:i.height,hasAudio:i.audioCodec!==null,frameTimes:b,intervalSec:a.intervalSec,sceneFrames:w,markers:h})},...f.map(({jpeg:g})=>({type:"image",data:g.toString("base64"),mimeType:"image/jpeg"}))]}}catch(i){return E(i)}});e.disable();let r=t.server.oninitialized;t.server.oninitialized=()=>{r?.(),Lh(t.server.getClientCapabilities())&&e.enable()}}import{z as pt}from"zod";import{readFileSync as mk,rmSync as fk}from"node:fs";var Ae=1280,ea=8,zo=20;function hk(t,e,r){if(!Number.isInteger(r)||r<16)throw new l("maxImageWidth must be an integer of at least 16.");return["-y","-v","error","-i",t,"-frames:v","1","-vf",`scale='min(${r},iw)':-2`,"-q:v","4",...Ee(e)]}function ta(t){return Math.max(0,Math.min(zo,Math.floor(t??ea)))}async function Re(t,e=Ae,r=ea){let n=t.slice(0,r);return{images:await He(n,async i=>{let s=Ue(".jpg");try{return await Z(hk(i,s,e),3e4),{type:"image",data:mk(s).toString("base64"),mimeType:"image/jpeg"}}finally{fk(s,{force:!0})}}),omitted:t.length-n.length}}var gk={target:pt.string().describe("full | monitor:<i> (0 = primary) | window:<title> (or window:exe=<app.exe> / window:hwnd=<n>) | region:<x>,<y>,<w>,<h>. Titles match exactly, else as a substring; topmost wins."),exactTitle:pt.boolean().optional().describe("window: targets match the whole title only, never a substring (default false)."),backend:pt.enum(["gdigrab","wgc"]).optional().describe("gdigrab (default, ~0.2 s): what is visible. wgc (window:, FFmpeg 8+, ~1-2 s): the window even if covered."),output:pt.string().optional().describe("Optional output .png path. Defaults to a file under SCREENCAST_HOME/screenshots."),overwrite:pt.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),returnImage:pt.boolean().optional().describe("Return the image inline (default true; the PNG on disk stays full size)."),maxImageWidth:pt.number().int().min(16).optional().describe(`Max inline image width (default ${Ae}).`)};function Jh(t){t.registerTool("screenshot",{title:"Take Screenshot",description:"Capture one PNG of the screen, a monitor, a window, or a region, returned inline and by path.",inputSchema:gk,outputSchema:N({outputPath:pt.string(),target:pt.string(),backend:pt.string(),inlineImages:pt.number().int()}),annotations:I},async(e,r)=>{try{k();let n=await at(e.target,{exactTitle:e.exactTitle,backend:e.backend}),{window:o}=n,i=B(e.output,"shot",".png",{overwrite:e.overwrite,dir:"screenshots",anyContainer:!0}),s=e.backend??"gdigrab";await Ot(t,`Take a screenshot of ${Ft(e.target,o)}, saved to ${i}?`,r.signal),await Nt(n,i,s);let a=e.returnImage===!1?[]:(await Re([i],e.maxImageWidth??Ae,1)).images;return v({outputPath:i,target:e.target,backend:s,...o?cr(o):{},inlineImages:a.length},a)}catch(n){return E(n)}})}import{z as Pe}from"zod";import{join as Uu}from"node:path";import{mkdirSync as bk,readdirSync as Yh,existsSync as wk,rmSync as yk}from"node:fs";var xk={input:Pe.string().min(1).describe("Path to the source video file."),mode:Pe.enum(["fps","timestamps","scenes"]).optional().describe("scenes: only frames where the screen changed (strongest first), usually the cheapest review. Default: fps or timestamps, whichever is given."),fps:Pe.number().positive().optional().describe("Frames per second (mode fps)."),timestamps:Pe.array(Pe.number().nonnegative()).optional().describe("Seconds to grab a frame at (mode timestamps)."),sceneThreshold:Pe.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed to count, 0-1 (default ${gt}).`),dedupe:Pe.boolean().optional().describe("Mode fps: drop near-duplicate frames (default false)."),outputDir:Pe.string().optional().describe("Optional folder for the frames (a relative path resolves under SCREENCAST_HOME/frames). Defaults to SCREENCAST_HOME/frames/<id>."),maxFrames:Pe.number().int().min(1).max(kc).optional().describe(`Frame cap (default ${Ri}); fps is lowered to fit while still spanning the video.`),returnImages:Pe.boolean().optional().describe("Return the first maxInlineImages frames inline (default true)."),maxInlineImages:Pe.number().int().min(0).max(zo).optional().describe(`Frames to embed inline (default ${ea}); all are listed by path.`),maxImageWidth:Pe.number().int().min(16).optional().describe(`Max inline image width (default ${Ae}).`)};function Kh(t){t.registerTool("sample_frames",{title:"Sample Frames",description:"Sample PNG frames from a video (by fps, timestamps, or scene changes) and return the first few inline so the model can see what happened.",inputSchema:xk,outputSchema:N({frameDir:Pe.string(),frameCount:Pe.number().int(),frames:Pe.array(Pe.string()),mode:Pe.string()}),annotations:he},async(e,r)=>{try{k(),F(e.input);let n=e.fps!==void 0,o=e.timestamps!==void 0&&e.timestamps.length>0,i=e.mode??(o?"timestamps":"fps");if(!(i==="scenes"?!n&&!o:i==="fps"?n&&!o:o&&!n))throw new l("Use exactly one way to pick frames: fps (fixed rate), timestamps (explicit offsets), or mode: 'scenes' (with neither fps nor timestamps).");let a=e.maxFrames??Ri;if(o&&e.timestamps.length>a)throw new l(`${e.timestamps.length} timestamps exceeds maxFrames (${a}). Pass fewer timestamps, or raise maxFrames (up to ${kc}).`);let c=i==="timestamps"?null:(await L(e.input)).durationSec,u=i==="fps"?Mi(c,e.fps,a):null,d=null,p=[];if(i==="scenes"){let{ffmpeg:w}=k(),g=await ne(w,rr(e.input,e.sceneThreshold??gt),le(c),{signal:r.signal});if(g.code!==0)throw new l(`Scene scan failed (exit ${g.code}): ${g.stderr.trim().slice(-400)}`);d=nr(g.stdout),p=mn(d,a)}let f=ln(e.outputDir,we("frames"))??Uu(we("frames"),`sample-${ge()}-${be()}`);bk(f,{recursive:!0});let m=[],h=[];if(u){let w=S=>S.endsWith(".png"),g=new Set(Yh(f).filter(w)),y=kp(g,`${ge()}-${be()}`),$=un(f,`${y}%05d.png`);await Z(Ci(e.input,u.fps,$,a,e.dedupe===!0),le(c),{signal:r.signal}),m=Yh(f).filter(S=>w(S)&&S.startsWith(y)&&!g.has(S)).sort().map(S=>Uu(f,S))}else{let w=i==="scenes"?p:e.timestamps,g=await He(w,async(y,$)=>{let S=Uu(f,`frame_${String($).padStart(3,"0")}_${y}s.png`);return yk(S,{force:!0}),await Z(fn(e.input,y,S),6e4,{signal:r.signal}),S});for(let[y,$]of g.entries())wk($)?m.push($):h.push(w[y])}let b=e.returnImages===!1?{images:[],omitted:0}:await Re(m,e.maxImageWidth??Ae,ta(e.maxInlineImages));return v({frameDir:f,frameCount:m.length,frames:m,mode:u?`fps=${u.fps}${e.dedupe?" (deduped)":""}`:d?`scenes (threshold ${e.sceneThreshold??gt})`:`timestamps=[${e.timestamps.join(", ")}]`,...d?{frameTimes:p,sceneChangesFound:d.length,...d.length+1>a?{capNote:`Found ${d.length} scene changes; kept the opening frame and the ${a-1} strongest (maxFrames ${a}). Raise sceneThreshold to keep only bigger changes, or raise maxFrames.`}:{}}:{},...u?.clamped?{requestedFps:e.fps,capNote:`fps=${e.fps} would write about ${u.requestedFrames} frames, over maxFrames (${a}); sampled at fps=${u.fps} instead so the frames still span the whole video. Raise maxFrames or use timestamps for more detail.`}:{},...u&&!u.clamped&&m.length>=a?{capNote:`Stopped at maxFrames (${a}); the video's length could not be probed in advance.`}:{},inlineImages:b.images.length,...b.omitted>0?{inlineNote:`Embedded the first ${b.images.length} of ${m.length} frames inline; the other ${b.omitted} are on disk at the listed paths.`}:{},...h.length>0?{skippedTimestamps:h,note:`No frame was written for ${h.length} timestamp(s) past the end of the video: [${h.join(", ")}].`}:{}},b.images)}catch(n){return E(n)}})}import{z as Ve}from"zod";var Sk={input:Ve.string().min(1).describe("Path to the source video."),count:Ve.number().int().min(1).max(Af).optional().describe(`Frames to tile (default ${Oo}).`),mode:Ve.enum(["even","scenes"]).optional().describe("even (default) or scenes (strongest changes; static stretches take no tiles)."),sceneThreshold:Ve.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed, 0-1 (default ${gt}).`),columns:Ve.number().int().min(1).max(12).optional().describe("Tiles per row (default: roughly square)."),tileWidth:Ve.number().int().min(64).max(1920).optional().describe(`Tile width in px (default ${No}).`),poster:Ve.boolean().optional().describe("Write one representative poster frame instead of a sheet."),output:Ve.string().optional().describe("Optional output .png path. Defaults under SCREENCAST_HOME/frames."),overwrite:Ve.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),returnImage:Ve.boolean().optional().describe("Return the sheet inline (default true)."),maxImageWidth:Ve.number().int().min(16).optional().describe(`Max inline image width (default ${Ae}).`)};function Vh(t){t.registerTool("contact_sheet",{title:"Contact Sheet",description:"Tile timestamped frames of a video into one image to see a whole recording at a glance (the cheapest first look).",inputSchema:Sk,outputSchema:N({outputPath:Ve.string(),inlineImages:Ve.number().int()}),annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();F(e.input);let{durationSec:o}=await L(e.input);if(o===null)throw new l(`Could not read duration of ${e.input}.`);let i=e.poster?"poster":"sheet",s=er(e.output,we("frames"),`${i}-${ge()}-${be()}.png`,e.overwrite),a=e.tileWidth??No,c;if(e.poster)await Z(Rf(e.input,o,s,Math.max(a,1280)),le(o),{signal:r.signal}),c={outputPath:s,poster:!0};else{let d=e.count??Oo,p;if(e.mode==="scenes"){let m=await ne(n,rr(e.input,e.sceneThreshold??gt),le(o),{signal:r.signal});if(m.code!==0)throw new l(`Scene scan failed (exit ${m.code}): ${m.stderr.trim().slice(-400)}`);p=mn(nr(m.stdout),d)}else p=Ms(o,d);let f=await Cs(e.input,p,s,{tileWidth:a,columns:e.columns},r.signal);c={outputPath:s,mode:e.mode??"even",frameTimes:p,columns:f.columns,rows:f.rows}}let u=e.returnImage===!1?[]:(await Re([s],e.maxImageWidth??Ae,1)).images;return v({...c,inlineImages:u.length},u)}catch(n){return E(n)}})}import{z as Et}from"zod";import{rmSync as Ek}from"node:fs";var Qh=320,vk=4,$k=1600,$t=8,Ho=12;function Zh(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(Qh,t),n=Math.max(2,Math.round(e*r/t/2)*2);return{width:Math.max(2,Math.round(r/2)*2),height:n}}function na(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(t,Math.max(Qh,Math.min($k,Math.ceil(t/vk)))),n=Math.max(2,Math.round(e*r/t/2)*2);return{width:Math.max(2,Math.round(r/2)*2),height:n}}function oa(t,e){switch(t.kind){case"region":return{x:t.x,y:t.y,width:t.w,height:t.h};case"monitor":{let r=e.find(n=>n.index===t.index);if(!r)throw new l(`No monitor ${t.index}.`);return{x:r.x,y:r.y,width:r.width,height:r.height}}case"full":{if(e.length===0)throw new l("No monitors found.");let r=Math.min(...e.map(s=>s.x)),n=Math.min(...e.map(s=>s.y)),o=Math.max(...e.map(s=>s.x+s.width)),i=Math.max(...e.map(s=>s.y+s.height));return{x:r,y:n,width:o-r,height:i-n}}default:throw new l("Internal: resolve window targets to a region first.")}}function kk(t,e){if(t.length!==e.length||t.length===0)throw new l("Frames differ in size.");let r=0;for(let n=0;n<t.length;n++)r+=Math.abs(t[n]-e[n]);return r/t.length/255}function kt(t,e,r,n,o={}){if(t.length!==r*n||e.length!==r*n)throw new l("Frame size does not match its dimensions.");let i=o.pixelThreshold??Ho,s=Math.ceil(r/$t),a=Math.ceil(n/$t),c=new Uint8Array(s*a);for(let g=0;g<a;g++)for(let y=0;y<s;y++){let $=0,S=0;for(let C=g*$t;C<Math.min(n,(g+1)*$t);C++)for(let M=y*$t;M<Math.min(r,(y+1)*$t);M++){let R=C*r+M;$+=Math.abs(t[R]-e[R]),S++}$/S>i&&(c[g*s+y]=1)}let u=new Uint8Array(s*a),d=[];for(let g=0;g<c.length;g++){if(!c[g]||u[g])continue;let y={x0:1/0,y0:1/0,x1:-1,y1:-1,cells:0},$=[g];for(u[g]=1;$.length>0;){let S=$.pop(),C=S%s,M=Math.floor(S/s);y.x0=Math.min(y.x0,C),y.y0=Math.min(y.y0,M),y.x1=Math.max(y.x1,C),y.y1=Math.max(y.y1,M),y.cells++;for(let R=-1;R<=1;R++)for(let P=-1;P<=1;P++){let j=C+P,X=M+R;if(j<0||X<0||j>=s||X>=a)continue;let D=X*s+j;c[D]&&!u[D]&&(u[D]=1,$.push(D))}}d.push(y)}let p=o.scaleX??o.scale??1,f=o.scaleY??o.scale??1,m=o.origin?.x??0,h=o.origin?.y??0,b=d.sort((g,y)=>y.cells-g.cells).slice(0,o.maxRegions??20).map(g=>{let y=g.x0*$t,$=g.y0*$t,S=Math.min(r,(g.x1+1)*$t)-y,C=Math.min(n,(g.y1+1)*$t)-$;return{x:m+Math.round(y*p),y:h+Math.round($*f),width:Math.round(S*p),height:Math.round(C*f)}}),w=c.reduce((g,y)=>g+y,0);return{meanDiff:kk(t,e),changedFraction:w/c.length,regions:b}}function eg(t,e,r){return{scaleX:t.width/e.width,scaleY:t.height/e.height,pixelThreshold:r}}var ra=class{constructor(e,r,n,o={}){this.width=r;this.height=n;this.opts=o;this.previous=e,this.anchor=e}width;height;opts;previous;anchor;push(e){let r=kt(this.previous,e,this.width,this.height,this.opts).regions,n=r.length>0?r:kt(this.anchor,e,this.width,this.height,this.opts).regions;return this.previous=e,n.length>0&&(this.anchor=e),n}};function Go(t,e){return["-v","error","-i",t,"-frames:v","1","-vf",`scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function tg(t,e,r,n){return["-v","error","-probesize","32","-analyzeduration","0","-f","gdigrab","-framerate",String(Math.round(n*1e3)/1e3),...ki(t,e),"-vf",`scale=${r.width}:${r.height}:flags=area,format=gray`,"-flush_packets","1","-f","rawvideo","-"]}function rg(t,e,r){let n=`scale=${r.width}:${r.height}:flags=area,format=gray`;return["-v","info","-i",t,"-i",e,"-lavfi",`[0]${n}[x];[1]${n}[y];[x][y]ssim`,"-frames:v","1","-f","null","-"]}function qo(t,e,r){let n=e.map(o=>`drawbox=x=${o.x}:y=${o.y}:w=${o.width}:h=${o.height}:color=red@0.9:t=3`);return["-y","-v","error","-i",t,"-frames:v","1",...n.length?["-vf",n.join(",")]:[],...Ee(r)]}function ng(t){let e=t.match(/All:([\d.]+)/);return e?Number(e[1]):null}import{tmpdir as _k}from"node:os";import{join as Tk}from"node:path";var Ak={a:Et.string().min(1).describe("Before image (or video: first frame)."),b:Et.string().min(1).describe("After image (or video); scaled to a's size."),pixelThreshold:Et.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${Ho}).`),returnImage:Et.boolean().optional().describe("Return b inline with changes outlined (default true).")};function og(t){t.registerTool("screen_diff",{title:"Screen Diff",description:"Compare two screenshots or frames: SSIM score, changed share, and changed boxes in b's pixels, to check a UI change happened only where expected.",inputSchema:Ak,outputSchema:N({identical:Et.boolean(),ssim:Et.number().nullable(),meanDiff:Et.number(),changedFraction:Et.number(),regions:Et.array(Et.unknown())}),annotations:he},async(e,r)=>{try{k();for(let p of[e.a,e.b])F(p);let[n,o]=await Promise.all([L(e.a),L(e.b)]);if(!n.width||!n.height)throw new l(`Could not read the size of ${e.a}.`);let i=na(n.width,n.height),[s,a,c]=await Promise.all([Dr(Go(e.a,i),3e4,{signal:r.signal}),Dr(Go(e.b,i),3e4,{signal:r.signal}),ne(k().ffmpeg,rg(e.a,e.b,i),3e4,{signal:r.signal})]),u=kt(s,a,i.width,i.height,{scaleX:(o.width??n.width)/i.width,scaleY:(o.height??n.height)/i.height,pixelThreshold:e.pixelThreshold}),d=[];if(e.returnImage!==!1){let p=Tk(_k(),`screencast-diff-${ge()}-${be()}.png`);try{await Z(qo(e.b,u.regions,p),3e4,{signal:r.signal}),d.push(...(await Re([p],Ae,1)).images)}finally{Ek(p,{force:!0})}}return v({identical:u.regions.length===0,ssim:ng(c.stderr),meanDiff:Number(u.meanDiff.toFixed(4)),changedFraction:Number(u.changedFraction.toFixed(4)),regions:u.regions,...o.width!==n.width||o.height!==n.height?{note:`b (${o.width}x${o.height}) was compared at a's size (${n.width}x${n.height}).`}:{}},d)}catch(n){return E(n)}})}import{z as Te}from"zod";var Rk=t=>new Promise(e=>setTimeout(e,t));async function ig(t){let e=t.now??Date.now,r=t.sleep??Rk,n=e(),o=await t.grab(),i=new ra(o,t.width,t.height,t.diff),s=n,a=!1,c=[],u="timeout";for(;e()-n<t.timeoutMs;){if(t.signal.aborted){u="cancelled";break}await r(t.intervalMs);let d=await t.grab().catch(p=>{if(t.signal.aborted)return null;throw p});if(!d){u="cancelled";break}if(t.mode==="change"){let p=kt(o,d,t.width,t.height,t.diff);if(p.regions.length>0){c=p.regions,u="changed";break}}else{let p=i.push(d);if(p.length>0)a=!0,s=e(),c=p;else if(e()-s>=t.settleMs){u="settled";break}}}return{outcome:u,regions:c,everChanged:a,startedAt:n}}var Mk=t=>new Promise(e=>setTimeout(e,t));async function sg(t){let e=t.now??Date.now,r=t.sleep??Mk,n=e(),o=0,i=[],s=async()=>(o++,i=await t.read(),t.gone?i.length===0:i.length>0),a=()=>t.grab().catch(u=>{if(t.signal.aborted)return null;throw u}),c=await a();if(!c)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};if(await s())return{outcome:"matched",matches:i,reads:o,startedAt:n};for(;e()-n<t.timeoutMs;){if(t.signal.aborted)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};await r(t.intervalMs);let u=await a();if(!u)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};if(kt(c,u,t.width,t.height,t.diff).regions.length!==0&&(c=u,await s()))return{outcome:"matched",matches:i,reads:o,startedAt:n}}return{outcome:"timeout",matches:i,reads:o,startedAt:n}}var ia=class{waiters=[];error=null;ended=!1;push(e){let r=this.waiters;this.waiters=[];for(let n of r)n.resolve(e)}fail(e){this.error===null&&(this.error=e),this.rejectAll(this.error)}end(){this.ended=!0,this.rejectAll(new l("The screen capture ended unexpectedly."))}next(e){return this.error!==null?Promise.reject(this.error):this.ended?Promise.reject(new l("The screen capture ended unexpectedly.")):new Promise((r,n)=>{let o=setTimeout(()=>{this.waiters=this.waiters.filter(s=>s!==i),n(new l(`No frame from the screen capture within ${Math.round(e/1e3)}s.`))},e),i={resolve:s=>{clearTimeout(o),r(s)},reject:s=>{clearTimeout(o),n(s)}};this.waiters.push(i)})}rejectAll(e){let r=this.waiters;this.waiters=[];for(let n of r)n.reject(e)}};import{join as sa}from"node:path";import{mkdtempSync as Ck,rmSync as Xo}from"node:fs";import{tmpdir as ag}from"node:os";var Pk={target:Te.string().describe("What to watch: full | monitor:<i> | window:<title> (or exe=/hwnd=) | region:<x>,<y>,<w>,<h>."),exactTitle:Te.boolean().optional().describe("window: targets match the whole title only (default false)."),mode:Te.enum(["change","settle","text"]).optional().describe("change (default): return once it differs from the start. settle: once it has been still for settleSec. text: once text appears (OCR, re-read only after a change)."),text:Te.string().min(1).max(jr).optional().describe("Mode text: what to wait for; tolerates OCR misreads."),regex:Te.boolean().optional().describe("Mode text: text is a regex."),gone:Te.boolean().optional().describe("Mode text: wait until it disappears instead."),backend:Te.enum(["gdigrab","wgc"]).optional().describe("wgc: watch a window even when covered (window: targets; 1-2 s per check)."),timeoutSec:Te.number().positive().max(600).optional().describe("Give up after this many seconds (default 30; a timeout is a result, not an error)."),settleSec:Te.number().positive().max(60).optional().describe("Mode settle: seconds of stillness (default 1)."),intervalMs:Te.number().int().min(100).max(5e3).optional().describe("Pause between checks in ms (default 250; 1000 with wgc)."),pixelThreshold:Te.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${Ho}).`),returnImage:Te.boolean().optional().describe("Return the final state inline (default true)."),keep:Te.boolean().optional().describe("Keep the final screenshot on disk and return its path (default false).")};function cg(t){t.registerTool("wait_for_change",{title:"Wait for Screen Change",description:"Wait until part of the screen changes, settles, or shows (or loses) some text, instead of guessing a sleep. Returns the elapsed time, changed regions (screenshot pixels; add `origin` for desktop), and the final state.",inputSchema:Pk,outputSchema:N({outcome:Te.string(),mode:Te.string(),elapsedSec:Te.number(),regions:Te.array(Te.unknown()),origin:N({x:Te.number(),y:Te.number()})}),annotations:he},async(e,r)=>{try{k();let n=e.mode??"change";if(n==="text"!=(e.text!==void 0))throw new l('Use text with mode "text", and mode "text" with text.');let o=e.backend??"gdigrab",i=(e.timeoutSec??30)*1e3,s=(e.settleSec??1)*1e3,a=e.intervalMs??(o==="wgc"?1e3:250),c=await at(e.target,{exactTitle:e.exactTitle,backend:o}),{target:u,monitors:d,window:p}=c;if(o==="wgc"&&!p?.hwnd)throw new l('backend "wgc" watches one window: use a window: target.');let f=n==="text"?`"${e.text}" ${e.gone?"disappears":"appears"}`:n==="settle"?"stops changing":"changes";await Ot(t,`Watch ${Ft(e.target,p)} for up to ${i/1e3} s, until it ${f}?`,r.signal);let m=Ck(sa(ag(),"screencast-wait-")),h=0,b=async()=>{let x=sa(m,`still-${h++}.png`);return await Nt(c,x,o),x},w=oa(u,d);if(o==="wgc")try{let x=await L(await b());if(!x.width||!x.height)throw new l("Could not read the window capture's size.");w={...p?.client??{x:w.x,y:w.y},width:x.width,height:x.height}}catch(x){throw Xo(m,{recursive:!0,force:!0}),x}let g=na(w.width,w.height),y=eg(w,g,e.pixelThreshold),$=new ia,S=new AbortController,C=o==="gdigrab"?Wi(tg(u,d,g,1e3/a),g.width*g.height,x=>$.push(x),i+6e4,{signal:AbortSignal.any([r.signal,S.signal])}).then(()=>$.end(),x=>$.fail(x)):Promise.resolve(),M=o==="gdigrab"?()=>$.next(15e3):async()=>{let x=await b();try{return await Dr(Go(x,g),3e4,{signal:r.signal})}finally{Xo(x,{force:!0})}},R=o==="gdigrab"?async()=>{}:void 0,P,j=null,X=0;try{if(n==="text"){let x=await sg({grab:M,read:async()=>{let q=await b(),[H]=await ct([q],m,r.signal);return Xo(q,{force:!0}),H?yt(H.lines,e.text,e.regex===!0):[]},width:g.width,height:g.height,diff:y,timeoutMs:i,intervalMs:a,gone:e.gone===!0,signal:r.signal,...R?{sleep:R}:{}});j={matches:x.matches,reads:x.reads},P={outcome:x.outcome,regions:x.matches.map(({x:q,y:H,width:de,height:G})=>({x:q,y:H,width:de,height:G})),startedAt:x.startedAt}}else P=await ig({grab:M,mode:n,width:g.width,height:g.height,diff:y,timeoutMs:i,settleMs:s,intervalMs:a,signal:r.signal,...R?{sleep:R}:{}});X=Date.now()}finally{S.abort(),await C,Xo(m,{recursive:!0,force:!0})}let{outcome:D,regions:ae,everChanged:ee,startedAt:J}=P,ie={outcome:D,mode:n,elapsedSec:Number(((X-J)/1e3).toFixed(2)),...n==="settle"?{changedWhileWaiting:ee}:{},...j?{text:e.text,...e.gone?{gone:!0}:{},matches:j.matches,ocrReads:j.reads}:{},regions:ae,origin:{x:w.x,y:w.y},...o==="wgc"?{backend:o}:{},...p?cr(p):{}},ce=[];if(e.returnImage!==!1&&D!=="cancelled"){let x=e.keep?sa(we("screenshots"),`wait-${ge()}-${be()}.png`):sa(ag(),`screencast-wait-${ge()}-${be()}.png`);try{o==="wgc"?await Nt(c,x,"wgc"):await Z(_i(u,x,d),6e4,{signal:r.signal}),e.keep&&(ie.screenshotPath=x),ce.push(...(await Re([x],Ae,1)).images)}finally{e.keep||Xo(x,{force:!0})}}return v(ie,ce)}catch(n){return E(n)}})}import{z as qe}from"zod";import{extname as ug,join as Nn}from"node:path";import{mkdtempSync as Ik,rmSync as Fk}from"node:fs";import{tmpdir as Ok}from"node:os";var lg=new Set([".png",".jpg",".jpeg",".bmp",".gif",".webp",".tif",".tiff"]),aa=300,Nk={target:qe.string().optional().describe("Live screen target (full | monitor:<i> | window:... | region:...), or pass input."),input:qe.string().optional().describe("Image or video file to read instead of a live target."),timestamp:qe.number().nonnegative().optional().describe("Video input: second to read (default 0)."),scanEverySec:qe.number().positive().optional().describe("Video input: scan a frame every N s across the clip (e.g. for secrets before sharing); matches and redactRegions get times. Widens to stay within maxFrames."),maxFrames:qe.number().int().min(1).max(vs).optional().describe(`scanEverySec frame cap (default ${En}; ~1 s each).`),exactTitle:qe.boolean().optional().describe("window: targets match the whole title only (default false)."),backend:qe.enum(["gdigrab","wgc"]).optional().describe("Live target: gdigrab (default) = what is visible; wgc (window:, FFmpeg 8+) = the window even if covered."),query:qe.string().optional().describe("Text to find (case-insensitive, tolerates OCR misreads like I/l, O/0, _/-). Omit to return all text."),regex:qe.boolean().optional().describe("Treat query as a regular expression (case-insensitive)."),redact:qe.boolean().optional().describe("Also return padded match rectangles ready for redact_region's regions."),keep:qe.boolean().optional().describe("Live target: keep the capture and return its path (default false: deleted after reading)."),returnImage:qe.boolean().optional().describe("Return the image with matches outlined (default: true with a query).")};function pg(t){t.registerTool("find_text",{title:"Find Text (OCR)",description:"OCR (built into Windows) on the screen, an image, or video frames, with line and match boxes in image pixels (add `origin` for desktop coordinates). Locate UI text or secrets (e.g. regex 'sk-|ghp_|api.?key') to redact. Best-effort: review results.",inputSchema:Nk,outputSchema:N({imageSize:N({width:qe.number(),height:qe.number()})}),annotations:he},async(e,r)=>{try{if(k(),e.target===void 0==(e.input===void 0))throw new l("Provide exactly one of: target (live screen) or input (a file).");let n=Ik(Nn(Ok(),"screencast-ocr-"));try{if(e.scanEverySec!==void 0)return await Dk(e,n,r.signal);let o,i={},s;if(e.target!==void 0){let h=await at(e.target,{exactTitle:e.exactTitle,backend:e.backend});o=e.keep?Nn(we("screenshots"),`ocr-${ge()}-${be()}.png`):Nn(n,"capture.png");let b=e.backend??"gdigrab";await Ot(t,`Capture ${Ft(e.target,h.window)} once to read the text on it?`,r.signal),await Nt(h,o,b),h.window&&(i=cr(h.window));let w=oa(h.target,h.monitors);s=b==="wgc"&&h.window?.client?h.window.client:{x:w.x,y:w.y}}else{F(e.input);let h=lg.has(ug(e.input).toLowerCase());o=Nn(n,"frame.png"),await Z(["-y","-v","error",...h?[]:["-ss",String(e.timestamp??0)],"-i",e.input,"-frames:v","1",...Ee(o)],6e4,{signal:r.signal})}let[a]=await ct([o],n,r.signal);if(!a)throw new l("Could not read the frame.");let{lines:c,width:u,height:d}=a,p=e.query?yt(c,e.query,e.regex===!0):[],f=[];if(e.returnImage??!!e.query){let h=Nn(n,"shown.png");await Z(qo(o,p,h),3e4,{signal:r.signal}),f.push(...(await Re([h],Ae,1)).images)}return v({...e.target!==void 0?e.keep?{screenshotPath:o}:{}:{input:e.input},imageSize:{width:u,height:d},...s?{origin:s}:{},...e.query?{query:e.query,matchCount:p.length,matches:p,...e.redact?{redactRegions:xs(p,{width:u,height:d})}:{}}:{},text:c.map(h=>h.text).join(`
330
- `),lines:c.slice(0,aa).map(({words:h,...b})=>b),...c.length>aa?{linesTruncated:c.length-aa}:{},...i,note:"OCR is best-effort: small or stylised text can be missed. Review before relying on it, especially for redaction."},f)}finally{Fk(n,{recursive:!0,force:!0})}}catch(n){return E(n)}})}async function Dk(t,e,r){if(t.input===void 0)throw new l("scanEverySec reads a video file: pass input, not target.");if(F(t.input),lg.has(ug(t.input).toLowerCase()))throw new l("scanEverySec is for a video input; an image has one frame, so drop scanEverySec.");let n=t.maxFrames??En,o=await Ss(t.input,{everySec:t.scanEverySec,maxFrames:n},e,r),{step:i}=o,[s]=o.frames;if(!s)throw new l("Could not read any frames from the video.");let a=new Set;for(let h of o.frames)for(let b of h.lines)a.add(b.text);let{matches:c,redactRegions:u}=t.query?kn(o,t.query,t.regex===!0):{matches:[],redactRegions:[]},d=[],p=c[0],f=p&&o.frames.find(h=>h.t===p.t)?.path;if((t.returnImage??!!t.query)&&p&&f){let h=Nn(e,"shown.png");await Z(qo(f,c.filter(b=>b.t===p.t),h),3e4,{signal:r}),d.push(...(await Re([h],Ae,1)).images)}let m=[...a].join(`
331
- `);return v({input:t.input,imageSize:{width:s.width,height:s.height},scan:{everySec:Math.round(i*1e3)/1e3,framesScanned:o.frames.length,...o.clamped?{note:`Widened from ${t.scanEverySec} s to fit maxFrames ${n}.`}:{}},...t.query?{query:t.query,matchCount:c.length,matches:c.slice(0,aa),...t.redact?{redactRegions:u}:{}}:{},text:m.length>2e4?`${m.slice(0,2e4)}...`:m,note:"OCR is best-effort and reads only the sampled frames: text shown briefly between samples, or small or stylised text, can be missed. Review before sharing, especially for redaction."},d)}import{z as yr}from"zod";import{dirname as Hk,join as Hu}from"node:path";import{existsSync as Dn,mkdirSync as Gk,mkdtempSync as qk,readFileSync as Ln,readdirSync as Xk,rmSync as qu}from"node:fs";import{tmpdir as Jk}from"node:os";import{spawnSync as Lk}from"node:child_process";import{isAbsolute as Bk}from"node:path";var Hr=8;function ca(t){let e=/^ff(?:mpeg|probe) version (\S+)/m.exec(t)?.[1]??null,r=e?/^n?(\d+)\.\d+/.exec(e):null;if(r)return{version:e,major:Number(r[1]),inferred:!1};let n=/^\s*libavutil\s+(\d+)\./m.exec(t);return n&&Number(n[1])>=56?{version:e,major:Number(n[1])-52,inferred:!0}:{version:e,major:null,inferred:!1}}function dg(t){let e=new Set,r=t.split(/^\s*---\s*$/m).slice(1).join(`
332
- `)||t;for(let n of r.split(/\r?\n/)){let o=/^\s{0,2}[D ][E ]\s?[d ]?\s+([a-z0-9_,]+)\s/i.exec(n);if(o?.[1])for(let i of o[1].split(","))e.add(i)}return[...e]}function zu(t,e){try{let r=Lk(t,e,{encoding:"utf8",windowsHide:!0,timeout:1e4});return r.status!==0?null:`${r.stdout??""}${r.stderr??""}`}catch{return null}}function ua(t){return zu(t,["-version"])}function mg(t){return zu(t,["-hide_banner","-devices"])}function fg(t){return Bk(t)?t:zu(process.platform==="win32"?"where":"which",[t])?.split(/\r?\n/).map(r=>r.trim()).find(r=>r.length>0)??null}var Wk=`
329
+ `)}})}function Oh(t,e){return t.replace(/\.srt$/i,"")+`.${e}.srt`}var fk=new Set([".mp4",".mkv",".mov"]),hk=12,gk={input:ve.string().min(1).optional().describe("Path to the video."),sessionId:ve.string().min(1).optional().describe("Or a stopped recording's id."),from:ve.enum(["markers","scenes","transcript"]).optional().describe("markers (default; add_marker, else the file's chapters), scenes (screen changes), or transcript (SRT sections)."),chapters:ve.array(ve.object({start:ve.number().min(0),title:ve.string().min(1).max(100)})).min(1).max(200).optional().describe("Or explicit { start, title } chapters."),transcript:ve.string().optional().describe("The .srt for from: transcript."),minChapterSec:ve.number().min(0).optional().describe(`Shortest chapter (default 1; scenes ${En}, transcript 30).`),subtitles:ve.string().optional().describe("Also mux this .srt/.vtt/.ass as a soft subtitle track."),subtitleLanguage:ve.string().regex(/^[a-z]{3}$/).optional().describe('ISO 639-2, e.g. "eng".'),subtitleTracks:ve.array(ve.object({file:ve.string().min(1),language:ve.string().regex(/^[a-z]{3}$/).optional(),title:ve.string().max(60).optional(),default:ve.boolean().optional()})).min(1).max(us).optional().describe("Or several tracks, e.g. one per language (translate_subtitles makes them)."),textOnly:ve.boolean().optional().describe("Return chapters and YouTube text only; write no file."),output:ve.string().optional().describe("Optional .mp4/.mkv/.mov path. Defaults under SCREENCAST_HOME/edits."),overwrite:ve.boolean().optional().describe("Allow replacing an existing output file.")};function Dh(t){t.registerTool("chapters",{title:"Chapters",description:"Write chapters (markers, scene changes, transcript, or a list) into an mp4/mkv/mov copy without re-encoding; returns YouTube chapter text. Can mux an SRT as soft subtitles.",inputSchema:gk,outputSchema:B({chapters:ve.array(B({start:ve.number(),end:ve.number(),title:ve.string()})),youtube:ve.string()}),annotations:I},async(e,r)=>{try{k();let n=e.input,o;if(e.sessionId){let y=oe().get(e.sessionId);if(!y)throw new l(`No session with id "${e.sessionId}".`);if(y.status==="recording"||y.status==="paused")throw new l("The recording is still running; stop it first.");n??=y.outputPath,o=y.markers}if(!n)throw new l("Pass input or sessionId.");if(O(n),e.subtitles&&e.subtitleTracks)throw new l("Pass subtitles or subtitleTracks, not both.");let i=e.subtitleTracks??(e.subtitles?[{file:e.subtitles,...e.subtitleLanguage?{language:e.subtitleLanguage}:{}}]:[]);for(let y of[e.transcript,...i.map(v=>v.file)])if(y!==void 0&&!ck(y))throw new l(`File not found: ${y}`);for(let y of i)if(!/\.(srt|vtt|ass|ssa)$/i.test(y.file))throw new l(`Subtitles must be .srt, .vtt, or .ass files, not ${y.file}.`);let a=(await W(n)).durationSec;if(!a||a<=0)throw new l(`Could not read the duration of ${n}.`);let c=e.chapters?"list":e.from??"markers",u,d=1,p=c;if(e.chapters)u=e.chapters;else if(c==="scenes"){d=En;let{ffmpeg:y}=k(),v=await se(y,ir(n,wt),pe(a),{signal:r.signal});if(v.code!==0)throw new l(`Scene scan failed (exit ${v.code}): ${v.stderr.trim().slice(-400)}`);u=Im(sr(v.stdout),e.minChapterSec??d,hk)}else if(c==="transcript"){if(!e.transcript)throw new l("from: transcript needs transcript (an .srt path).");if(d=30,u=Fm(Ue(lk(e.transcript,"utf8")),{minChapterSec:e.minChapterSec??d}),u.length===0)throw new l(`No cues in ${e.transcript}.`)}else{let y=o??[];if(y.length===0){let v=await gr(n,r.signal);y=v.markers,v.from==="chapters"&&(p="embedded chapters")}if(y.length===0)throw new l(`No markers for ${n}.`,"Add some with add_marker, or use from: scenes / transcript, or pass chapters.");u=ms(y)}let f=ps(u,a,{minChapterSec:e.minChapterSec??d});if(f.length===0)throw new l("No chapter falls inside the video.");let m=Pm(f,a),h={source:p,chapters:f,youtube:m.text,...m.issues.length>0?{youtubeIssues:m.issues}:{}};if(e.textOnly)return S(h);let b=e.output?ak(e.output).toLowerCase():Z(n);if(!fk.has(b))throw new l(`Chapters can be written to .mp4, .mkv, or .mov, not ${b||"a file without an extension"}.`);let w=j(e.output,"chapters",b,{overwrite:e.overwrite,anyContainer:!0}),g=uk(Nh(mk(),"screencast-chapters-"));try{let y=Nh(g,"chapters.txt");dk(y,ds(f)),await U(Om(n,y,w,{container:b,subtitles:i}),{output:w,durationSec:a,extra:r})}finally{pk(g,{recursive:!0,force:!0})}return S({outputPath:w,...h,...e.subtitles?{subtitleTrack:{...i[0],codec:b===".mkv"?"copy":"mov_text"}}:{},...e.subtitleTracks?{subtitleTracks:i.map(y=>({...y,codec:b===".mkv"?"copy":"mov_text"}))}:{}})}catch(n){return E(n)}})}import{z as dt}from"zod";import{existsSync as yk,readFileSync as Jh,rmSync as xk}from"node:fs";var zo="ui://screencast/player",Qs="text/html;profile=mcp-app",Bh={ui:{resourceUri:zo},"ui/resourceUri":zo},Lh="io.modelcontextprotocol/ui";function Wh(t){let e=t,r=e?.extensions?.[Lh]??e?.experimental?.[Lh];return!r||typeof r!="object"?!1:!Array.isArray(r.mimeTypes)||r.mimeTypes.includes(Qs)}var Zs=120,jh=300,bk=4,Uu=640,wk=.01;function Uh(t,e=Zs){if(!(t>0))throw new l("The video has no duration to review.");let r=Math.max(1,Math.min(e,Math.ceil(t*bk))),n=Number((t/r).toFixed(6));return{count:r,intervalSec:n,sceneGapSec:Number(Math.max(.25,n/4).toFixed(6))}}function zh(t,e,r,n,o=wk){let i=e.intervalSec,s=`isnan(prev_t)+gt(floor((t-start_t)/${i})\\,floor((prev_t-start_t)/${i}))`,a=`gt(scene\\,${o})*not(${s})*(isnan(prev_selected_t)+gte(t-prev_selected_t\\,${e.sceneGapSec}))`;return["-v","error","-i",t,"-an","-vf",`scale='min(${r},iw)':-2,split[g][s];[g]select='${s}',metadata=add:key=kind:value=grid[g1];[s]select='${a}',metadata=add:key=kind:value=scene[s1];[g1][s1]interleave,metadata=print:file=${ye(n)}`,"-fps_mode","passthrough","-q:v","6","-f","image2pipe","-c:v","mjpeg","-"]}function Hh(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.match(/pts_time:\s*(-?[\d.]+)/);if(n){e.push({timeSec:Number(n[1]),scene:!1,score:0});continue}let o=e.at(-1);if(!o)continue;r==="kind=scene"&&(o.scene=!0);let i=r.match(/^lavfi\.scene_score=([\d.]+)/);i&&(o.score=Number(i[1]))}return e}function Gh(t,e){let r=t.map((o,i)=>({f:o,i})).filter(o=>o.f.scene).sort((o,i)=>i.f.score-o.f.score).slice(0,Math.max(0,e)),n=new Set(r.map(o=>o.i));return t.flatMap((o,i)=>!o.scene||n.has(i)?[i]:[])}function qh(t){let e=[],r=-1;for(let n=0;n+1<t.length;n++){if(t[n]!==255)continue;let o=t[n+1];o===216&&r<0?r=n:o===217&&r>=0&&(e.push(t.subarray(r,n+2)),r=-1,n++)}return e}var Xh=t=>Jh(_n("ui",t),"utf8");function Sk(){let t=Xh("player.js");if(/<\/script/i.test(t))throw new l("player.js must not contain a closing script tag.");return Xh("player.html").replace('<script src="player.js"></script>',()=>`<script>
330
+ ${t}</script>`)}function vk(t){if(t.sessionId){let e=oe().get(t.sessionId);if(!e)throw new l(`No session with id "${t.sessionId}".`);if(e.status==="recording"||e.status==="paused")throw new l("The recording is still running; stop it first.");return e.outputPath}if(t.input)return t.input;throw new l("Pass input or sessionId.")}function $k(t){return t&&t.length>0?{markers:t.map(({t:e,label:r})=>({t:e,label:r}))}:{}}function Yh(t){t.registerResource("review-player",zo,{title:"Recording review player",description:"Interactive player: scrub, trim, and draw redaction boxes on a recording.",mimeType:Qs},async()=>({contents:[{uri:zo,mimeType:Qs,text:Sk(),_meta:{ui:{prefersBorder:!0}}}]})),t.registerTool("review_recording",{title:"Review Recording",description:"Open a recording for a person to review: in MCP Apps clients an inline player to scrub, trim, and redact, then export; elsewhere just the video's details.",inputSchema:{input:dt.string().optional().describe("Path to the video."),sessionId:dt.string().optional().describe("Or the session id of a stopped recording.")},outputSchema:B({input:dt.string(),durationSec:dt.number().nullable(),width:dt.number().nullable(),height:dt.number().nullable(),fps:dt.number().nullable(),hasAudio:dt.boolean()}),annotations:fe,_meta:Bh},async n=>{try{k();let o=vk(n);O(o);let i=await W(o);return S({input:o,durationSec:i.durationSec,width:i.width,height:i.height,fps:i.fps,hasAudio:i.audioCodec!==null,...$k(n.sessionId?oe().get(n.sessionId)?.markers??We(o):We(o)),note:"Clients with MCP Apps show an inline review player for this result. Without it, look with contact_sheet or sample_frames, then trim and redact with pipeline."})}catch(o){return E(o)}});let e=t.registerTool("player_frames",{title:"Player Frames",description:"Preview frames for the review player: JPEGs on an even grid over the video plus frames at scene changes, with their real times. Used by the inline player; agents should use sample_frames or contact_sheet instead.",inputSchema:{input:dt.string().min(1).describe("Path to the video."),maxFrames:dt.number().int().min(1).max(jh).optional().describe(`Frames on the even grid (default ${Zs}); scene-change frames come on top, up to as many again.`),width:dt.number().int().min(64).max(1280).optional().describe(`Frame width (default ${Uu}).`)},annotations:fe,_meta:{ui:{visibility:["app"]}}},async(n,o)=>{try{k(),O(n.input);let i=await W(n.input),s=i.durationSec??0,a=Uh(s,n.maxFrames??Zs),c=He(".txt"),u,d;try{let g=await Ur(zh(n.input,a,n.width??Uu,c),pe(s),{signal:o.signal});u=qh(g),d=Hh(yk(c)?Jh(c,"utf8"):"").slice(0,u.length)}finally{xk(c,{force:!0})}let[p]=d;if(!p)throw new l("ffmpeg returned no preview frames.");let f=Gh(d,a.count).flatMap(g=>{let y=d[g],v=u[g];return y&&v?[{frame:y,jpeg:v}]:[]}),m=p.timeSec,h=[];try{h=(await gr(n.input,o.signal)).markers.map(({t:g,label:y})=>({t:g,label:y}))}catch{}let b=f.map(({frame:g})=>Math.round((g.timeSec-m)*1e3)/1e3),w=f.flatMap(({frame:g},y)=>g.scene?[y]:[]);return{content:[{type:"text",text:JSON.stringify({input:n.input,durationSec:s,width:i.width,height:i.height,hasAudio:i.audioCodec!==null,frameTimes:b,intervalSec:a.intervalSec,sceneFrames:w,markers:h})},...f.map(({jpeg:g})=>({type:"image",data:g.toString("base64"),mimeType:"image/jpeg"}))]}}catch(i){return E(i)}});e.disable();let r=t.server.oninitialized;t.server.oninitialized=()=>{r?.(),Wh(t.server.getClientCapabilities())&&e.enable()}}import{z as mt}from"zod";import{readFileSync as kk,rmSync as Ek}from"node:fs";var Me=1280,ea=8,Ho=20;function _k(t,e,r){if(!Number.isInteger(r)||r<16)throw new l("maxImageWidth must be an integer of at least 16.");return["-y","-v","error","-i",t,"-frames:v","1","-vf",`scale='min(${r},iw)':-2`,"-q:v","4",...Te(e)]}function ta(t){return Math.max(0,Math.min(Ho,Math.floor(t??ea)))}async function Ce(t,e=Me,r=ea){let n=t.slice(0,r);return{images:await qe(n,async i=>{let s=He(".jpg");try{return await te(_k(i,s,e),3e4),{type:"image",data:kk(s).toString("base64"),mimeType:"image/jpeg"}}finally{Ek(s,{force:!0})}}),omitted:t.length-n.length}}var Tk={target:mt.string().describe("full | monitor:<i> (0 = primary) | window:<title> (or window:exe=<app.exe> / window:hwnd=<n>) | region:<x>,<y>,<w>,<h>. Titles match exactly, else as a substring; topmost wins."),exactTitle:mt.boolean().optional().describe("window: targets match the whole title only, never a substring (default false)."),backend:mt.enum(["gdigrab","wgc"]).optional().describe("gdigrab (default, ~0.2 s): what is visible. wgc (window:, FFmpeg 8+, ~1-2 s): the window even if covered."),output:mt.string().optional().describe("Optional output .png path. Defaults to a file under SCREENCAST_HOME/screenshots."),overwrite:mt.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),returnImage:mt.boolean().optional().describe("Return the image inline (default true; the PNG on disk stays full size)."),maxImageWidth:mt.number().int().min(16).optional().describe(`Max inline image width (default ${Me}).`)};function Kh(t){t.registerTool("screenshot",{title:"Take Screenshot",description:"Capture one PNG of the screen, a monitor, a window, or a region, returned inline and by path.",inputSchema:Tk,outputSchema:B({outputPath:mt.string(),target:mt.string(),backend:mt.string(),inlineImages:mt.number().int()}),annotations:I},async(e,r)=>{try{k();let n=await ut(e.target,{exactTitle:e.exactTitle,backend:e.backend}),{window:o}=n,i=j(e.output,"shot",".png",{overwrite:e.overwrite,dir:"screenshots",anyContainer:!0}),s=e.backend??"gdigrab";await Dt(t,`Take a screenshot of ${Nt(e.target,o)}, saved to ${i}?`,r.signal),await Lt(n,i,s);let a=e.returnImage===!1?[]:(await Ce([i],e.maxImageWidth??Me,1)).images;return S({outputPath:i,target:e.target,backend:s,...o?pr(o):{},inlineImages:a.length},a)}catch(n){return E(n)}})}import{z as Fe}from"zod";import{join as zu}from"node:path";import{mkdirSync as Rk,readdirSync as Vh,existsSync as Ak,rmSync as Mk}from"node:fs";var Ck={input:Fe.string().min(1).describe("Path to the source video file."),mode:Fe.enum(["fps","timestamps","scenes"]).optional().describe("scenes: only frames where the screen changed (strongest first), usually the cheapest review. Default: fps or timestamps, whichever is given."),fps:Fe.number().positive().optional().describe("Frames per second (mode fps)."),timestamps:Fe.array(Fe.number().nonnegative()).optional().describe("Seconds to grab a frame at (mode timestamps)."),sceneThreshold:Fe.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed to count, 0-1 (default ${wt}).`),dedupe:Fe.boolean().optional().describe("Mode fps: drop near-duplicate frames (default false)."),outputDir:Fe.string().optional().describe("Optional folder for the frames (a relative path resolves under SCREENCAST_HOME/frames). Defaults to SCREENCAST_HOME/frames/<id>."),maxFrames:Fe.number().int().min(1).max(Ec).optional().describe(`Frame cap (default ${Mi}); fps is lowered to fit while still spanning the video.`),returnImages:Fe.boolean().optional().describe("Return the first maxInlineImages frames inline (default true)."),maxInlineImages:Fe.number().int().min(0).max(Ho).optional().describe(`Frames to embed inline (default ${ea}); all are listed by path.`),maxImageWidth:Fe.number().int().min(16).optional().describe(`Max inline image width (default ${Me}).`)};function Qh(t){t.registerTool("sample_frames",{title:"Sample Frames",description:"Sample PNG frames from a video (by fps, timestamps, or scene changes) and return the first few inline so the model can see what happened.",inputSchema:Ck,outputSchema:B({frameDir:Fe.string(),frameCount:Fe.number().int(),frames:Fe.array(Fe.string()),mode:Fe.string()}),annotations:fe},async(e,r)=>{try{k(),O(e.input);let n=e.fps!==void 0,o=e.timestamps!==void 0&&e.timestamps.length>0,i=e.mode??(o?"timestamps":"fps");if(!(i==="scenes"?!n&&!o:i==="fps"?n&&!o:o&&!n))throw new l("Use exactly one way to pick frames: fps (fixed rate), timestamps (explicit offsets), or mode: 'scenes' (with neither fps nor timestamps).");let a=e.maxFrames??Mi;if(o&&e.timestamps.length>a)throw new l(`${e.timestamps.length} timestamps exceeds maxFrames (${a}). Pass fewer timestamps, or raise maxFrames (up to ${Ec}).`);let c=i==="timestamps"?null:(await W(e.input)).durationSec,u=i==="fps"?Ci(c,e.fps,a):null,d=null,p=[];if(i==="scenes"){let{ffmpeg:w}=k(),g=await se(w,ir(e.input,e.sceneThreshold??wt),pe(c),{signal:r.signal});if(g.code!==0)throw new l(`Scene scan failed (exit ${g.code}): ${g.stderr.trim().slice(-400)}`);d=sr(g.stdout),p=bn(d,a)}let f=fn(e.outputDir,we("frames"))??zu(we("frames"),`sample-${he()}-${ge()}`);Rk(f,{recursive:!0});let m=[],h=[];if(u){let w=x=>x.endsWith(".png"),g=new Set(Vh(f).filter(w)),y=_p(g,`${he()}-${ge()}`),v=mn(f,`${y}%05d.png`);await te(Pi(e.input,u.fps,v,a,e.dedupe===!0),pe(c),{signal:r.signal}),m=Vh(f).filter(x=>w(x)&&x.startsWith(y)&&!g.has(x)).sort().map(x=>zu(f,x))}else{let w=i==="scenes"?p:e.timestamps,g=await qe(w,async(y,v)=>{let x=zu(f,`frame_${String(v).padStart(3,"0")}_${y}s.png`);return Mk(x,{force:!0}),await te(wn(e.input,y,x),6e4,{signal:r.signal}),x});for(let[y,v]of g.entries())Ak(v)?m.push(v):h.push(w[y])}let b=e.returnImages===!1?{images:[],omitted:0}:await Ce(m,e.maxImageWidth??Me,ta(e.maxInlineImages));return S({frameDir:f,frameCount:m.length,frames:m,mode:u?`fps=${u.fps}${e.dedupe?" (deduped)":""}`:d?`scenes (threshold ${e.sceneThreshold??wt})`:`timestamps=[${e.timestamps.join(", ")}]`,...d?{frameTimes:p,sceneChangesFound:d.length,...d.length+1>a?{capNote:`Found ${d.length} scene changes; kept the opening frame and the ${a-1} strongest (maxFrames ${a}). Raise sceneThreshold to keep only bigger changes, or raise maxFrames.`}:{}}:{},...u?.clamped?{requestedFps:e.fps,capNote:`fps=${e.fps} would write about ${u.requestedFrames} frames, over maxFrames (${a}); sampled at fps=${u.fps} instead so the frames still span the whole video. Raise maxFrames or use timestamps for more detail.`}:{},...u&&!u.clamped&&m.length>=a?{capNote:`Stopped at maxFrames (${a}); the video's length could not be probed in advance.`}:{},inlineImages:b.images.length,...b.omitted>0?{inlineNote:`Embedded the first ${b.images.length} of ${m.length} frames inline; the other ${b.omitted} are on disk at the listed paths.`}:{},...h.length>0?{skippedTimestamps:h,note:`No frame was written for ${h.length} timestamp(s) past the end of the video: [${h.join(", ")}].`}:{}},b.images)}catch(n){return E(n)}})}import{z as Ze}from"zod";var Pk={input:Ze.string().min(1).describe("Path to the source video."),count:Ze.number().int().min(1).max(Mf).optional().describe(`Frames to tile (default ${No}).`),mode:Ze.enum(["even","scenes"]).optional().describe("even (default) or scenes (strongest changes; static stretches take no tiles)."),sceneThreshold:Ze.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed, 0-1 (default ${wt}).`),columns:Ze.number().int().min(1).max(12).optional().describe("Tiles per row (default: roughly square)."),tileWidth:Ze.number().int().min(64).max(1920).optional().describe(`Tile width in px (default ${Do}).`),poster:Ze.boolean().optional().describe("Write one representative poster frame instead of a sheet."),output:Ze.string().optional().describe("Optional output .png path. Defaults under SCREENCAST_HOME/frames."),overwrite:Ze.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),returnImage:Ze.boolean().optional().describe("Return the sheet inline (default true)."),maxImageWidth:Ze.number().int().min(16).optional().describe(`Max inline image width (default ${Me}).`)};function Zh(t){t.registerTool("contact_sheet",{title:"Contact Sheet",description:"Tile timestamped frames of a video into one image to see a whole recording at a glance (the cheapest first look).",inputSchema:Pk,outputSchema:B({outputPath:Ze.string(),inlineImages:Ze.number().int()}),annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();O(e.input);let{durationSec:o}=await W(e.input);if(o===null)throw new l(`Could not read duration of ${e.input}.`);let i=e.poster?"poster":"sheet",s=nr(e.output,we("frames"),`${i}-${he()}-${ge()}.png`,e.overwrite),a=e.tileWidth??Do,c;if(e.poster)await te(Cf(e.input,o,s,Math.max(a,1280)),pe(o),{signal:r.signal}),c={outputPath:s,poster:!0};else{let d=e.count??No,p;if(e.mode==="scenes"){let m=await se(n,ir(e.input,e.sceneThreshold??wt),pe(o),{signal:r.signal});if(m.code!==0)throw new l(`Scene scan failed (exit ${m.code}): ${m.stderr.trim().slice(-400)}`);p=bn(sr(m.stdout),d)}else p=Ms(o,d);let f=await Cs(e.input,p,s,{tileWidth:a,columns:e.columns},r.signal);c={outputPath:s,mode:e.mode??"even",frameTimes:p,columns:f.columns,rows:f.rows}}let u=e.returnImage===!1?[]:(await Ce([s],e.maxImageWidth??Me,1)).images;return S({...c,inlineImages:u.length},u)}catch(n){return E(n)}})}import{z as Rt}from"zod";import{rmSync as Nk}from"node:fs";var eg=320,Ik=4,Fk=1600,_t=8,Go=12;function tg(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(eg,t),n=Math.max(2,Math.round(e*r/t/2)*2);return{width:Math.max(2,Math.round(r/2)*2),height:n}}function na(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(t,Math.max(eg,Math.min(Fk,Math.ceil(t/Ik)))),n=Math.max(2,Math.round(e*r/t/2)*2);return{width:Math.max(2,Math.round(r/2)*2),height:n}}function oa(t,e){switch(t.kind){case"region":return{x:t.x,y:t.y,width:t.w,height:t.h};case"monitor":{let r=e.find(n=>n.index===t.index);if(!r)throw new l(`No monitor ${t.index}.`);return{x:r.x,y:r.y,width:r.width,height:r.height}}case"full":{if(e.length===0)throw new l("No monitors found.");let r=Math.min(...e.map(s=>s.x)),n=Math.min(...e.map(s=>s.y)),o=Math.max(...e.map(s=>s.x+s.width)),i=Math.max(...e.map(s=>s.y+s.height));return{x:r,y:n,width:o-r,height:i-n}}default:throw new l("Internal: resolve window targets to a region first.")}}function Ok(t,e){if(t.length!==e.length||t.length===0)throw new l("Frames differ in size.");let r=0;for(let n=0;n<t.length;n++)r+=Math.abs(t[n]-e[n]);return r/t.length/255}function Tt(t,e,r,n,o={}){if(t.length!==r*n||e.length!==r*n)throw new l("Frame size does not match its dimensions.");let i=o.pixelThreshold??Go,s=Math.ceil(r/_t),a=Math.ceil(n/_t),c=new Uint8Array(s*a);for(let g=0;g<a;g++)for(let y=0;y<s;y++){let v=0,x=0;for(let R=g*_t;R<Math.min(n,(g+1)*_t);R++)for(let T=y*_t;T<Math.min(r,(y+1)*_t);T++){let M=R*r+T;v+=Math.abs(t[M]-e[M]),x++}v/x>i&&(c[g*s+y]=1)}let u=new Uint8Array(s*a),d=[];for(let g=0;g<c.length;g++){if(!c[g]||u[g])continue;let y={x0:1/0,y0:1/0,x1:-1,y1:-1,cells:0},v=[g];for(u[g]=1;v.length>0;){let x=v.pop(),R=x%s,T=Math.floor(x/s);y.x0=Math.min(y.x0,R),y.y0=Math.min(y.y0,T),y.x1=Math.max(y.x1,R),y.y1=Math.max(y.y1,T),y.cells++;for(let M=-1;M<=1;M++)for(let H=-1;H<=1;H++){let G=R+H,L=T+M;if(G<0||L<0||G>=s||L>=a)continue;let C=L*s+G;c[C]&&!u[C]&&(u[C]=1,v.push(C))}}d.push(y)}let p=o.scaleX??o.scale??1,f=o.scaleY??o.scale??1,m=o.origin?.x??0,h=o.origin?.y??0,b=d.sort((g,y)=>y.cells-g.cells).slice(0,o.maxRegions??20).map(g=>{let y=g.x0*_t,v=g.y0*_t,x=Math.min(r,(g.x1+1)*_t)-y,R=Math.min(n,(g.y1+1)*_t)-v;return{x:m+Math.round(y*p),y:h+Math.round(v*f),width:Math.round(x*p),height:Math.round(R*f)}}),w=c.reduce((g,y)=>g+y,0);return{meanDiff:Ok(t,e),changedFraction:w/c.length,regions:b}}function rg(t,e,r){return{scaleX:t.width/e.width,scaleY:t.height/e.height,pixelThreshold:r}}var ra=class{constructor(e,r,n,o={}){this.width=r;this.height=n;this.opts=o;this.previous=e,this.anchor=e}width;height;opts;previous;anchor;push(e){let r=Tt(this.previous,e,this.width,this.height,this.opts).regions,n=r.length>0?r:Tt(this.anchor,e,this.width,this.height,this.opts).regions;return this.previous=e,n.length>0&&(this.anchor=e),n}};function qo(t,e){return["-v","error","-i",t,"-frames:v","1","-vf",`scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function ng(t,e,r,n){return["-v","error","-probesize","32","-analyzeduration","0","-f","gdigrab","-framerate",String(Math.round(n*1e3)/1e3),...Ei(t,e),"-vf",`scale=${r.width}:${r.height}:flags=area,format=gray`,"-flush_packets","1","-f","rawvideo","-"]}function og(t,e,r){let n=`scale=${r.width}:${r.height}:flags=area,format=gray`;return["-v","info","-i",t,"-i",e,"-lavfi",`[0]${n}[x];[1]${n}[y];[x][y]ssim`,"-frames:v","1","-f","null","-"]}function Xo(t,e,r){let n=e.map(o=>`drawbox=x=${o.x}:y=${o.y}:w=${o.width}:h=${o.height}:color=red@0.9:t=3`);return["-y","-v","error","-i",t,"-frames:v","1",...n.length?["-vf",n.join(",")]:[],...Te(r)]}function ig(t){let e=t.match(/All:([\d.]+)/);return e?Number(e[1]):null}import{tmpdir as Dk}from"node:os";import{join as Lk}from"node:path";var Bk={a:Rt.string().min(1).describe("Before image (or video: first frame)."),b:Rt.string().min(1).describe("After image (or video); scaled to a's size."),pixelThreshold:Rt.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${Go}).`),returnImage:Rt.boolean().optional().describe("Return b inline with changes outlined (default true).")};function sg(t){t.registerTool("screen_diff",{title:"Screen Diff",description:"Compare two screenshots or frames: SSIM score, changed share, and changed boxes in b's pixels, to check a UI change happened only where expected.",inputSchema:Bk,outputSchema:B({identical:Rt.boolean(),ssim:Rt.number().nullable(),meanDiff:Rt.number(),changedFraction:Rt.number(),regions:Rt.array(Rt.unknown())}),annotations:fe},async(e,r)=>{try{k();for(let p of[e.a,e.b])O(p);let[n,o]=await Promise.all([W(e.a),W(e.b)]);if(!n.width||!n.height)throw new l(`Could not read the size of ${e.a}.`);let i=na(n.width,n.height),[s,a,c]=await Promise.all([Ur(qo(e.a,i),3e4,{signal:r.signal}),Ur(qo(e.b,i),3e4,{signal:r.signal}),se(k().ffmpeg,og(e.a,e.b,i),3e4,{signal:r.signal})]),u=Tt(s,a,i.width,i.height,{scaleX:(o.width??n.width)/i.width,scaleY:(o.height??n.height)/i.height,pixelThreshold:e.pixelThreshold}),d=[];if(e.returnImage!==!1){let p=Lk(Dk(),`screencast-diff-${he()}-${ge()}.png`);try{await te(Xo(e.b,u.regions,p),3e4,{signal:r.signal}),d.push(...(await Ce([p],Me,1)).images)}finally{Nk(p,{force:!0})}}return S({identical:u.regions.length===0,ssim:ig(c.stderr),meanDiff:Number(u.meanDiff.toFixed(4)),changedFraction:Number(u.changedFraction.toFixed(4)),regions:u.regions,...o.width!==n.width||o.height!==n.height?{note:`b (${o.width}x${o.height}) was compared at a's size (${n.width}x${n.height}).`}:{}},d)}catch(n){return E(n)}})}import{z as Ae}from"zod";var Wk=t=>new Promise(e=>setTimeout(e,t));async function ag(t){let e=t.now??Date.now,r=t.sleep??Wk,n=e(),o=await t.grab(),i=new ra(o,t.width,t.height,t.diff),s=n,a=!1,c=[],u="timeout";for(;e()-n<t.timeoutMs;){if(t.signal.aborted){u="cancelled";break}await r(t.intervalMs);let d=await t.grab().catch(p=>{if(t.signal.aborted)return null;throw p});if(!d){u="cancelled";break}if(t.mode==="change"){let p=Tt(o,d,t.width,t.height,t.diff);if(p.regions.length>0){c=p.regions,u="changed";break}}else{let p=i.push(d);if(p.length>0)a=!0,s=e(),c=p;else if(e()-s>=t.settleMs){u="settled";break}}}return{outcome:u,regions:c,everChanged:a,startedAt:n}}var jk=t=>new Promise(e=>setTimeout(e,t));async function cg(t){let e=t.now??Date.now,r=t.sleep??jk,n=e(),o=0,i=[],s=async()=>(o++,i=await t.read(),t.gone?i.length===0:i.length>0),a=()=>t.grab().catch(u=>{if(t.signal.aborted)return null;throw u}),c=await a();if(!c)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};if(await s())return{outcome:"matched",matches:i,reads:o,startedAt:n};for(;e()-n<t.timeoutMs;){if(t.signal.aborted)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};await r(t.intervalMs);let u=await a();if(!u)return{outcome:"cancelled",matches:i,reads:o,startedAt:n};if(Tt(c,u,t.width,t.height,t.diff).regions.length!==0&&(c=u,await s()))return{outcome:"matched",matches:i,reads:o,startedAt:n}}return{outcome:"timeout",matches:i,reads:o,startedAt:n}}var ia=class{waiters=[];error=null;ended=!1;push(e){let r=this.waiters;this.waiters=[];for(let n of r)n.resolve(e)}fail(e){this.error===null&&(this.error=e),this.rejectAll(this.error)}end(){this.ended=!0,this.rejectAll(new l("The screen capture ended unexpectedly."))}next(e){return this.error!==null?Promise.reject(this.error):this.ended?Promise.reject(new l("The screen capture ended unexpectedly.")):new Promise((r,n)=>{let o=setTimeout(()=>{this.waiters=this.waiters.filter(s=>s!==i),n(new l(`No frame from the screen capture within ${Math.round(e/1e3)}s.`))},e),i={resolve:s=>{clearTimeout(o),r(s)},reject:s=>{clearTimeout(o),n(s)}};this.waiters.push(i)})}rejectAll(e){let r=this.waiters;this.waiters=[];for(let n of r)n.reject(e)}};import{join as sa}from"node:path";import{mkdtempSync as Uk,rmSync as Jo}from"node:fs";import{tmpdir as ug}from"node:os";var zk={target:Ae.string().describe("What to watch: full | monitor:<i> | window:<title> (or exe=/hwnd=) | region:<x>,<y>,<w>,<h>."),exactTitle:Ae.boolean().optional().describe("window: targets match the whole title only (default false)."),mode:Ae.enum(["change","settle","text"]).optional().describe("change (default): return once it differs from the start. settle: once it has been still for settleSec. text: once text appears (OCR, re-read only after a change)."),text:Ae.string().min(1).max(qr).optional().describe("Mode text: what to wait for; tolerates OCR misreads."),regex:Ae.boolean().optional().describe("Mode text: text is a regex."),gone:Ae.boolean().optional().describe("Mode text: wait until it disappears instead."),backend:Ae.enum(["gdigrab","wgc"]).optional().describe("wgc: watch a window even when covered (window: targets; 1-2 s per check)."),timeoutSec:Ae.number().positive().max(600).optional().describe("Give up after this many seconds (default 30; a timeout is a result, not an error)."),settleSec:Ae.number().positive().max(60).optional().describe("Mode settle: seconds of stillness (default 1)."),intervalMs:Ae.number().int().min(100).max(5e3).optional().describe("Pause between checks in ms (default 250; 1000 with wgc)."),pixelThreshold:Ae.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${Go}).`),returnImage:Ae.boolean().optional().describe("Return the final state inline (default true)."),keep:Ae.boolean().optional().describe("Keep the final screenshot on disk and return its path (default false).")};function lg(t){t.registerTool("wait_for_change",{title:"Wait for Screen Change",description:"Wait until part of the screen changes, settles, or shows (or loses) some text, instead of guessing a sleep. Returns the elapsed time, changed regions (screenshot pixels; add `origin` for desktop), and the final state.",inputSchema:zk,outputSchema:B({outcome:Ae.string(),mode:Ae.string(),elapsedSec:Ae.number(),regions:Ae.array(Ae.unknown()),origin:B({x:Ae.number(),y:Ae.number()})}),annotations:fe},async(e,r)=>{try{k();let n=e.mode??"change";if(n==="text"!=(e.text!==void 0))throw new l('Use text with mode "text", and mode "text" with text.');let o=e.backend??"gdigrab",i=(e.timeoutSec??30)*1e3,s=(e.settleSec??1)*1e3,a=e.intervalMs??(o==="wgc"?1e3:250),c=await ut(e.target,{exactTitle:e.exactTitle,backend:o}),{target:u,monitors:d,window:p}=c;if(o==="wgc"&&!p?.hwnd)throw new l('backend "wgc" watches one window: use a window: target.');let f=n==="text"?`"${e.text}" ${e.gone?"disappears":"appears"}`:n==="settle"?"stops changing":"changes";await Dt(t,`Watch ${Nt(e.target,p)} for up to ${i/1e3} s, until it ${f}?`,r.signal);let m=Uk(sa(ug(),"screencast-wait-")),h=0,b=async()=>{let $=sa(m,`still-${h++}.png`);return await Lt(c,$,o),$},w=oa(u,d);if(o==="wgc")try{let $=await W(await b());if(!$.width||!$.height)throw new l("Could not read the window capture's size.");w={...p?.client??{x:w.x,y:w.y},width:$.width,height:$.height}}catch($){throw Jo(m,{recursive:!0,force:!0}),$}let g=na(w.width,w.height),y=rg(w,g,e.pixelThreshold),v=new ia,x=new AbortController,R=o==="gdigrab"?ji(ng(u,d,g,1e3/a),g.width*g.height,$=>v.push($),i+6e4,{signal:AbortSignal.any([r.signal,x.signal])}).then(()=>v.end(),$=>v.fail($)):Promise.resolve(),T=o==="gdigrab"?()=>v.next(15e3):async()=>{let $=await b();try{return await Ur(qo($,g),3e4,{signal:r.signal})}finally{Jo($,{force:!0})}},M=o==="gdigrab"?async()=>{}:void 0,H,G=null,L=0;try{if(n==="text"){let $=await cg({grab:T,read:async()=>{let J=await b(),[N]=await lt([J],m,r.signal);return Jo(J,{force:!0}),N?St(N.lines,e.text,e.regex===!0):[]},width:g.width,height:g.height,diff:y,timeoutMs:i,intervalMs:a,gone:e.gone===!0,signal:r.signal,...M?{sleep:M}:{}});G={matches:$.matches,reads:$.reads},H={outcome:$.outcome,regions:$.matches.map(({x:J,y:N,width:le,height:X})=>({x:J,y:N,width:le,height:X})),startedAt:$.startedAt}}else H=await ag({grab:T,mode:n,width:g.width,height:g.height,diff:y,timeoutMs:i,settleMs:s,intervalMs:a,signal:r.signal,...M?{sleep:M}:{}});L=Date.now()}finally{x.abort(),await R,Jo(m,{recursive:!0,force:!0})}let{outcome:C,regions:ne,everChanged:V,startedAt:Y}=H,q={outcome:C,mode:n,elapsedSec:Number(((L-Y)/1e3).toFixed(2)),...n==="settle"?{changedWhileWaiting:V}:{},...G?{text:e.text,...e.gone?{gone:!0}:{},matches:G.matches,ocrReads:G.reads}:{},regions:ne,origin:{x:w.x,y:w.y},...o==="wgc"?{backend:o}:{},...p?pr(p):{}},Q=[];if(e.returnImage!==!1&&C!=="cancelled"){let $=e.keep?sa(we("screenshots"),`wait-${he()}-${ge()}.png`):sa(ug(),`screencast-wait-${he()}-${ge()}.png`);try{o==="wgc"?await Lt(c,$,"wgc"):await te(Ti(u,$,d),6e4,{signal:r.signal}),e.keep&&(q.screenshotPath=$),Q.push(...(await Ce([$],Me,1)).images)}finally{e.keep||Jo($,{force:!0})}}return S(q,Q)}catch(n){return E(n)}})}import{z as Xe}from"zod";import{extname as pg,join as Ln}from"node:path";import{mkdtempSync as Hk,rmSync as Gk}from"node:fs";import{tmpdir as qk}from"node:os";var dg=new Set([".png",".jpg",".jpeg",".bmp",".gif",".webp",".tif",".tiff"]),aa=300,Xk={target:Xe.string().optional().describe("Live screen target (full | monitor:<i> | window:... | region:...), or pass input."),input:Xe.string().optional().describe("Image or video file to read instead of a live target."),timestamp:Xe.number().nonnegative().optional().describe("Video input: second to read (default 0)."),scanEverySec:Xe.number().positive().optional().describe("Video input: scan a frame every N s across the clip (e.g. for secrets before sharing); matches and redactRegions get times. Widens to stay within maxFrames."),maxFrames:Xe.number().int().min(1).max(vs).optional().describe(`scanEverySec frame cap (default ${Wt}; ~1 s each).`),exactTitle:Xe.boolean().optional().describe("window: targets match the whole title only (default false)."),backend:Xe.enum(["gdigrab","wgc"]).optional().describe("Live target: gdigrab (default) = what is visible; wgc (window:, FFmpeg 8+) = the window even if covered."),query:Xe.string().optional().describe("Text to find (case-insensitive, tolerates OCR misreads like I/l, O/0, _/-). Omit to return all text."),regex:Xe.boolean().optional().describe("Treat query as a regular expression (case-insensitive)."),redact:Xe.boolean().optional().describe("Also return padded match rectangles ready for redact_region's regions."),keep:Xe.boolean().optional().describe("Live target: keep the capture and return its path (default false: deleted after reading)."),returnImage:Xe.boolean().optional().describe("Return the image with matches outlined (default: true with a query).")};function mg(t){t.registerTool("find_text",{title:"Find Text (OCR)",description:"OCR (built into Windows) on the screen, an image, or video frames, with line and match boxes in image pixels (add `origin` for desktop coordinates). Locate UI text or secrets (e.g. regex 'sk-|ghp_|api.?key') to redact. Best-effort: review results.",inputSchema:Xk,outputSchema:B({imageSize:B({width:Xe.number(),height:Xe.number()})}),annotations:fe},async(e,r)=>{try{if(k(),e.target===void 0==(e.input===void 0))throw new l("Provide exactly one of: target (live screen) or input (a file).");let n=Hk(Ln(qk(),"screencast-ocr-"));try{if(e.scanEverySec!==void 0)return await Jk(e,n,r.signal);let o,i={},s;if(e.target!==void 0){let h=await ut(e.target,{exactTitle:e.exactTitle,backend:e.backend});o=e.keep?Ln(we("screenshots"),`ocr-${he()}-${ge()}.png`):Ln(n,"capture.png");let b=e.backend??"gdigrab";await Dt(t,`Capture ${Nt(e.target,h.window)} once to read the text on it?`,r.signal),await Lt(h,o,b),h.window&&(i=pr(h.window));let w=oa(h.target,h.monitors);s=b==="wgc"&&h.window?.client?h.window.client:{x:w.x,y:w.y}}else{O(e.input);let h=dg.has(pg(e.input).toLowerCase());o=Ln(n,"frame.png"),await te(["-y","-v","error",...h?[]:["-ss",String(e.timestamp??0)],"-i",e.input,"-frames:v","1",...Te(o)],6e4,{signal:r.signal})}let[a]=await lt([o],n,r.signal);if(!a)throw new l("Could not read the frame.");let{lines:c,width:u,height:d}=a,p=e.query?St(c,e.query,e.regex===!0):[],f=[];if(e.returnImage??!!e.query){let h=Ln(n,"shown.png");await te(Xo(o,p,h),3e4,{signal:r.signal}),f.push(...(await Ce([h],Me,1)).images)}return S({...e.target!==void 0?e.keep?{screenshotPath:o}:{}:{input:e.input},imageSize:{width:u,height:d},...s?{origin:s}:{},...e.query?{query:e.query,matchCount:p.length,matches:p,...e.redact?{redactRegions:Ss(p,{width:u,height:d})}:{}}:{},text:c.map(h=>h.text).join(`
331
+ `),lines:c.slice(0,aa).map(({words:h,...b})=>b),...c.length>aa?{linesTruncated:c.length-aa}:{},...i,note:"OCR is best-effort: small or stylised text can be missed. Review before relying on it, especially for redaction."},f)}finally{Gk(n,{recursive:!0,force:!0})}}catch(n){return E(n)}})}async function Jk(t,e,r){if(t.input===void 0)throw new l("scanEverySec reads a video file: pass input, not target.");if(O(t.input),dg.has(pg(t.input).toLowerCase()))throw new l("scanEverySec is for a video input; an image has one frame, so drop scanEverySec.");let n=t.maxFrames??Wt,o=await Rn(t.input,{everySec:t.scanEverySec,maxFrames:n},e,r),{step:i}=o,[s]=o.frames;if(!s)throw new l("Could not read any frames from the video.");let a=new Set;for(let h of o.frames)for(let b of h.lines)a.add(b.text);let{matches:c,redactRegions:u}=t.query?br(o,t.query,t.regex===!0):{matches:[],redactRegions:[]},d=[],p=c[0],f=p&&o.frames.find(h=>h.t===p.t)?.path;if((t.returnImage??!!t.query)&&p&&f){let h=Ln(e,"shown.png");await te(Xo(f,c.filter(b=>b.t===p.t),h),3e4,{signal:r}),d.push(...(await Ce([h],Me,1)).images)}let m=[...a].join(`
332
+ `);return S({input:t.input,imageSize:{width:s.width,height:s.height},scan:{everySec:Math.round(i*1e3)/1e3,framesScanned:o.frames.length,...o.clamped?{note:`Widened from ${t.scanEverySec} s to fit maxFrames ${n}.`}:{}},...t.query?{query:t.query,matchCount:c.length,matches:c.slice(0,aa),...t.redact?{redactRegions:u}:{}}:{},text:m.length>2e4?`${m.slice(0,2e4)}...`:m,note:"OCR is best-effort and reads only the sampled frames: text shown briefly between samples, or small or stylised text, can be missed. Review before sharing, especially for redaction."},d)}import{z as $r}from"zod";import{dirname as tE,join as Gu}from"node:path";import{existsSync as Bn,mkdirSync as rE,mkdtempSync as nE,readFileSync as Wn,readdirSync as oE,rmSync as Xu}from"node:fs";import{tmpdir as iE}from"node:os";import{spawnSync as Yk}from"node:child_process";import{isAbsolute as Kk}from"node:path";var Yr=8;function ca(t){let e=/^ff(?:mpeg|probe) version (\S+)/m.exec(t)?.[1]??null,r=e?/^n?(\d+)\.\d+/.exec(e):null;if(r)return{version:e,major:Number(r[1]),inferred:!1};let n=/^\s*libavutil\s+(\d+)\./m.exec(t);return n&&Number(n[1])>=56?{version:e,major:Number(n[1])-52,inferred:!0}:{version:e,major:null,inferred:!1}}function fg(t){let e=new Set,r=t.split(/^\s*---\s*$/m).slice(1).join(`
333
+ `)||t;for(let n of r.split(/\r?\n/)){let o=/^\s{0,2}[D ][E ]\s?[d ]?\s+([a-z0-9_,]+)\s/i.exec(n);if(o?.[1])for(let i of o[1].split(","))e.add(i)}return[...e]}function Hu(t,e){try{let r=Yk(t,e,{encoding:"utf8",windowsHide:!0,timeout:1e4});return r.status!==0?null:`${r.stdout??""}${r.stderr??""}`}catch{return null}}function ua(t){return Hu(t,["-version"])}function hg(t){return Hu(t,["-hide_banner","-devices"])}function gg(t){return Kk(t)?t:Hu(process.platform==="win32"?"where":"which",[t])?.split(/\r?\n/).map(r=>r.trim()).find(r=>r.length>0)??null}var Vk=`
333
334
  $ErrorActionPreference = 'Stop'
334
335
  $null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
335
336
  $e = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
336
337
  [pscustomobject]@{ available = ($null -ne $e); language = $(if ($e) { $e.RecognizerLanguage.LanguageTag } else { $null }); languages = @([Windows.Media.Ocr.OcrEngine]::AvailableRecognizerLanguages | ForEach-Object { $_.LanguageTag }) } | ConvertTo-Json -Compress
337
- `;async function wr(){if(process.platform!=="win32")return{available:!1,language:null,languages:[],error:"The Windows OCR engine is available on Windows only."};try{let t=JSON.parse(await st(Wk,"OCR languages",{timeoutMs:sr(15e3)})),e=Array.isArray(t.languages)?t.languages:t.languages?[t.languages]:[];return{available:t.available===!0,language:t.language??null,languages:e}}catch(t){return{available:!1,language:null,languages:[],error:U(t)}}}var jk=["SCREENCAST_HOME","SCREENCAST_ALLOWED_DIRS","FFMPEG_PATH","FFPROBE_PATH","SCREENCAST_WHISPER_MODEL","SCREENCAST_MAX_RECORDING_SEC","SCREENCAST_JOB_TIMEOUT_MS","SCREENCAST_PS_TIMEOUT_MS","SCREENCAST_RETENTION_DAYS","SCREENCAST_CONFIRM_CAPTURE","SCREENCAST_TOOLSETS","SCREENCAST_DEBUG_JOBS"],Uk=[{name:"SCREENCAST_MAX_RECORDING_SEC",ok:t=>Number.isInteger(t)&&t>=0&&t<=168*3600,want:"an integer from 0 (no cap) to 604800",otherwise:"start_recording fails until it is fixed"},{name:"SCREENCAST_JOB_TIMEOUT_MS",ok:t=>Number.isInteger(t)&&t>0,want:"a positive integer (milliseconds)",otherwise:"edits use the default timeout"},{name:"SCREENCAST_PS_TIMEOUT_MS",ok:t=>Number.isInteger(t)&&t>0,want:"a positive integer (milliseconds)",otherwise:"the PowerShell helpers use their default limits"},{name:"SCREENCAST_RETENTION_DAYS",ok:t=>Number.isFinite(t)&&t>=0,want:"a number of days (0 = off)",otherwise:"nothing is pruned"}],zk=["auto","1","true","yes","on","always","0","false","no","off","never"];function hg(t=process.env){let e=[];for(let n of Uk){let o=t[n.name];o===void 0||o.trim()===""||n.ok(Number(o.trim()))||e.push(`${n.name}="${o}" is not ${n.want}, so ${n.otherwise}.`)}let r=t.SCREENCAST_CONFIRM_CAPTURE;return r!==void 0&&r.trim()!==""&&!zk.includes(r.trim().toLowerCase())&&e.push(`SCREENCAST_CONFIRM_CAPTURE="${r}" is not auto, always (1/true/yes/on) or off (0/false/no/never), so captures follow auto.`),e}function gg(t=process.env){return Object.fromEntries(jk.map(e=>{let r=t[e];return[e,r&&r.trim().length>0?r:null]}))}var bg=[{filter:"whisper",tools:"transcribe",why:`FFmpeg ${Hr}+ built with whisper.cpp`},{filter:"gfxcapture",tools:'backend: "wgc" (screenshot, start_recording, find_text)',why:`FFmpeg ${Hr}+ on Windows`},{filter:"subtitles",tools:"burn_subtitles",why:"libass"},{filter:"drawtext",tools:"title_card, callout, contact_sheet labels, produce",why:"libfreetype"},{filter:"afftdn",tools:"denoise",why:"a standard build"},{filter:"loudnorm",tools:"normalize_audio",why:"a standard build"},{filter:"xfade",tools:"xfade_transition, assemble_highlights",why:"FFmpeg 4.3+"}];var Gu=8,Yk={input:yr.string().optional().describe("Recording path."),sessionId:yr.string().optional().describe("Or a stopped session id."),sceneThreshold:yr.number().gt(0).lt(1).optional().describe(`Change starting a segment (default ${Ou}).`),maxFrames:yr.number().int().min(1).max(Gf).optional().describe(`Keyframes to OCR (default ${Nu}).`),transcript:yr.string().optional().describe("An .srt, or 'whisper' to transcribe. Default: <video>.srt if any."),force:yr.boolean().optional().describe("Re-OCR despite a matching cached index.")};function wg(t){t.registerTool("index_recording",{title:"Index Recording",description:"Build a recording's text timeline (<video>.index.json: OCR per scene, events, markers, transcript) for search_recording.",inputSchema:Yk,outputSchema:N({indexPath:yr.string(),segments:yr.number()}),annotations:I},async(e,r)=>{let n=qk(Hu(Jk(),"screencast-index-"));try{let{ffmpeg:o}=k(),i=await qs(e),s=await L(i.path),a=s.videoDurationSec??s.durationSec;if(!s.width||a===null||!(a>0))throw new l(`Could not read the video size and duration of ${i.path}.`);let c=e.sceneThreshold??Ou,u=e.maxFrames??Nu,d=we("edits"),p=Xf(i.path,d),f=Hs(i.path),m=vo(r),h=[],b=e.force?null:js(i.path,d,f),w=b?Wo(b):null,g=null,y=async()=>g??=process.platform==="win32"&&(await wr()).available,$=Jf(w,{fingerprint:f,sceneThreshold:c,maxFrames:u,ocrAvailable:w!==null&&!w.ocr?await y():!1}),S,C=0,M=!1;if($)S=w.segments,C=w.framesRead,M=w.ocr;else{let J=await ne(o,rr(i.path,c),le(a),{signal:r.signal});if(J.code!==0)throw new l(`Scene scan failed (exit ${J.code}): ${J.stderr.trim().slice(-400)}`);m?.(.1);let ie=Vf(Kf(nr(J.stdout),a,u),a),ce=ie.map(()=>[]);if(M=await y(),M)for(let q=0;q<ie.length;q+=Gu){r.signal.throwIfAborted();let H=ie.slice(q,q+Gu),G=(await He(H,async(te,T)=>{let _=Hu(n,`key_${q+T}.png`);return await Z(fn(i.path,zs(te),_),6e4,{signal:r.signal}),{at:q+T,path:_}})).filter(te=>Dn(te.path)),Q=G.length>0?await ct(G.map(te=>te.path),n,r.signal,{sameSize:!0}):[];Q.forEach((te,T)=>ce[G[T].at]=te.lines.map(_=>_.text)),C+=Q.length,m?.(.1+.85*Math.min(ie.length,q+Gu)/ie.length)}else h.push("Windows OCR is not available, so the index holds no screen text; install an OCR language (doctor).");let x=ie.map((q,H)=>({...q,ocr:ce[H]??[]}));S=M?Qf(x):x}S=Yf(S);let R=i.eventsPath?Zf(je(Ln(i.eventsPath,"utf8"))):[];S=zr(S,R,"events"),S=zr(S,eh(i.markers),"markers");let P=xt(i.path);if(Dn(P)){let J=An(Ln(P,"utf8")),{busy:ie}=Tn(J),ce=ie.map(x=>{let q=Math.max(...J.filter(H=>H.t>=x.start&&H.t<=x.end).map(H=>H.cpu??H.sysCpu));return{t:x.start,text:`cpu pinned ${Math.round(q)}% for ${Math.round(x.end-x.start)} s (performance spike)`}});ce.length&&(S=zr(S,[...S.flatMap(x=>x.events??[]),...ce],"events"))}let j=Lt(i.path);if(Dn(j)){let J=Es(Ln(j,"utf8")),ie=Oe(J.map(ce=>`${ce.source}: ${ce.line}`),Ge);S=zr(S,J.map((ce,x)=>({t:ce.t,text:ie[x]??""})),"logs")}let X=await Kk(e.transcript,i.path,s.audioCodec!==null,a,r.signal,h);if(X!==null)S=zr(S,th(X),"transcript");else if($&&w){let J=w.segments.flatMap(ie=>ie.transcript??[]);S=zr(S,J,"transcript")}let D={version:Fu,video:i.path,fingerprint:f,durationSec:a,createdAt:new Date().toISOString(),sceneThreshold:c,maxFrames:u,framesRead:C,ocr:M,segments:S};Gk(Hu(p,".."),{recursive:!0}),rh(p,D);let ae=Du(i.path);if(ae!==p&&Dn(ae)){let J=Wo(ae);J&&Bs(J,i.path,f)&&qu(ae,{force:!0})}m?.(1);let ee=J=>S.reduce((ie,ce)=>ie+(ce[J]?.length??0),0);return v({indexPath:p,segments:S.length,cached:$,framesRead:C,durationSec:a,sources:{screenLines:S.reduce((J,ie)=>J+ie.ocr.length,0),events:ee("events"),markers:ee("markers"),transcriptCues:ee("transcript")},...h.length>0?{note:h.join(" ")}:{},next:"search_recording { query } returns timecoded hits. Secret-shaped screen text is stored masked; the rest of the index is plain text, so treat it like the video."})}catch(o){return E(o)}finally{qu(n,{recursive:!0,force:!0})}})}async function Kk(t,e,r,n,o,i){if(t==="whisper"){if(!r)return i.push("The recording has no audio, so there is no transcript."),null;if(!Ye("whisper"))throw new l("This ffmpeg has no whisper filter.","transcript: 'whisper' needs FFmpeg 8 built with whisper.cpp; or pass an .srt.");let c=br(void 0),u=Ue(".srt");try{return await Z(On(e,c,u),le(n),{signal:o}),Dn(u)?ut(We(Ln(u,"utf8"))):[]}finally{qu(u,{force:!0})}}if(t!==void 0){if(!Dn(t))throw new l(`Transcript not found: ${t}`);return ut(We(Ln(t,"utf8")))}let s;try{s=Xk(Hk(e))}catch{return null}let a=Us(e,s);return a.ambiguous&&i.push("Another video in the folder shares this one's base name, so its .srt was not attached; pass transcript."),a.path?ut(We(Ln(a.path,"utf8"))):null}import{z as jt}from"zod";import{join as yg}from"node:path";import{existsSync as xg,mkdtempSync as Vk,rmSync as Qk}from"node:fs";import{tmpdir as Zk}from"node:os";var eE=480,tE={input:jt.string().optional().describe("Recording path."),sessionId:jt.string().optional().describe("Or a stopped session id."),query:jt.string().min(1).describe("Text; tolerates OCR misreads."),regex:jt.boolean().optional().describe("query is a regex."),limit:jt.number().int().min(1).max(qf).optional().describe(`Max hits (default ${Ls}).`),images:jt.number().int().min(0).max(zo).optional().describe("Thumbnails of the top N hits (default 0).")};function Sg(t){t.registerTool("search_recording",{title:"Search Recording",description:"Search an index_recording timeline (screen text, events, markers, transcript): timecoded hits, best first, secrets masked. No frames unless asked. No input: search all indexes.",inputSchema:tE,outputSchema:N({total:jt.number(),hits:jt.array(jt.unknown())}),annotations:he},async(e,r)=>{try{if(e.input===void 0&&e.sessionId===void 0){if((e.images??0)>0)throw new l("images needs one recording.","Pass input or sessionId, or search the library with images: 0.");let f=oh(Me()).flatMap(b=>{let w=Lu(b);return w?[{indexPath:b,index:w}]:[]}),m=ih(f,e.query,{regex:e.regex===!0,limit:e.limit}),h=m.recordings.map(b=>({...b,...xg(b.video)?{}:{missing:!0}}));return v({query:e.query,searched:m.searched,total:m.total,hits:m.hits,recordings:h,...m.searched===0?{note:"No indexed recordings under SCREENCAST_HOME; run index_recording first."}:{}})}let n=await qs(e),o=Hs(n.path),i=js(n.path,we("edits"),o),s=i?Lu(i):null;if(!i||!s)throw new l(`No index for ${n.path}.`,"Run index_recording on it first.");let a=!Gs(s.fingerprint,o),{hits:c,total:u}=Bu(s,e.query,{regex:e.regex===!0,limit:e.limit,video:n.path,fingerprint:o}),d=Math.min(ta(e.images??0),c.length),p=[];if(d>0){k();let f=Vk(yg(Zk(),"screencast-search-"));try{let m=[];for(let[h,b]of c.slice(0,d).entries()){let w=b.t===b.start?zs(b):b.t,g=yg(f,`hit_${h}.png`);await Z(fn(n.path,w,g),6e4,{signal:r.signal}),xg(g)&&m.push(g)}p=(await Re(m,eE,d)).images}finally{Qk(f,{recursive:!0,force:!0})}}return v({indexPath:i,query:e.query,total:u,hits:c,...u>c.length?{more:u-c.length}:{},...s.ocr?{}:{note:"The index has no screen text (OCR was unavailable when it was built)."},...a?{stale:!0,warning:"The recording changed since it was indexed; run index_recording again."}:{}},p)}catch(n){return E(n)}})}import{z as xr}from"zod";var rE={input:xr.string().min(1).describe("Path to the media file to probe.")};function vg(t){t.registerTool("get_media_info",{title:"Get Media Info",description:"Probe a media file with ffprobe and return duration, resolution, frame rate, codecs, container format, and size.",inputSchema:rE,outputSchema:N({input:xr.string(),durationSec:xr.number().nullable(),width:xr.number().nullable(),height:xr.number().nullable(),fps:xr.number().nullable(),videoCodec:xr.string().nullable(),audioCodec:xr.string().nullable()}),annotations:he},async e=>{try{return F(e.input),v({input:e.input,...await L(e.input)})}catch(r){return E(r)}})}import{z as Gr}from"zod";import{extname as nE}from"node:path";var oE={input:Gr.string().min(1).describe("Path to the source video."),start:Gr.number().nonnegative().describe("Start time in seconds."),end:Gr.number().positive().optional().describe("End time in seconds. Use end OR duration."),duration:Gr.number().positive().optional().describe("Clip length in seconds. Use end OR duration."),exact:Gr.boolean().optional().describe("Re-encode for a frame-exact cut with the removed content really gone (default true). false = fast stream copy that snaps to a keyframe and keeps hidden earlier frames; never use it to remove secrets."),output:Gr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Gr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function $g(t){t.registerTool("trim",{title:"Trim Video",description:"Cut a video down to one sub-clip by start + (end or duration). For several segments use clip; to combine with other edits use pipeline.",inputSchema:oE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.exact===!1?nE(e.input)||".mp4":V(e.input),o=B(e.output,"trim",n,{overwrite:e.overwrite,anyContainer:e.exact===!1}),i=_p(e.input,o,{start:e.start,end:e.end,duration:e.duration,exact:e.exact}),s=e.start??0,a=e.end??await se(e.input),c=e.duration??(a!==null?a-s:null);return await W(i,{output:o,durationSec:c,extra:r}),v({outputPath:o})}catch(n){return E(n)}})}import{z as ma}from"zod";import{extname as pE,resolve as dE}from"node:path";import{writeFileSync as mE,rmSync as fE}from"node:fs";var iE=1920,sE=1080,kg=30,Eg=48e3,Bn=1,Xu="standard";function Ju(t){return Math.round(t*1e3)/1e3}function _g(t){return t.width!==void 0&&tr(t.width,"width"),t.height!==void 0&&tr(t.height,"height"),{w:t.width??iE,h:t.height??sE}}function aE(t,e,r){return`scale=${t}:${e}:force_original_aspect_ratio=decrease,pad=${t}:${e}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${r},format=yuv420p`}function cE(t){return`aresample=${t},aformat=sample_fmts=fltp:channel_layouts=stereo`}function uE(t,e){let r=[],n=0;for(let[o,i]of t.slice(0,-1).entries())n+=i,r.push(Math.max(0,Ju(n-(o+1)*e)));return r}function qr(t){return t.videoDurationSec??t.durationSec}function Tg(t,e,r,n,o={},i=[!1,!1]){let s=Sc(o.transition??"fade"),a=o.duration??Bn;if(!Number.isFinite(a)||a<=0)throw new l("transition duration must be a positive number.");if(!Number.isFinite(r[0])||r[0]<=a)throw new l(`first clip (${r[0]}s) must be longer than the transition (${a}s).`);return Jo([t,e],r,n,{...o,transition:s},i)}function Jo(t,e,r,n={},o=[]){if(t.length<2)throw new l("assemble_highlights requires at least two clips.");let{w:i,h:s}=_g(n),a=n.fps??kg,c=n.audioRate??Eg,u=n.transition??"cut",d=n.duration??Bn,p=t.length,f=aE(i,s,a),m=cE(c),h=o.some(Boolean),b=[];for(let g=0;g<p;g++)if(b.push(`[${g}:v]${f}[v${g}]`),!!h)if(o[g]){let y=e[g]??Number.NaN,$=Number.isFinite(y)&&y>0?`,apad,atrim=duration=${Ju(y)}`:"";b.push(`[${g}:a]${m}${$}[a${g}]`)}else{let y=e[g]??Number.NaN;if(!Number.isFinite(y)||y<=0)throw new l(`clip ${g} has no audio track and its duration is unknown, so a matching silent track cannot be generated.`);b.push(`anullsrc=channel_layout=stereo:sample_rate=${c}:d=${y}[a${g}]`)}let w=[];if(u==="cut")if(h){let g=t.map((y,$)=>`[v${$}][a${$}]`).join("");b.push(`${g}concat=n=${p}:v=1:a=1[vout][aout]`),w.push("-map","[vout]","-map","[aout]")}else{let g=t.map((y,$)=>`[v${$}]`).join("");b.push(`${g}concat=n=${p}:v=1:a=0[vout]`),w.push("-map","[vout]")}else{if(Sc(u),e.length!==p)throw new l(`a ${u} transition needs a duration for each of the ${p} clips.`);if(!Number.isFinite(d)||d<=0)throw new l("transition duration must be a positive number.");let g=e.findIndex(S=>!Number.isFinite(S)||S<=d);if(g!==-1)throw new l(`clip ${g} (${e[g]}s) must be longer than the ${d}s ${u} transition. Use a shorter transition or trim fewer frames.`);let y=uE(e,d),$="v0";for(let S=1;S<p;S++){let C=S===p-1?"vout":`vx${S}`;b.push(`[${$}][v${S}]xfade=transition=${u}:duration=${d}:offset=${y[S-1]}[${C}]`),$=C}if(w.push("-map","[vout]"),h){let S="a0";for(let C=1;C<p;C++){let M=C===p-1?"aout":`ax${C}`;b.push(`[${S}][a${C}]acrossfade=d=${d}[${M}]`),S=M}w.push("-map","[aout]")}}return["-y",...t.flatMap(g=>["-i",g]),"-filter_complex",b.join(";"),...w,...Se({quality:n.quality??Xu,audio:h?"aac":"none",faststart:!0}),r]}var Yu=3;function Ag(t,e,r,n={}){let{w:o,h:i}=_g(n),s=n.duration??Yu,a=n.fps??kg,c=De(n.bg??"black","bg"),u=De(n.fontColor??"white","fontColor"),d=n.fontSize??96;if(!Number.isFinite(s)||s<=0)throw new l("title duration must be a positive number.");if(!Number.isInteger(d)||d<=0)throw new l("fontSize must be a positive integer.");let p=`drawtext=fontfile=${ye(e)}:textfile=${ye(t)}:expansion=none:fontcolor=${u}:fontsize=${d}:x=(w-text_w)/2:y=(h-text_h)/2:shadowcolor=black@0.5:shadowx=2:shadowy=2`;return["-y","-f","lavfi","-i",`color=c=${c}:s=${o}x${i}:d=${s}:r=${a}`,"-f","lavfi","-i","anullsrc=channel_layout=stereo:sample_rate=48000","-vf",p,"-shortest",...Se({quality:n.quality??Xu,audio:"aac",faststart:!0}),r]}function Rg(t,e,r,n,o,i={}){if(!Number.isFinite(n)||n<=0)throw new l("video duration must be known and positive.");let s=i.musicVolume??(o?.25:.8),a=i.fadeIn??1,c=i.fadeOut??2;for(let[h,b]of[[s,"musicVolume"],[a,"fadeIn"],[c,"fadeOut"]])if(!Number.isFinite(h)||h<0)throw new l(`${b} must be a non-negative number.`);let u=i.duck??!1,d=Math.max(0,Ju(n-c)),p=`[1:a]afade=t=in:st=0:d=${a},afade=t=out:st=${d}:d=${c},volume=${s}`,f="amix=inputs=2:duration=first:dropout_transition=0:normalize=0",m=[];return o?(m.push(`${p}[music]`),u?(m.push("[music][0:a]sidechaincompress=threshold=0.03:ratio=8:attack=20:release=300[ducked]"),m.push(`[0:a][ducked]${f}[aout]`)):m.push(`[0:a][music]${f}[aout]`)):m.push(`${p}[aout]`),["-y","-i",t,"-stream_loop","-1","-i",e,"-filter_complex",m.join(";"),"-map","0:v","-map","[aout]","-t",String(n),...Se({video:["-c:v","copy"],audio:"aac",bitrate:"192k",faststart:!0}),r]}var Wn=["16:9","9:16","1:1","4:5"],la=["pad","crop"],jn={"16:9":{w:1920,h:1080},"9:16":{w:1080,h:1920},"1:1":{w:1080,h:1080},"4:5":{w:1080,h:1350}};function pa(t,e,r){return r==="crop"?`scale=${t}:${e}:force_original_aspect_ratio=increase,crop=${t}:${e},setsar=1`:`scale=${t}:${e}:force_original_aspect_ratio=decrease,pad=${t}:${e}:(ow-iw)/2:(oh-ih)/2,setsar=1`}function Mg(t,e,r,n="pad",o=Xu){let i=jn[r];if(!i)throw new l(`Unknown aspect "${r}".`);return["-y","-i",t,"-vf",`${pa(i.w,i.h,n)},format=yuv420p`,...Se({quality:o,audio:"copy",faststart:!0}),e]}var da=["youtube","instagram_reel","tiktok","x","square","steam_trailer","vertical_reel"],Ku={youtube:{aspect:"16:9",fps:30,videoBitrate:"8M",bufsize:"16M",audioBitrate:"192k"},instagram_reel:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},tiktok:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},x:{aspect:"16:9",fps:30,videoBitrate:"5M",bufsize:"10M",audioBitrate:"128k"},square:{aspect:"1:1",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},steam_trailer:{aspect:"16:9",fps:30,videoBitrate:"5.5M",bufsize:"11M",audioBitrate:"192k",cbr:!0,loudness:{sampleRate:48e3}},vertical_reel:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k",blurFill:!0,loudness:{}}};function lE(t,e,r=""){return`split=2[${r}bg][${r}fg];[${r}bg]scale=${t}:${e}:force_original_aspect_ratio=increase,crop=${t}:${e},boxblur=20:2,eq=brightness=-0.08[${r}b];[${r}fg]scale=${t}:${t}:force_original_aspect_ratio=decrease:force_divisible_by=2[${r}f];[${r}b][${r}f]overlay=(W-w)/2:(H-h)/2,setsar=1`}function Vu(t,e="pad",r=""){let n=Ku[t];if(!n)throw new l(`Unknown platform "${t}".`);let o=jn[n.aspect],i=n.blurFill?lE(o.w,o.h,r):pa(o.w,o.h,e),s=n.loudness?`loudnorm=I=-14:TP=-1:LRA=11,aresample=${n.loudness.sampleRate??Eg}`:void 0;return{vf:`${i},fps=${n.fps},format=yuv420p`,...s?{af:s}:{},encode:["-c:v","libx264","-preset","medium",...n.cbr?["-profile:v","high"]:[],"-b:v",n.videoBitrate,...n.cbr?["-minrate",n.videoBitrate,"-x264-params","nal-hrd=cbr"]:[],"-maxrate",n.videoBitrate,"-bufsize",n.bufsize,"-pix_fmt","yuv420p",...Cr(n.audioBitrate),...n.loudness?.sampleRate?["-ar",String(n.loudness.sampleRate),"-ac","2"]:[],"-r",String(n.fps),...Pr],width:o.w,height:o.h}}function Cg(t,e,r,n="pad"){let{vf:o,af:i,encode:s}=Vu(r,n);return["-y","-i",t,"-vf",o,...i?["-af",i]:[],...s,e]}var hE={inputs:ma.array(ma.string().min(1)).min(2).describe("Video paths to join, in order."),output:ma.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ma.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Pg(t){t.registerTool("concat",{title:"Concatenate Videos",description:"Join videos end to end with hard cuts: stream copy when they match, else a re-encode (`mode` says which). For transitions use xfade_transition or assemble_highlights.",inputSchema:hE,outputSchema:Y,annotations:I},async(e,r)=>{try{k();let n=e.inputs.map(m=>dE(m));for(let m of n)F(m);let o=await Promise.all(n.map(m=>L(m))),[i]=n,[s]=o;if(i===void 0||s===void 0)throw new l("concat needs at least two inputs.");let a=o.map(m=>qr(m)),c=a.every(m=>m!==null)?a.reduce((m,h)=>m+h,0):null,u=Ap(n,o);if(u!==null){let m=B(e.output,"concat",V(i),{overwrite:e.overwrite}),h=w=>w!==null&&w>=2?w-w%2:void 0,b=Jo(n,a.map(w=>w??0),m,{transition:"cut",width:h(s.width),height:h(s.height),fps:s.fps??void 0},o.map(w=>w.audioCodec!==null));return await W(b,{output:m,durationSec:c,extra:r}),v({outputPath:m,inputCount:n.length,mode:"reencode",reason:u})}let d=pE(i)||".mp4",p=B(e.output,"concat",d,{overwrite:e.overwrite,anyContainer:!0}),f=Ue(".txt");mE(f,Tp(n));try{await W(hn(f,p),{output:p,durationSec:c,extra:r})}finally{fE(f,{force:!0})}return v({outputPath:p,inputCount:n.length,mode:"copy"})}catch(n){return E(n)}})}import{z as Un}from"zod";var gE={input:Un.string().min(1).describe("Path to the source media."),format:Un.enum(["mp4","gif","webm"]).describe("mp4 (H.264), webm (VP9), or gif (palette)."),fps:Un.number().positive().optional().describe("gif only: fps (default 12)."),width:Un.number().positive().optional().describe("gif only: width in px (default 720)."),output:Un.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Un.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ig(t){t.registerTool("convert",{title:"Convert Format",description:"Convert media to mp4, webm, or gif. For a size-bounded GIF/WebP prefer export_gif; for a smaller mp4, compress or export_preset.",inputSchema:gE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.format,o=B(e.output,"convert",`.${n}`,{overwrite:e.overwrite,anyContainer:!0}),i=Rp(e.input,o,n,{fps:e.fps,width:e.width});return await W(i,{output:o,durationSec:await se(e.input),extra:r}),v({outputPath:o,format:n})}catch(n){return E(n)}})}import{z as Ut}from"zod";var fa=12,ha=960,Sr=1e7,Fg=5;function Og(t,e,r){return(t==="gif"?[[1,1,256],[.83,.8,256],[.67,.67,128],[.5,.5,64],[.4,.4,32],[.33,.33,16]]:[[1,1,75],[.83,.8,65],[.67,.67,55],[.5,.5,45],[.4,.4,35],[.33,.33,25]]).map(([o,i,s])=>({fps:Math.max(1,Math.round(e*o*10)/10),width:Math.max(64,Math.round(r*i/2)*2),...t==="gif"?{colors:s}:{quality:s}}))}function Ng(t,e,r,n){let o=n-1;if(t>=o)return null;let i=Math.max(1,Math.ceil(Math.log(e/r)/Math.log(1.8)));return Math.min(o,t+i)}function Dg(t,e,r,n,o={}){if(!(n.fps>0)||!Number.isInteger(n.width)||n.width<16)throw new l("fps must be positive and width an integer of at least 16.");if(o.start!==void 0&&!(o.start>=0))throw new l("start must be >= 0.");if(o.duration!==void 0&&!(o.duration>0))throw new l("duration must be > 0.");let i=[...o.start?["-ss",String(o.start)]:[],...o.duration?["-t",String(o.duration)]:[]],s=`fps=${n.fps},scale='min(${n.width},iw)':-1:flags=lanczos`;if(r==="gif"){let a=n.colors??256;return["-y",...i,"-i",t,"-an","-vf",`${s},split[a][b];[a]palettegen=stats_mode=diff:max_colors=${a}[p];[b][p]paletteuse=dither=sierra2_4a:diff_mode=rectangle`,"-loop","0",e]}return["-y",...i,"-i",t,"-an","-vf",s,"-c:v","libwebp_anim","-lossless","0","-q:v",String(n.quality??75),"-compression_level","4","-loop","0",e]}import{basename as bE,dirname as wE,extname as yE,join as xE}from"node:path";import{renameSync as SE,rmSync as vE,statSync as $E}from"node:fs";async function zn(t,e,r,n){let o=r.format??"gif",i=r.maxBytes??Sr,s=await se(t),a=r.duration??(s!==null?s-(r.start??0):null),c=Og(o,r.fps??fa,r.width??ha),u=yE(e),d=f=>xE(wE(e),`${bE(e,u)}.try${f}${u}`),p=[];try{let f=0;for(;f!==null&&p.length<Fg;){let b=c[f];if(!b)break;let w=d(p.length),g={start:r.start,duration:r.duration};await W(Dg(t,w,o,b,g),{output:w,durationSec:a,extra:n});let y=$E(w).size;if(p.push({path:w,size:y,settings:b}),y<=i)break;f=Ng(f,y,i,c.length)}let m=p.find(b=>b.size<=i),h=m??p.reduce((b,w)=>w.size<b.size?w:b);return SE(h.path,e),{outputPath:e,format:o,sizeBytes:h.size,maxBytes:i,withinBudget:h.size<=i,settings:h.settings,attempts:p.map(b=>({...b.settings,sizeBytes:b.size})),...m?{}:{note:`Could not get under ${i} bytes; kept the smallest attempt. Export a shorter clip (start/duration), or try format: 'webp'.`}}}finally{for(let f of p)vE(f.path,{force:!0})}}var kE={input:Ut.string().min(1).describe("Path to the source video."),format:Ut.enum(["gif","webp"]).optional().describe("gif (default) or webp (usually much smaller)."),maxBytes:Ut.number().int().min(1e4).optional().describe(`Size budget in bytes (default ${Sr}, under GitHub's 10 MB image limit).`),fps:Ut.number().positive().max(30).optional().describe(`Starting frame rate (default ${fa}).`),width:Ut.number().int().min(64).max(1920).optional().describe(`Starting width in px (default ${ha}).`),start:Ut.number().nonnegative().optional().describe("Start second."),duration:Ut.number().positive().optional().describe("Seconds to export (default: to the end)."),output:Ut.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ut.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Lg(t){t.registerTool("export_gif",{title:"Export GIF or WebP",description:"Export an animated GIF or WebP that fits a size budget (for PRs, issues, READMEs), stepping fps, width, and quality down until it fits.",inputSchema:kE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.format??"gif",o=e.maxBytes??Sr,i=B(e.output,"anim",`.${n}`,{overwrite:e.overwrite,anyContainer:!0});return v(await zn(e.input,i,{format:n,maxBytes:o,fps:e.fps,width:e.width,start:e.start,duration:e.duration},r))}catch(n){return E(n)}})}import{z as Xr}from"zod";var EE={input:Xr.string().min(1).describe("Path to the source video."),x:Xr.number().int().nonnegative(),y:Xr.number().int().nonnegative(),width:Xr.number().int().positive(),height:Xr.number().int().positive(),output:Xr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Xr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Bg(t){t.registerTool("crop",{title:"Crop Video",description:"Crop a video to a pixel rectangle; one running off the frame is rejected.",inputSchema:EE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let{width:n,height:o,durationSec:i}=await L(e.input),s=V(e.input),a=B(e.output,"crop",s,{overwrite:e.overwrite}),c=Mp(e.input,a,{x:e.x,y:e.y,width:e.width,height:e.height},{width:n,height:o});return await W(c,{output:a,durationSec:i,extra:r}),v({outputPath:a})}catch(n){return E(n)}})}import{z as Yo}from"zod";var _E={input:Yo.string().min(1).describe("Path to the source video."),width:Yo.number().int().positive().optional().describe("Target width in px. Omit to derive from height (keeps aspect)."),height:Yo.number().int().positive().optional().describe("Target height in px. Omit to derive from width (keeps aspect)."),output:Yo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Yo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Wg(t){t.registerTool("scale",{title:"Scale Video",description:"Resize a video to a target width and/or height and re-encode. Provide one side to keep the aspect ratio, or both to set an exact size.",inputSchema:_E,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=V(e.input),o=B(e.output,"scale",n,{overwrite:e.overwrite}),i=Pp(e.input,o,{width:e.width,height:e.height});return await W(i,{output:o,durationSec:await se(e.input),extra:r}),v({outputPath:o})}catch(n){return E(n)}})}import{z as Qo}from"zod";import{z as ga}from"zod";function _t(t){if(t.length===0)return"0";if(t.length<=50)return t.join("+");let e=[];for(let r=0;r<t.length;r+=50)e.push(`(${t.slice(r,r+50).join("+")})`);return _t(e)}var Yr=2,Ko=.4,Hn=200;function ba(t,e,r){if(!(e>0))throw new l("minIdleSec must be positive.");return["-hide_banner","-nostats","-v","info","-i",t,"-vf",`freezedetect=n=-60dB:d=${e}`,...r?["-af",`silencedetect=n=-40dB:d=${e}`]:["-an"],"-f","null","-"]}function jg(t,e,r,n){let o=[],i=null;for(let s of t.split(/\r?\n/)){let a=s.match(e);if(a){i=Number(a[1]);continue}let c=s.match(r);c&&i!==null&&(o.push({start:i,end:Number(c[1])}),i=null)}return i!==null&&n>i&&o.push({start:i,end:n}),o}function wa(t,e){return jg(t,/freeze_start:\s*([\d.]+)/,/freeze_end:\s*([\d.]+)/,e)}function ya(t,e){return jg(t,/silence_start:\s*([\d.]+)/,/silence_end:\s*([\d.]+)/,e)}function xa(t,e){let r=[],n=0,o=0;for(;;){let i=t[n],s=e[o];if(!i||!s)break;let a=Math.max(i.start,s.start),c=Math.min(i.end,s.end);c>a&&r.push({start:a,end:c}),i.end<s.end?n++:o++}return r}function Sa(t,e,r){return t.filter(n=>n.end-n.start>=e).map(n=>({start:n.start+r,end:n.end-r})).filter(n=>n.end-n.start>.05).map(n=>({start:Number(n.start.toFixed(3)),end:Number(n.end.toFixed(3))}))}function Qu(t){if(t.length===0)throw new l("Nothing to cut.");if(t.length>Hn)throw new l(`Too many idle stretches (${t.length}); raise minIdleSec.`);let e=_t(t.map(n=>`between(t,${n.start},${n.end})`)),r=_t(t.map(n=>`clip(T-${n.start},0,${Number((n.end-n.start).toFixed(3))})`));return{video:`select='not(${e})',setpts='(T-(${r}))/TB'`,audio:`asetnsamples=n=256:p=0,aselect='not(${e})',asetpts=N/SR/TB`}}var Jr=100,va=ga.object({start:ga.number().min(0),end:ga.number().positive(),factor:ga.number().gt(1).max(Jr)}),Vo=8;function $a(t,e){if(t.length===0)throw new l("segments needs at least one range.");if(t.length>Hn)throw new l(`Too many ranges (${t.length}); at most ${Hn}.`);let r=[...t].sort((n,o)=>n.start-o.start).map(n=>({start:Number(n.start.toFixed(3)),end:Number(n.end.toFixed(3)),factor:n.factor}));return r.forEach((n,o)=>{if(!(n.end>n.start)||n.start<0)throw new l(`Range ${n.start}-${n.end}s: end must be after start, from 0.`);if(!(n.factor>1)||n.factor>Jr)throw new l(`Range ${n.start}-${n.end}s: factor must be above 1 and at most ${Jr} (for slow motion, use factor on the whole clip).`);if(e!==null&&n.start>=e)throw new l(`Range ${n.start}-${n.end}s starts after the video ends (${e}s).`);let i=r[o-1];if(i&&n.start<i.end)throw new l(`Ranges ${i.start}-${i.end}s and ${n.start}-${n.end}s overlap.`)}),r}function Kr(t){return t.reduce((e,r)=>e+(r.end-r.start)*(1-1/r.factor),0)}function ka(t,e){if(t.length===0)throw new l("Nothing to speed up.");let r=s=>Number((1-1/s.factor).toFixed(6)),n=_t(t.map(s=>`clip(T-${s.start},0,${Number((s.end-s.start).toFixed(3))})*${r(s)}`)),o=s=>Number((s.start+(s.end-s.start)/s.factor).toFixed(3)),i=_t(t.map(s=>`between(t,${o(s)},${s.end})`));return{video:`setpts='(T-(${n}))/TB'`+(e?`,fps=${Number(e.toFixed(3))}`:""),audio:`asetnsamples=n=256:p=0,aselect='not(${i})',asetpts=N/SR/TB`}}function Ea(t,e,r,n){let o=ka(r,n.fps);return["-y","-i",t,"-vf",o.video,...n.withAudio?["-af",o.audio]:["-an"],...Se({quality:n.quality??"standard",audio:n.withAudio?"aac":"omit"}),e]}function _a(t,e,r,n,o="standard"){let i=Qu(r);return["-y","-i",t,"-vf",i.video,...n?["-af",i.audio]:["-an"],...Se({quality:o,audio:n?"aac":"omit"}),e]}var TE={input:Qo.string().min(1).describe("Path to the source video."),factor:Qo.number().positive().optional().describe("Whole clip: >1 faster, <1 slower."),segments:Qo.array(va).min(1).optional().describe("Or fast-forward just these ranges (audio shortened, not pitched)."),output:Qo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Qo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ug(t){t.registerTool("speed",{title:"Change Speed",description:"Change playback speed, or fast-forward ranges, and re-encode. Audio is retempo'd to match.",inputSchema:TE,outputSchema:Y,annotations:I},async(e,r)=>{try{if(k(),F(e.input),e.factor===void 0==(e.segments===void 0))throw new l("Pass factor (the whole clip) or segments (ranges), not both.");let{audioCodec:n,durationSec:o,fps:i}=await L(e.input),s=V(e.input),a=B(e.output,"speed",s,{overwrite:e.overwrite}),c=n!==null;if(e.segments){let p=$a(e.segments,o),f=Kr(p);return await W(Ea(e.input,a,p,{withAudio:c,fps:i}),{output:a,durationSec:o!==null?o-f:null,inputDurationSec:o,extra:r}),v({outputPath:a,segments:p,savedSec:Number(f.toFixed(2)),audio:c})}let u=e.factor,d=Ip(e.input,a,u,c);return await W(d,{output:a,durationSec:o!==null?o/u:null,inputDurationSec:o,extra:r}),v({outputPath:a,factor:u,audio:c})}catch(n){return E(n)}})}import{z as dt}from"zod";var AE={input:dt.string().min(1).describe("Path to the base video."),overlay:dt.string().min(1).describe("Overlay image or video path."),x:dt.number().int().nonnegative().describe("Left, px."),y:dt.number().int().nonnegative().describe("Top, px."),width:dt.number().int().positive().optional().describe("Scale to this width (other side keeps aspect)."),height:dt.number().int().positive().optional().describe("Scale to this height."),start:dt.number().nonnegative().optional().describe("Show from this second."),end:dt.number().positive().optional().describe("Hide after this second."),shape:dt.enum(["rect","circle"]).optional().describe("circle: centre square masked round (webcam)."),output:dt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:dt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function zg(t){t.registerTool("overlay",{title:"Overlay Image or Video",description:"Composite an image or video (logo, watermark, picture-in-picture) onto a video at a pixel position, optionally scaled and time-limited; keeps the base's audio and length.",inputSchema:AE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input),F(e.overlay,"Overlay file");let n=V(e.input),o=B(e.output,"overlay",n,{overwrite:e.overwrite}),i=e.width!==void 0||e.height!==void 0?{width:e.width,height:e.height}:void 0,s=await se(e.input),a=Fp(e.input,e.overlay,o,{x:e.x,y:e.y,start:e.start,end:e.end,scale:i,shape:e.shape,durationSec:s});return await W(a,{output:o,durationSec:s,extra:r}),v({outputPath:o})}catch(n){return E(n)}})}import{z as ot}from"zod";import{mkdtempSync as PE,rmSync as IE,writeFileSync as FE}from"node:fs";import{tmpdir as OE}from"node:os";import{join as Jg}from"node:path";var qg=["side_by_side","stack","grid"],Ta=2,Aa=9,Hg=3840,RE=1080,Gg=t=>Math.max(2,Math.round(t/2)*2);function ME(t,e){if(t==="side_by_side")return{cols:e,rows:1};if(t==="stack")return{cols:1,rows:e};let r=Math.ceil(Math.sqrt(e));return{cols:r,rows:Math.ceil(e/r)}}function CE(t,e){let r=Math.min(t.height,RE),n=t.width*r/t.height,o=Math.min(1,Hg/(n*e.cols),Hg/(r*e.rows));return n*=o,r*=o,{width:Gg(n),height:Gg(r)}}function Zu(t,e){let r=t.map(n=>Math.max(0,n.durationSec-n.skipSec));return e==="longest"?Math.max(...r):Math.min(...r)}function Xg(t,e,r){let n=t.length;if(n<Ta||n>Aa)throw new l(`compose takes ${Ta} to ${Aa} inputs.`);let o=t[0],i=ME(r.layout,n),s=CE(o,i),a=Zu(t,r.endWith);if(!(a>0))throw new l("Nothing is left to show after lining the inputs up.");let c=[];t.forEach((m,h)=>{let b=Math.max(0,a-(m.durationSec-m.skipSec)),w=m.label?`,drawtext=fontfile=${ye(m.label.fontFile)}:textfile=${ye(m.label.textFile)}:expansion=none:fontcolor=white:fontsize=${Math.max(14,Math.round(s.height/18))}:x=12:y=12:box=1:boxcolor=black@0.6:boxborderw=8`:"";c.push(`[${h}:v]fps=${r.fps},scale=${s.width}:${s.height}:force_original_aspect_ratio=decrease,pad=${s.width}:${s.height}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,format=yuv420p`+(b>.001?`,tpad=stop_mode=clone:stop_duration=${b.toFixed(3)}`:"")+`${w}[c${h}]`)});let u=t.map((m,h)=>`${h%i.cols*s.width}_${Math.floor(h/i.cols)*s.height}`).join("|");c.push(`${t.map((m,h)=>`[c${h}]`).join("")}xstack=inputs=${n}:layout=${u}:fill=black[v]`);let d=t.map((m,h)=>m.hasAudio?h:-1).filter(m=>m>=0),p=[];if(r.audio==="mix"&&d.length>0)c.push(`${d.map(m=>`[${m}:a]`).join("")}amix=inputs=${d.length}:normalize=0:duration=longest,apad[a]`),p=["-map","[a]"];else if(typeof r.audio=="number"){if(!t[r.audio])throw new l(`audio ${r.audio} is not an input (0-${n-1}).`);if(!t[r.audio].hasAudio)throw new l(`Input ${r.audio} has no audio; pick another, "mix", or "none".`);c.push(`[${r.audio}:a]apad[a]`),p=["-map","[a]"]}let f=p.length>0;return["-y",...t.flatMap(m=>[...m.skipSec>0?["-ss",m.skipSec.toFixed(3)]:[],"-i",m.path]),"-filter_complex",c.join(";"),"-map","[v]",...p,"-t",a.toFixed(3),...Se({quality:r.quality??"standard",audio:f?"aac":"omit"}),e]}var NE={inputs:ot.array(ot.object({path:ot.string().min(1),label:ot.string().min(1).max(80).optional()})).min(Ta).max(Aa).describe('Videos in reading order, each with an optional label (e.g. "Before").'),layout:ot.enum(qg).optional().describe("side_by_side (default), stack, or grid."),alignMarker:ot.string().min(1).optional().describe("Line inputs up on this add_marker label."),endWith:ot.enum(["longest","shortest"]).optional().describe("longest (default; shorter ones hold their last frame) or shortest."),audio:ot.union([ot.number().int().min(0),ot.enum(["mix","none"])]).optional().describe('Input index whose audio to keep (default 0), "mix", or "none".'),output:ot.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ot.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Yg(t){t.registerTool("compose",{title:"Compose Videos",description:"Lay 2-9 videos out side by side, stacked, or in a grid (before/after, app and terminal), labelled and in sync.",inputSchema:NE,outputSchema:Y,annotations:I},async(e,r)=>{let n=PE(Jg(OE(),"screencast-compose-"));try{k();let o=[],i=[];for(let[f,m]of e.inputs.entries()){F(m.path,`Input ${f}`);let h=await L(m.path);if(!h.width||!h.height||h.durationSec===null)throw new l(`Input ${f} has no readable video: ${m.path}`);let b=0;if(e.alignMarker){let g=Le(m.path).find(y=>y.label===e.alignMarker);if(!g)throw new l(`Input ${f} has no marker "${e.alignMarker}".`,"Add one with add_marker, or leave alignMarker out.");b=g.t}let w;if(m.label){let g=vt(m.label);g.warning&&i.push(g.warning);let y=Jg(n,`label${f}.txt`);FE(y,m.label),w={textFile:y,fontFile:g.fontFile}}o.push({path:m.path,width:h.width,height:h.height,durationSec:h.durationSec,hasAudio:h.audioCodec!==null,skipSec:b,label:w})}if(e.alignMarker){let f=Math.min(...o.map(m=>m.skipSec));for(let m of o)m.skipSec-=f}let s=e.endWith??"longest",a=e.audio??(o[0].hasAudio?0:"none"),c=(await L(o[0].path)).fps??30,u=B(e.output,"compose",".mp4",{overwrite:e.overwrite}),d=Xg(o,u,{layout:e.layout??"side_by_side",endWith:s,audio:a,fps:Math.min(60,Math.round(c))}),p=Zu(o,s);return await W(d,{output:u,durationSec:p,extra:r}),v({outputPath:u,durationSec:Number(p.toFixed(2)),layout:e.layout??"side_by_side",...e.alignMarker?{alignedOn:e.alignMarker,skipSec:o.map(f=>Number(f.skipSec.toFixed(3)))}:{},...i.length?{warnings:i}:{}})}catch(o){return E(o)}finally{IE(n,{recursive:!0,force:!0})}})}import{z as Vr}from"zod";import{existsSync as BE,mkdtempSync as WE,readFileSync as jE,rmSync as UE,writeFileSync as zE}from"node:fs";import{tmpdir as HE}from"node:os";import{join as tb}from"node:path";var Vg=["cpu","sysCpu","rssMB","sysMem"],Qg=["top_left","top_right","bottom_left","bottom_right"],DE=120,el={cpu:"App CPU %",sysCpu:"CPU %",rssMB:"App memory MB",sysMem:"Memory %"};function Zg(t,e,r,n=DE){if(!(r>0))throw new l("The video has no duration.");let o=new Array(n).fill(null);for(let s of t){let a=s[e];if(a===void 0||!Number.isFinite(a)||s.t<0||s.t>=r)continue;let c=Math.min(n-1,Math.floor(s.t/r*n));o[c]=Math.max(o[c]??-1/0,a)}let i=null;return o.map(s=>s===null?i:i=s)}function LE(t,e){if(t!=="rssMB")return 100;let r=Math.max(0,...e.map(n=>n??0));return r>0?Math.ceil(r/50)*50:1}var Kg=t=>Math.max(2,Math.round(t/2)*2);function eb(t,e,r,n){let o=Kg(n.width),i=Kg(n.height);if(o>n.videoWidth||i>n.videoHeight)throw new l("The chart is larger than the video.");let s=LE(n.metric,r),a=Math.round(i*.25),c=i-a-4,u=o/r.length,d=r.flatMap((y,$)=>{if(y===null||y<=0)return[];let S=Math.max(1,Math.round(Math.min(y,s)/s*c)),C=n.metric!=="rssMB"&&n.metric!=="sysMem"&&y>=fu;return[`drawbox=x=${Math.floor($*u)}:y=${i-2-S}:w=${Math.max(1,Math.ceil(u))}:h=${S}:color=${C?"0xFF5252":"0x4FC3F7"}@0.95:t=fill`]}),p=Number(n.durationSec.toFixed(3)),f=n.label?`,drawtext=fontfile=${ye(n.label.fontFile)}:textfile=${ye(n.label.textFile)}:expansion=none:fontcolor=white:fontsize=${Math.max(10,Math.round(a*.7))}:x=6:y=${Math.round(a*.15)}`:"",m=Math.round(Math.min(n.videoWidth,n.videoHeight)*.02),h=n.corner.endsWith("left")?m:n.videoWidth-o-m,b=n.corner.startsWith("top")?m:n.videoHeight-i-m,w=[`color=c=0x1E1E1E:s=${o}x${i}:d=${p}:r=30`,"format=yuv420p",...d].join(",")+f,g=`color=c=white:s=2x${i-a}:d=${p}:r=30`;return["-y","-i",t,"-filter_complex",`${w}[c];${g}[p];[c][p]overlay=x='min(${o-2},t/${p}*${o})':y=${a}:shortest=1[g];[0:v][g]overlay=x=${h}:y=${b}:shortest=1[v]`,"-map","[v]","-map","0:a?",...Se({quality:n.quality??"standard",audio:n.hasAudio?"copy":"omit",faststart:!0}),e]}var GE={input:Vr.string().min(1).describe("A recording made with perf: true."),perf:Vr.string().optional().describe("Its .perf.jsonl (default: next to input)."),metric:Vr.enum(Vg).optional().describe("Default cpu (the app's) if sampled, else sysCpu."),corner:Vr.enum(Qg).optional().describe("Default top_right."),width:Vr.number().int().min(80).max(1920).optional().describe("Chart width px (default video/4)."),output:Vr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Vr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function rb(t){t.registerTool("perf_overlay",{title:"Performance Overlay",description:"Draw a recording's CPU or memory track as a small chart with a moving playhead (spikes in red).",inputSchema:GE,outputSchema:Y,annotations:I},async(e,r)=>{let n=WE(tb(HE(),"screencast-perf-"));try{k(),F(e.input);let o=e.perf??xt(e.input);if(!BE(o))throw new l(`No performance track at ${o}.`,"Record with start_recording perf: true, or pass perf.");let i=An(jE(o,"utf8"));if(i.length===0)throw new l(`${o} has no samples.`);let s=await L(e.input);if(!s.width||!s.height||!s.durationSec)throw new l(`Could not read the size and length of ${e.input}.`);let a=e.metric??(i.some(h=>h.cpu!==void 0)?"cpu":"sysCpu"),c=Zg(i,a,s.durationSec);if(c.every(h=>h===null))throw new l(`The track has no ${a} values.`);let u=e.width??Math.max(160,Math.round(s.width/4)),d=vt(el[a]),p=tb(n,"label.txt");zE(p,el[a]);let f=B(e.output,"perf",V(e.input),{overwrite:e.overwrite}),m=eb(e.input,f,c,{metric:a,corner:e.corner??"top_right",width:u,height:Math.round(u*.4),videoWidth:s.width,videoHeight:s.height,durationSec:s.durationSec,label:{textFile:p,fontFile:d.fontFile},hasAudio:s.audioCodec!==null});return await W(m,{output:f,durationSec:s.durationSec,extra:r}),v({outputPath:f,metric:a,samples:i.length})}catch(o){return E(o)}finally{UE(n,{recursive:!0,force:!0})}})}import{z as Gn}from"zod";import{existsSync as qE,readFileSync as XE,writeFileSync as JE}from"node:fs";var tl=2e3,YE={input:Gn.string().min(1).describe("The .srt to translate (e.g. from transcribe)."),language:Gn.string().regex(/^[a-z]{3}$/).optional().describe('With translations: ISO 639-2 code, e.g. "spa".'),translations:Gn.array(Gn.string().max(Ys)).max(tl).optional().describe("One translated string per cue, in order. Omit to get the cues to translate."),output:Gn.string().optional().describe("Default: <input>.<language>.srt."),overwrite:Gn.boolean().optional().describe("Allow replacing an existing output file.")};function nb(t){t.registerTool("translate_subtitles",{title:"Translate Subtitles",description:"Translate an SRT without breaking its timing: call once for the numbered cues, translate them, then call with translations to write <input>.<language>.srt for chapters' subtitleTracks.",inputSchema:YE,annotations:I},async e=>{try{if(F(e.input,"Subtitle file"),!/\.srt$/i.test(e.input))throw new l("input must be an .srt file.");let r=We(XE(e.input,"utf8"));if(r.length===0)throw new l(`No cues in ${e.input}.`);if(r.length>tl)throw new l(`${r.length} cues; at most ${tl} per file.`);if(!e.translations)return v({input:e.input,count:r.length,cues:r.map((i,s)=>`${s+1}. ${i.text.replace(/\s*\n\s*/g," / ")}`),next:`Translate each cue's text (keep " / " as a line break), then call again with language and translations: ${r.length} strings, in order.`});if(!e.language)throw new l('translations needs language (ISO 639-2, e.g. "spa").');let n=Ph(r,e.translations.map(i=>i.replace(/\s+\/\s+/g,`
338
- `))),o=e.output??Ih(e.input,e.language);if(!/\.srt$/i.test(o))throw new l("output must end in .srt.");if(Zt(o),qE(o)){if(!e.overwrite)throw new l(`${o} already exists.`,"Pass overwrite: true to replace it.");wc(o)}return JE(o,nt(n)),v({outputPath:o,language:e.language,count:n.length})}catch(r){return E(r)}})}import{z as Ca}from"zod";import{join as VE}from"node:path";import{mkdtempSync as QE,rmSync as ZE}from"node:fs";import{tmpdir as e_}from"node:os";import{z as xe}from"zod";var qn=(t,e)=>{if(!Number.isFinite(t)||t<0)throw new l(`${e} must be a non-negative number.`);return Math.round(t)};function rl(t){let e=Ii(t.from,t.to);return e?`:enable='${e}'`:""}function ob(t){let e=t.x2-t.x1,r=t.y2-t.y1,n=Math.round(Math.hypot(e,r)),o=Math.max(2,Math.round(t.thickness??8));if(n<o*3)throw new l("An arrow must be at least three times as long as it is thick.");return{length:n,thickness:o,angle:Math.atan2(r,e),cx:(t.x1+t.x2)/2,cy:(t.y1+t.y2)/2}}function ib(t,e){let{length:r,thickness:n,angle:o}=ob(t),i=De(t.color??"red"),s=n*3,a=o.toFixed(6),c=`if(lt(X,W-H),if(lt(abs(Y-H/2),${n}/2),255,0),if(lt(abs(Y-H/2),(W-X)/2),255,0))`;return["-y","-v","error","-f","lavfi","-i",`color=c=${i}:s=${r}x${s}`,"-vf",`format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${c}',rotate=a=${a}:ow=rotw(${a}):oh=roth(${a}):c=none`,"-frames:v","1",...Ee(e)]}function ol(t,e,r,n,o){if(t.length===0)throw new l("Give at least one callout.");let i=[],s=[],a=r;return t.forEach((c,u)=>{let d=`[${o}c${u}]`;if(c.type==="box"){let p=De(c.color??"red"),f=c.fill?"fill":String(Math.max(1,Math.round(c.thickness??4)));s.push(`${a}drawbox=x=${qn(c.x,"x")}:y=${qn(c.y,"y")}:w=${qn(c.width,"width")}:h=${qn(c.height,"height")}:color=${p}:t=${f}${rl(c)}${d}`)}else if(c.type==="text"){let p=e.textFiles[u];if(!p)throw new l("Internal: missing text file for a text callout.");let f=De(c.color??"white"),m=Math.max(8,Math.round(c.size??32)),h=c.background===!1?"":`:box=1:boxcolor=black@0.6:boxborderw=${Math.round(m/3)}`;s.push(`${a}drawtext=fontfile=${ye(e.fontFiles?.[u]??e.fontFile)}:textfile=${ye(p)}:expansion=none:x=${qn(c.x,"x")}:y=${qn(c.y,"y")}:fontsize=${m}:fontcolor=${f}${h}${rl(c)}${d}`)}else{let p=e.arrowFiles[u];if(!p)throw new l("Internal: missing image for an arrow callout.");let{cx:f,cy:m}=ob(c),h=n+i.length/4;i.push("-loop","1","-i",p),s.push(`${a}[${h}:v]overlay=x=${f.toFixed(1)}-w/2:y=${m.toFixed(1)}-h/2:shortest=1${rl(c)}${d}`)}a=d}),{steps:s,out:a,extraInputs:i}}function sb(t,e,r,n,o="standard",i=!1){let s=i?r.map(({from:d,to:p,...f})=>f):r,{steps:a,out:c,extraInputs:u}=ol(s,n,"[0:v]",1,"");return i?["-y","-i",t,...u,"-filter_complex",a.join(";"),"-map",c,"-frames:v","1",...Ee(e)]:["-y","-i",t,...u,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",..._e(o),"-c:a","copy",e]}var nl={from:xe.number().nonnegative().optional(),to:xe.number().positive().optional(),color:xe.string().optional()},vr=xe.string().min(1).optional().describe("Font: a .ttf/.otf/.ttc path or a C:\\Windows\\Fonts file name. Default: bundled Inter, with a covering system font for scripts it lacks (CJK, emoji, Arabic, ...)."),Ra=xe.discriminatedUnion("type",[xe.object({type:xe.literal("box"),x:xe.number(),y:xe.number(),width:xe.number().positive(),height:xe.number().positive(),thickness:xe.number().positive().optional().describe("Outline px (default 4)."),fill:xe.boolean().optional().describe("Fill instead of outline."),...nl}),xe.object({type:xe.literal("text"),x:xe.number(),y:xe.number(),text:xe.string().min(1),size:xe.number().positive().optional().describe("Font size px (default 32)."),background:xe.boolean().optional().describe("Dark panel behind the text (default true)."),...nl}),xe.object({type:xe.literal("arrow"),x1:xe.number(),y1:xe.number(),x2:xe.number().describe("Head (x2,y2) is the point the arrow points at."),y2:xe.number(),thickness:xe.number().positive().optional().describe("Shaft px (default 8)."),...nl})]);import{join as ab}from"node:path";import{writeFileSync as KE}from"node:fs";function il(t,e){let r={fontFiles:[],fallbackFonts:[],warnings:[]};return t.forEach((n,o)=>{if(n.type!=="text"){r.fontFiles.push(null);return}let i=vt(n.text,{weight:"bold",fontFile:e});r.fontFiles.push(i.fontFile),i.fallback&&r.fallbackFonts.push({item:o,fontFile:i.fontFile}),i.warning&&r.warnings.push(`Item ${o}: ${i.warning}`)}),r}async function Ma(t,e,r="",n){let o=il(t,n),i=t.map((a,c)=>{if(a.type!=="text")return null;let u=ab(e,`${r}text_${c}.txt`);return KE(u,a.text),u}),s=[];for(let[a,c]of t.entries()){if(c.type!=="arrow"){s.push(null);continue}let u=ab(e,`${r}arrow_${a}.png`);await Z(ib(c,u),3e4),s.push(u)}return{fontFile:Bt("bold"),textFiles:i,arrowFiles:s,...o}}var t_={input:Ca.string().min(1).describe("Path to the source video or image (png/jpg; from/to are ignored for an image)."),items:Ca.array(Ra).min(1).max(50).describe("Boxes, text labels, and arrows, drawn in order (later on top), in video pixels. Each shows from..to seconds (default: whole video); color is a name, #RRGGBB, or name@alpha."),fontFile:vr,output:Ca.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ca.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function cb(t){t.registerTool("callout",{title:"Add Callouts",description:"Annotate a video or screenshot with timed boxes, text labels, and arrows. Fallback fonts used are listed in fallbackFonts; characters no font covers are reported in warnings.",inputSchema:t_,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.items,{still:o,ext:i}=Oi(e.input,e.output),s=B(e.output,"callout",i,{overwrite:e.overwrite,anyContainer:!0}),a=QE(VE(e_(),"screencast-callout-"));try{let c=await Ma(n,a,"",e.fontFile),u=sb(e.input,s,n,c,void 0,o);return await W(u,{output:s,durationSec:o?null:await se(e.input),extra:r}),v({outputPath:s,callouts:n.length,...c.fallbackFonts.length>0&&{fallbackFonts:c.fallbackFonts},...c.warnings.length>0&&{warnings:c.warnings}})}finally{ZE(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as ei}from"zod";import{join as h_}from"node:path";import{mkdtempSync as g_,rmSync as b_}from"node:fs";import{tmpdir as w_}from"node:os";import{z as zt}from"zod";import{existsSync as r_,readFileSync as n_,writeFileSync as o_}from"node:fs";import{join as i_}from"node:path";var s_=["bottom","bottom-left","bottom-right","top","top-left","top-right"],sl=1.2,a_=.5,ub=8,lb=100,pb="Typing\u2026",c_=new Set(["Ctrl","Alt","Shift","Win"]),u_=/^(?:[A-Z0-9]|F\d{1,2}|Enter|Tab|Esc|Space|Backspace|Delete|Insert|Left|Up|Right|Down|Home|End|PageUp|PageDown|[=\-,./`[\];'\\])$/;function l_(t,e="shortcuts"){let r=t.split("+"),n=r.pop();return n===void 0||r.length===0||!u_.test(n)||!r.every(o=>c_.has(o))||new Set(r).size!==r.length?null:[...r,e==="masked"?"\u2026":n].join(" + ")}var p_={left:"Click",right:"Right click",middle:"Middle click",x1:"Back button",x2:"Forward button"},Pa=t=>Math.round(t*1e3)/1e3;function d_(t,e={}){let r=e.lingerSec??sl;if(!(r>0))throw new l("lingerSec must be positive.");let n=e.keys??"shortcuts",o=[...t].filter(a=>Number.isFinite(a.t)&&a.t>=0).sort((a,c)=>a.t-c.t),i=[];for(let a of o)if(a.type==="key"&&a.keys){let c=l_(a.keys,n);if(!c)continue;let u=i.at(-1);if(u&&u.kind==="shortcut"&&u.base===c&&a.t-u.last<=r){u.count++,u.last=a.t,u.label=`${c} \xD7${u.count}`,u.to=a.t+r;continue}i.push({from:a.t,to:a.t+r,label:c,base:c,kind:"shortcut",count:1,last:a.t})}else if(a.type==="down"&&e.clicks!==!1&&a.inFrame){let c=p_[a.button??"left"]??"Click",u=i.at(-1);if(c==="Click"&&u&&u.kind==="click"&&u.base==="Click"&&u.count<3&&a.t-u.last<=a_&&Math.abs(a.x-(u.x??a.x))<=ub&&Math.abs(a.y-(u.y??a.y))<=ub){u.count++,u.last=a.t,u.label=u.count===2?"Double click":"Triple click",u.to=a.t+r;continue}i.push({from:a.t,to:a.t+r,label:c,base:c,kind:"click",count:1,x:a.x,y:a.y,last:a.t})}else if(a.type==="typing"&&e.typing!==!1){let c=a.t+Math.max(a.durationSec??0,0),u=i.at(-1);if(u&&u.kind==="typing"&&a.t<=u.to){u.to=Math.max(u.to,c+r/2),u.last=a.t;continue}i.push({from:a.t,to:c+r/2,label:pb,base:pb,kind:"typing",count:1,last:a.t})}let s=[];return i.forEach((a,c)=>{let u=i[c+1],d=u?Math.min(a.to,u.from):a.to;d-a.from>=.05&&s.push({from:Pa(a.from),to:Pa(d),label:a.label,kind:a.kind})}),s}function Ia(t){let e=new Map;for(let r of t){let n=e.get(r.label);n||(n={label:r.label,windows:[]},e.set(r.label,n)),n.windows.push([r.from,r.to])}if(e.size>lb)throw new l(`${e.size} different badges is more than ${lb}; trim the video or turn off keys or clicks.`);return[...e.values()]}function m_(t,e){return t.flatMap(r=>{let n=e(r.from,r.to);return n&&n[1]-n[0]>=.05?[{...r,from:Pa(n[0]),to:Pa(n[1])}]:[]})}function db(t,e){return m_(t,(r,n)=>Wr(r,n,e))}function f_(t,e){if(e!==void 0){if(!(e>=8&&e<=400))throw new l("size must be between 8 and 400.");return Math.round(e)}return Math.max(14,Math.round(t*.045))}function al(t,e,r,n,o,i){if(t.length===0)throw new l("No badges to draw.");let s=f_(n.height,r.size),a=Math.round(s/3),c=a+Math.round(s*.6),u=r.position??"bottom",d=u.endsWith("left")?`${c}`:u.endsWith("right")?`w-tw-${c}`:"(w-tw)/2",p=u.startsWith("top")?`${c}`:`h-lh-${c}`,f=De(r.color??"white"),m=[],h=o;return t.forEach((b,w)=>{let g=e.textFiles[b.label];if(!g)throw new l(`Internal: no text file for badge "${b.label}".`);let y=_t(b.windows.map(([S,C])=>`between(t,${S},${C})`)),$=`[${i}k${w}]`;m.push(`${h}drawtext=fontfile=${ye(e.fontFile)}:textfile=${ye(g)}:expansion=none:fontsize=${s}:fontcolor=${f}:box=1:boxcolor=black@0.6:boxborderw=${a}:x=${d}:y=${p}:enable='${y}'${$}`),h=$}),{steps:m,out:h}}function mb(t,e,r,n,o,i,s="standard"){let{steps:a,out:c}=al(r,n,o,i,"[0:v]","");return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",..._e(s),"-c:a","copy",e]}var Fa={events:zt.string().optional(),clicks:zt.boolean().optional(),typing:zt.boolean().optional(),keys:zt.enum(["shortcuts","masked"]).optional(),lingerSec:zt.number().positive().max(10).optional(),position:zt.enum(s_).optional(),size:zt.number().min(8).max(400).optional(),color:zt.string().optional(),fontFile:zt.string().min(1).optional()};function Oa(t,e,r){let n=e??$e(t).jsonl;if(!r_(n))throw new l(`No event log for ${t} (looked for ${n}). Record with start_recording events: true (keys: "shortcuts" to name shortcuts), or pass events: <path to .events.jsonl>.`);let o=je(n_(n,"utf8"));return{badges:d_(o,r),shortcutsLogged:o.filter(i=>i.type==="key").length,path:n}}function Zo(t,e,r="",n){let o=vt(t.join(" "),{weight:"bold",fontFile:n}),i={};return t.forEach((s,a)=>{if(e===null){i[s]=`<badge ${a}>`;return}let c=i_(e,`${r}badge_${a}.txt`);o_(c,s),i[s]=c}),{fontFile:o.fontFile,textFiles:i,...o.fallback&&{fallbackFont:o.fontFile},warnings:o.warning?[o.warning]:[]}}var $r=Fa,y_={input:ei.string().min(1).describe("Path to the recording."),events:$r.events.describe("Event log (default: the input's .events.jsonl)."),clicks:$r.clicks.describe("Show clicks (default true)."),typing:$r.typing.describe('Show typing as "Typing\u2026" (default true).'),keys:$r.keys.describe("shortcuts (default): the chord (Ctrl + S); masked: modifiers only (Ctrl + \u2026)."),lingerSec:$r.lingerSec.describe(`Seconds a badge stays up (default ${sl}).`),position:$r.position.describe("Default bottom (centred)."),size:$r.size.describe("Font px (default 4.5% of the frame height)."),color:$r.color.describe("Text color (default white)."),fontFile:vr,dryRun:ei.boolean().optional().describe("Return the planned badges; write nothing."),output:ei.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ei.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function fb(t){t.registerTool("keystroke_overlay",{title:"Keystroke Overlay",description:"Burn keycast-style badges for shortcuts, clicks, and typing from the recording's input event log (start_recording events: true). Never shows typed text: the log has none.",inputSchema:y_,outputSchema:N({badges:ei.number().int()}),annotations:I},async(e,r)=>{try{k(),F(e.input);let n={clicks:e.clicks,typing:e.typing,keys:e.keys,lingerSec:e.lingerSec},{badges:o,shortcutsLogged:i}=Oa(e.input,e.events,n),s=i===0?'The log names no shortcuts (recorded with keys: "masked"), so only clicks and typing can show.':void 0;if(o.length===0)return v({badges:0,note:"Nothing to show: the log has no clicks, shortcuts, or typing; nothing written."});let a=Ia(o);if(e.dryRun){let p=Zo(a.map(f=>f.label),null,"",e.fontFile);return v({dryRun:!0,badges:o.length,plan:o,...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}let c=await L(e.input);if(!c.height)throw new l(`Could not read the size of ${e.input}.`);let u=B(e.output,"keys",V(e.input),{overwrite:e.overwrite}),d=g_(h_(w_(),"screencast-keys-"));try{let p=Zo(a.map(h=>h.label),d,"",e.fontFile),f={position:e.position,size:e.size,color:e.color},m=mb(e.input,u,a,p,f,{height:c.height});return await W(m,{output:u,durationSec:c.durationSec,extra:r}),v({outputPath:u,badges:o.length,labels:a.map(h=>h.label),...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}finally{b_(d,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as ri}from"zod";import{join as yb}from"node:path";import{mkdtempSync as L_,rmSync as B_,writeFileSync as W_}from"node:fs";import{tmpdir as j_}from"node:os";import{z as Xn}from"zod";import{existsSync as x_,readFileSync as S_}from"node:fs";var ti={w:114,h:168,hotX:9,hotY:9,arrowH:135};function Na(){return vn("cursor","arrow.png")}var v_=.5,cl=2,ul=1.5,$_=.4,hb=240,k_=4,E_=.35,__=new Set(["move","down","up","wheel"]),Jn=t=>Math.round(t*1e3)/1e3;function T_(t){let e=6+(1-t)*34;return{omega:e,lead:Math.min(2/e,.2)}}function A_(t){let e=[],r=fc/1e3;for(let n of t){let o=e.at(-1);o&&n.t-o.t>r*2&&(o.x!==n.x||o.y!==n.y)&&e.push({t:n.t-r,x:o.x,y:o.y}),o&&n.t===o.t?e[e.length-1]=n:e.push(n)}return e}function R_(t,e,r=0){if(t.length===0)return{x:0,y:0,i:0};let n=Math.max(0,Math.min(r,t.length-1));for(;n>0&&t[n].t>e;)n--;for(;n<t.length-1&&t[n+1].t<=e;)n++;let o=t[n],i=t[n+1];if(!i||e<=o.t)return{x:o.x,y:o.y,i:n};let s=(e-o.t)/(i.t-o.t);return{x:o.x+(i.x-o.x)*s,y:o.y+(i.y-o.y)*s,i:n}}function M_(t,e,r,n,o){if(t.length===0)return[];let i=1/hb,s=0,a=w=>{let g=R_(t,w+r,s);return s=g.i,g},c=a(n),u=c.x,d=c.y,p=0,f=0,m=[{t:Jn(n),x:u,y:d}],h=Math.exp(-e*i),b=Math.max(0,Math.ceil((o-n)*hb));for(let w=1;w<=b;w++){let g=Math.min(o,n+w*i),y=a(g),$=u-y.x,S=d-y.y,C=(p+e*$)*i,M=(f+e*S)*i;p=(p-e*C)*h,f=(f-e*M)*h,u=y.x+($+C)*h,d=y.y+(S+M)*h,(w%k_===0||w===b)&&m.push({t:Jn(g),x:u,y:d})}return m}function C_(t,e=E_){if(t.length<=2)return[...t];let r=new Uint8Array(t.length);r[0]=1,r[t.length-1]=1;let n=[[0,t.length-1]];for(;n.length>0;){let[o,i]=n.pop(),s=t[o],a=t[i],c=-1,u=-1;for(let d=o+1;d<i;d++){let p=t[d],f=a.t>s.t?(p.t-s.t)/(a.t-s.t):0,m=Math.hypot(p.x-(s.x+(a.x-s.x)*f),p.y-(s.y+(a.y-s.y)*f));m>c&&(c=m,u=d)}c>e&&(r[u]=1,n.push([o,u],[u,i]))}return t.filter((o,i)=>r[i]===1)}function P_(t){let e=[];for(let r of[...t].sort((n,o)=>n[0]-o[0])){let n=e.at(-1);n&&r[0]<=n[1]?n[1]=Math.max(n[1],r[1]):e.push([r[0],r[1]])}return e}function I_(t,e={},r=null){let n=e.smoothing??v_;if(!(n>=0&&n<=1))throw new l("smoothing must be between 0 and 1.");let o=e.hideAfterSec??cl;if(!(o>=0))throw new l("hideAfterSec must be 0 or more.");let i=t.filter(h=>__.has(h.type)&&Number.isFinite(h.t)&&h.t>=0&&Number.isFinite(h.x)&&Number.isFinite(h.y)).filter(h=>r===null||h.t<=r).sort((h,b)=>h.t-b.t);if(i.length===0)return{path:[],visible:[],clicks:[]};let s=A_(i.map(h=>({t:h.t,x:h.x,y:h.y}))),a=s[0].t,c=s.at(-1).t,u,d=0;if(n===0)u=s.map(h=>({...h})),r!==null&&r>c&&u.push({...s.at(-1),t:r});else{let h=T_(n);d=h.lead;let b=Math.max(0,a-d),w=Math.max(b,r??c+8/h.omega);u=M_(s,h.omega,d,b,w)}let p=Math.max(0,a-d),f=o===0?[[p,r??1/0]]:P_(i.map(h=>[Math.max(0,h.t-d),h.t+o])),m=i.filter(h=>h.type==="down").map(h=>({t:h.t,x:h.x,y:h.y}));return{path:u,visible:f.map(([h,b])=>[Jn(h),r!==null?Math.min(b,r):b]).filter(([h,b])=>b>h),clicks:m}}var F_={sx:1,sy:1,ox:0,oy:0};function Da(t,e=[],r=F_){let n=a=>{let c=ss(a.t,e);return c===null?null:{t:Jn(c),x:a.x*r.sx+r.ox,y:a.y*r.sy+r.oy}},o=[];for(let a of t.path){let c=n(a);c&&(o.length>0&&o.at(-1).t>=c.t?o[o.length-1]={...c,t:o.at(-1).t}:o.push(c))}let i=t.visible.flatMap(([a,c])=>{let u=Wr(a,c,e);return u&&u[1]-u[0]>=.05?[[Jn(u[0]),Number.isFinite(u[1])?Jn(u[1]):u[1]]]:[]}),s=t.clicks.flatMap(a=>{let c=n(a);return c?[c]:[]});return{path:C_(o),visible:i,clicks:s}}var Ce=(t,e=2)=>{let r=Number(t.toFixed(e));return Object.is(r,-0)?"0":String(r)};function gb(t,e,r){let n=Number(r.toFixed(3));return n===0?Ce(t):`${Ce(t)}${n<0?"-":"+"}(t-${Ce(e,3)})*${Ce(Math.abs(n),3)}`}function O_(t,e=ul){if(!(e>=.25&&e<=8))throw new l("size must be between 0.25 and 8.");let r=Math.max(8,t*.025*e),n=r/ti.arrowH,o=Math.max(12,Math.round(r*2.2));return{spriteW:Math.max(2,Math.round(ti.w*n)),spriteH:Math.max(2,Math.round(ti.h*n)),hotX:ti.hotX*n,hotY:ti.hotY*n,ripples:[.45,.72,1].map(i=>Math.max(6,Math.round(o*i/2)*2)),spotRadius:Math.max(24,Math.round(t*.12))}}function N_(t){let e=new Map;for(let r of[...t].sort((n,o)=>n.t-o.t)){let n=Ce(Math.max(0,r.t),3),o=e.get(n)??[];o.push(r.text),e.set(n,o)}return[...e.entries()].map(([r,n])=>`${r} ${n.join(", ")};`).join(`
338
+ `;async function vr(){if(process.platform!=="win32")return{available:!1,language:null,languages:[],error:"The Windows OCR engine is available on Windows only."};try{let t=JSON.parse(await ct(Vk,"OCR languages",{timeoutMs:ur(15e3)})),e=Array.isArray(t.languages)?t.languages:t.languages?[t.languages]:[];return{available:t.available===!0,language:t.language??null,languages:e}}catch(t){return{available:!1,language:null,languages:[],error:z(t)}}}var Qk=["SCREENCAST_HOME","SCREENCAST_ALLOWED_DIRS","FFMPEG_PATH","FFPROBE_PATH","SCREENCAST_WHISPER_MODEL","SCREENCAST_MAX_RECORDING_SEC","SCREENCAST_JOB_TIMEOUT_MS","SCREENCAST_PS_TIMEOUT_MS","SCREENCAST_RETENTION_DAYS","SCREENCAST_CONFIRM_CAPTURE","SCREENCAST_TOOLSETS","SCREENCAST_DEBUG_JOBS"],Zk=[{name:"SCREENCAST_MAX_RECORDING_SEC",ok:t=>Number.isInteger(t)&&t>=0&&t<=168*3600,want:"an integer from 0 (no cap) to 604800",otherwise:"start_recording fails until it is fixed"},{name:"SCREENCAST_JOB_TIMEOUT_MS",ok:t=>Number.isInteger(t)&&t>0,want:"a positive integer (milliseconds)",otherwise:"edits use the default timeout"},{name:"SCREENCAST_PS_TIMEOUT_MS",ok:t=>Number.isInteger(t)&&t>0,want:"a positive integer (milliseconds)",otherwise:"the PowerShell helpers use their default limits"},{name:"SCREENCAST_RETENTION_DAYS",ok:t=>Number.isFinite(t)&&t>=0,want:"a number of days (0 = off)",otherwise:"nothing is pruned"}],eE=["auto","1","true","yes","on","always","0","false","no","off","never"];function bg(t=process.env){let e=[];for(let n of Zk){let o=t[n.name];o===void 0||o.trim()===""||n.ok(Number(o.trim()))||e.push(`${n.name}="${o}" is not ${n.want}, so ${n.otherwise}.`)}let r=t.SCREENCAST_CONFIRM_CAPTURE;return r!==void 0&&r.trim()!==""&&!eE.includes(r.trim().toLowerCase())&&e.push(`SCREENCAST_CONFIRM_CAPTURE="${r}" is not auto, always (1/true/yes/on) or off (0/false/no/never), so captures follow auto.`),e}function wg(t=process.env){return Object.fromEntries(Qk.map(e=>{let r=t[e];return[e,r&&r.trim().length>0?r:null]}))}var yg=[{filter:"whisper",tools:"transcribe",why:`FFmpeg ${Yr}+ built with whisper.cpp`},{filter:"gfxcapture",tools:'backend: "wgc" (screenshot, start_recording, find_text)',why:`FFmpeg ${Yr}+ on Windows`},{filter:"subtitles",tools:"burn_subtitles",why:"libass"},{filter:"drawtext",tools:"title_card, callout, contact_sheet labels, produce",why:"libfreetype"},{filter:"afftdn",tools:"denoise",why:"a standard build"},{filter:"loudnorm",tools:"normalize_audio",why:"a standard build"},{filter:"xfade",tools:"xfade_transition, assemble_highlights",why:"FFmpeg 4.3+"}];var qu=8,sE={input:$r.string().optional().describe("Recording path."),sessionId:$r.string().optional().describe("Or a stopped session id."),sceneThreshold:$r.number().gt(0).lt(1).optional().describe(`Change starting a segment (default ${Nu}).`),maxFrames:$r.number().int().min(1).max(Xf).optional().describe(`Keyframes to OCR (default ${Du}).`),transcript:$r.string().optional().describe("An .srt, or 'whisper' to transcribe. Default: <video>.srt if any."),force:$r.boolean().optional().describe("Re-OCR despite a matching cached index.")};function xg(t){t.registerTool("index_recording",{title:"Index Recording",description:"Build a recording's text timeline (<video>.index.json: OCR per scene, events, markers, transcript) for search_recording.",inputSchema:sE,outputSchema:B({indexPath:$r.string(),segments:$r.number()}),annotations:I},async(e,r)=>{let n=nE(Gu(iE(),"screencast-index-"));try{let{ffmpeg:o}=k(),i=await qs(e),s=await W(i.path),a=s.videoDurationSec??s.durationSec;if(!s.width||a===null||!(a>0))throw new l(`Could not read the video size and duration of ${i.path}.`);let c=e.sceneThreshold??Nu,u=e.maxFrames??Du,d=we("edits"),p=Yf(i.path,d),f=Hs(i.path),m=$o(r),h=[],b=e.force?null:js(i.path,d,f),w=b?jo(b):null,g=null,y=async()=>g??=process.platform==="win32"&&(await vr()).available,v=Kf(w,{fingerprint:f,sceneThreshold:c,maxFrames:u,ocrAvailable:w!==null&&!w.ocr?await y():!1}),x,R=0,T=!1;if(v)x=w.segments,R=w.framesRead,T=w.ocr;else{let Y=await se(o,ir(i.path,c),pe(a),{signal:r.signal});if(Y.code!==0)throw new l(`Scene scan failed (exit ${Y.code}): ${Y.stderr.trim().slice(-400)}`);m?.(.1);let q=Zf(Qf(sr(Y.stdout),a,u),a),Q=q.map(()=>[]);if(T=await y(),T)for(let J=0;J<q.length;J+=qu){r.signal.throwIfAborted();let N=q.slice(J,J+qu),X=(await qe(N,async(ie,_)=>{let P=Gu(n,`key_${J+_}.png`);return await te(wn(i.path,zs(ie),P),6e4,{signal:r.signal}),{at:J+_,path:P}})).filter(ie=>Bn(ie.path)),ee=X.length>0?await lt(X.map(ie=>ie.path),n,r.signal,{sameSize:!0}):[];ee.forEach((ie,_)=>Q[X[_].at]=ie.lines.map(P=>P.text)),R+=ee.length,m?.(.1+.85*Math.min(q.length,J+qu)/q.length)}else h.push("Windows OCR is not available, so the index holds no screen text; install an OCR language (doctor).");let $=q.map((J,N)=>({...J,ocr:Q[N]??[]}));x=T?eh($):$}x=Vf(x);let M=i.eventsPath?th(ze(Wn(i.eventsPath,"utf8"))):[];x=Jr(x,M,"events"),x=Jr(x,rh(i.markers),"markers");let H=vt(i.path);if(Bn(H)){let Y=Cn(Wn(H,"utf8")),{busy:q}=Mn(Y),Q=q.map($=>{let J=Math.max(...Y.filter(N=>N.t>=$.start&&N.t<=$.end).map(N=>N.cpu??N.sysCpu));return{t:$.start,text:`cpu pinned ${Math.round(J)}% for ${Math.round($.end-$.start)} s (performance spike)`}});Q.length&&(x=Jr(x,[...x.flatMap($=>$.events??[]),...Q],"events"))}let G=jt(i.path);if(Bn(G)){let Y=Es(Wn(G,"utf8")),q=Le(Y.map(Q=>`${Q.source}: ${Q.line}`),De);x=Jr(x,Y.map((Q,$)=>({t:Q.t,text:q[$]??""})),"logs")}let L=await aE(e.transcript,i.path,s.audioCodec!==null,a,r.signal,h);if(L!==null)x=Jr(x,nh(L),"transcript");else if(v&&w){let Y=w.segments.flatMap(q=>q.transcript??[]);x=Jr(x,Y,"transcript")}let C={version:Ou,video:i.path,fingerprint:f,durationSec:a,createdAt:new Date().toISOString(),sceneThreshold:c,maxFrames:u,framesRead:R,ocr:T,segments:x};rE(Gu(p,".."),{recursive:!0}),oh(p,C);let ne=Lu(i.path);if(ne!==p&&Bn(ne)){let Y=jo(ne);Y&&Bs(Y,i.path,f)&&Xu(ne,{force:!0})}m?.(1);let V=Y=>x.reduce((q,Q)=>q+(Q[Y]?.length??0),0);return S({indexPath:p,segments:x.length,cached:v,framesRead:R,durationSec:a,sources:{screenLines:x.reduce((Y,q)=>Y+q.ocr.length,0),events:V("events"),markers:V("markers"),transcriptCues:V("transcript")},...h.length>0?{note:h.join(" ")}:{},next:"search_recording { query } returns timecoded hits. Secret-shaped screen text is stored masked; the rest of the index is plain text, so treat it like the video."})}catch(o){return E(o)}finally{Xu(n,{recursive:!0,force:!0})}})}async function aE(t,e,r,n,o,i){if(t==="whisper"){if(!r)return i.push("The recording has no audio, so there is no transcript."),null;if(!Ve("whisper"))throw new l("This ffmpeg has no whisper filter.","transcript: 'whisper' needs FFmpeg 8 built with whisper.cpp; or pass an .srt.");let c=Sr(void 0),u=He(".srt");try{return await te(Dn(e,c,u),pe(n),{signal:o}),Bn(u)?pt(Ue(Wn(u,"utf8"))):[]}finally{Xu(u,{force:!0})}}if(t!==void 0){if(!Bn(t))throw new l(`Transcript not found: ${t}`);return pt(Ue(Wn(t,"utf8")))}let s;try{s=oE(tE(e))}catch{return null}let a=Us(e,s);return a.ambiguous&&i.push("Another video in the folder shares this one's base name, so its .srt was not attached; pass transcript."),a.path?pt(Ue(Wn(a.path,"utf8"))):null}import{z as Ht}from"zod";import{join as Sg}from"node:path";import{existsSync as vg,mkdtempSync as cE,rmSync as uE}from"node:fs";import{tmpdir as lE}from"node:os";var pE=480,dE={input:Ht.string().optional().describe("Recording path."),sessionId:Ht.string().optional().describe("Or a stopped session id."),query:Ht.string().min(1).describe("Text; tolerates OCR misreads."),regex:Ht.boolean().optional().describe("query is a regex."),limit:Ht.number().int().min(1).max(Jf).optional().describe(`Max hits (default ${Ls}).`),images:Ht.number().int().min(0).max(Ho).optional().describe("Thumbnails of the top N hits (default 0).")};function $g(t){t.registerTool("search_recording",{title:"Search Recording",description:"Search an index_recording timeline (screen text, events, markers, transcript): timecoded hits, best first, secrets masked. No frames unless asked. No input: search all indexes.",inputSchema:dE,outputSchema:B({total:Ht.number(),hits:Ht.array(Ht.unknown())}),annotations:fe},async(e,r)=>{try{if(e.input===void 0&&e.sessionId===void 0){if((e.images??0)>0)throw new l("images needs one recording.","Pass input or sessionId, or search the library with images: 0.");let f=sh(Pe()).flatMap(b=>{let w=Bu(b);return w?[{indexPath:b,index:w}]:[]}),m=ah(f,e.query,{regex:e.regex===!0,limit:e.limit}),h=m.recordings.map(b=>({...b,...vg(b.video)?{}:{missing:!0}}));return S({query:e.query,searched:m.searched,total:m.total,hits:m.hits,recordings:h,...m.searched===0?{note:"No indexed recordings under SCREENCAST_HOME; run index_recording first."}:{}})}let n=await qs(e),o=Hs(n.path),i=js(n.path,we("edits"),o),s=i?Bu(i):null;if(!i||!s)throw new l(`No index for ${n.path}.`,"Run index_recording on it first.");let a=!Gs(s.fingerprint,o),{hits:c,total:u}=Wu(s,e.query,{regex:e.regex===!0,limit:e.limit,video:n.path,fingerprint:o}),d=Math.min(ta(e.images??0),c.length),p=[];if(d>0){k();let f=cE(Sg(lE(),"screencast-search-"));try{let m=[];for(let[h,b]of c.slice(0,d).entries()){let w=b.t===b.start?zs(b):b.t,g=Sg(f,`hit_${h}.png`);await te(wn(n.path,w,g),6e4,{signal:r.signal}),vg(g)&&m.push(g)}p=(await Ce(m,pE,d)).images}finally{uE(f,{recursive:!0,force:!0})}}return S({indexPath:i,query:e.query,total:u,hits:c,...u>c.length?{more:u-c.length}:{},...s.ocr?{}:{note:"The index has no screen text (OCR was unavailable when it was built)."},...a?{stale:!0,warning:"The recording changed since it was indexed; run index_recording again."}:{}},p)}catch(n){return E(n)}})}import{z as kr}from"zod";var mE={input:kr.string().min(1).describe("Path to the media file to probe.")};function kg(t){t.registerTool("get_media_info",{title:"Get Media Info",description:"Probe a media file with ffprobe and return duration, resolution, frame rate, codecs, container format, and size.",inputSchema:mE,outputSchema:B({input:kr.string(),durationSec:kr.number().nullable(),width:kr.number().nullable(),height:kr.number().nullable(),fps:kr.number().nullable(),videoCodec:kr.string().nullable(),audioCodec:kr.string().nullable()}),annotations:fe},async e=>{try{return O(e.input),S({input:e.input,...await W(e.input)})}catch(r){return E(r)}})}import{z as Kr}from"zod";import{extname as fE}from"node:path";var hE={input:Kr.string().min(1).describe("Path to the source video."),start:Kr.number().nonnegative().describe("Start time in seconds."),end:Kr.number().positive().optional().describe("End time in seconds. Use end OR duration."),duration:Kr.number().positive().optional().describe("Clip length in seconds. Use end OR duration."),exact:Kr.boolean().optional().describe("Re-encode for a frame-exact cut with the removed content really gone (default true). false = fast stream copy that snaps to a keyframe and keeps hidden earlier frames; never use it to remove secrets."),output:Kr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Kr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Eg(t){t.registerTool("trim",{title:"Trim Video",description:"Cut a video down to one sub-clip by start + (end or duration). For several segments use clip; to combine with other edits use pipeline.",inputSchema:hE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=e.exact===!1?fE(e.input)||".mp4":Z(e.input),o=j(e.output,"trim",n,{overwrite:e.overwrite,anyContainer:e.exact===!1}),i=Rp(e.input,o,{start:e.start,end:e.end,duration:e.duration,exact:e.exact}),s=e.start??0,a=e.end??await ue(e.input),c=e.duration??(a!==null?a-s:null);return await U(i,{output:o,durationSec:c,extra:r}),S({outputPath:o})}catch(n){return E(n)}})}import{z as ma}from"zod";import{extname as vE,resolve as $E}from"node:path";import{writeFileSync as kE,rmSync as EE}from"node:fs";var gE=1920,bE=1080,_g=30,Tg=48e3,jn=1,Ju="standard";function Yu(t){return Math.round(t*1e3)/1e3}function Rg(t){return t.width!==void 0&&or(t.width,"width"),t.height!==void 0&&or(t.height,"height"),{w:t.width??gE,h:t.height??bE}}function wE(t,e,r){return`scale=${t}:${e}:force_original_aspect_ratio=decrease,pad=${t}:${e}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${r},format=yuv420p`}function yE(t){return`aresample=${t},aformat=sample_fmts=fltp:channel_layouts=stereo`}function xE(t,e){let r=[],n=0;for(let[o,i]of t.slice(0,-1).entries())n+=i,r.push(Math.max(0,Yu(n-(o+1)*e)));return r}function Vr(t){return t.videoDurationSec??t.durationSec}function Ag(t,e,r,n,o={},i=[!1,!1]){let s=vc(o.transition??"fade"),a=o.duration??jn;if(!Number.isFinite(a)||a<=0)throw new l("transition duration must be a positive number.");if(!Number.isFinite(r[0])||r[0]<=a)throw new l(`first clip (${r[0]}s) must be longer than the transition (${a}s).`);return Yo([t,e],r,n,{...o,transition:s},i)}function Yo(t,e,r,n={},o=[]){if(t.length<2)throw new l("assemble_highlights requires at least two clips.");let{w:i,h:s}=Rg(n),a=n.fps??_g,c=n.audioRate??Tg,u=n.transition??"cut",d=n.duration??jn,p=t.length,f=wE(i,s,a),m=yE(c),h=o.some(Boolean),b=[];for(let g=0;g<p;g++)if(b.push(`[${g}:v]${f}[v${g}]`),!!h)if(o[g]){let y=e[g]??Number.NaN,v=Number.isFinite(y)&&y>0?`,apad,atrim=duration=${Yu(y)}`:"";b.push(`[${g}:a]${m}${v}[a${g}]`)}else{let y=e[g]??Number.NaN;if(!Number.isFinite(y)||y<=0)throw new l(`clip ${g} has no audio track and its duration is unknown, so a matching silent track cannot be generated.`);b.push(`anullsrc=channel_layout=stereo:sample_rate=${c}:d=${y}[a${g}]`)}let w=[];if(u==="cut")if(h){let g=t.map((y,v)=>`[v${v}][a${v}]`).join("");b.push(`${g}concat=n=${p}:v=1:a=1[vout][aout]`),w.push("-map","[vout]","-map","[aout]")}else{let g=t.map((y,v)=>`[v${v}]`).join("");b.push(`${g}concat=n=${p}:v=1:a=0[vout]`),w.push("-map","[vout]")}else{if(vc(u),e.length!==p)throw new l(`a ${u} transition needs a duration for each of the ${p} clips.`);if(!Number.isFinite(d)||d<=0)throw new l("transition duration must be a positive number.");let g=e.findIndex(x=>!Number.isFinite(x)||x<=d);if(g!==-1)throw new l(`clip ${g} (${e[g]}s) must be longer than the ${d}s ${u} transition. Use a shorter transition or trim fewer frames.`);let y=xE(e,d),v="v0";for(let x=1;x<p;x++){let R=x===p-1?"vout":`vx${x}`;b.push(`[${v}][v${x}]xfade=transition=${u}:duration=${d}:offset=${y[x-1]}[${R}]`),v=R}if(w.push("-map","[vout]"),h){let x="a0";for(let R=1;R<p;R++){let T=R===p-1?"aout":`ax${R}`;b.push(`[${x}][a${R}]acrossfade=d=${d}[${T}]`),x=T}w.push("-map","[aout]")}}return["-y",...t.flatMap(g=>["-i",g]),"-filter_complex",b.join(";"),...w,...Se({quality:n.quality??Ju,audio:h?"aac":"none",faststart:!0}),r]}var Ku=3;function Mg(t,e,r,n={}){let{w:o,h:i}=Rg(n),s=n.duration??Ku,a=n.fps??_g,c=Be(n.bg??"black","bg"),u=Be(n.fontColor??"white","fontColor"),d=n.fontSize??96;if(!Number.isFinite(s)||s<=0)throw new l("title duration must be a positive number.");if(!Number.isInteger(d)||d<=0)throw new l("fontSize must be a positive integer.");let p=`drawtext=fontfile=${ye(e)}:textfile=${ye(t)}:expansion=none:fontcolor=${u}:fontsize=${d}:x=(w-text_w)/2:y=(h-text_h)/2:shadowcolor=black@0.5:shadowx=2:shadowy=2`;return["-y","-f","lavfi","-i",`color=c=${c}:s=${o}x${i}:d=${s}:r=${a}`,"-f","lavfi","-i","anullsrc=channel_layout=stereo:sample_rate=48000","-vf",p,"-shortest",...Se({quality:n.quality??Ju,audio:"aac",faststart:!0}),r]}function Cg(t,e,r,n,o,i={}){if(!Number.isFinite(n)||n<=0)throw new l("video duration must be known and positive.");let s=i.musicVolume??(o?.25:.8),a=i.fadeIn??1,c=i.fadeOut??2;for(let[h,b]of[[s,"musicVolume"],[a,"fadeIn"],[c,"fadeOut"]])if(!Number.isFinite(h)||h<0)throw new l(`${b} must be a non-negative number.`);let u=i.duck??!1,d=Math.max(0,Yu(n-c)),p=`[1:a]afade=t=in:st=0:d=${a},afade=t=out:st=${d}:d=${c},volume=${s}`,f="amix=inputs=2:duration=first:dropout_transition=0:normalize=0",m=[];return o?(m.push(`${p}[music]`),u?(m.push("[music][0:a]sidechaincompress=threshold=0.03:ratio=8:attack=20:release=300[ducked]"),m.push(`[0:a][ducked]${f}[aout]`)):m.push(`[0:a][music]${f}[aout]`)):m.push(`${p}[aout]`),["-y","-i",t,"-stream_loop","-1","-i",e,"-filter_complex",m.join(";"),"-map","0:v","-map","[aout]","-t",String(n),...Se({video:["-c:v","copy"],audio:"aac",bitrate:"192k",faststart:!0}),r]}var Un=["16:9","9:16","1:1","4:5"],la=["pad","crop"],zn={"16:9":{w:1920,h:1080},"9:16":{w:1080,h:1920},"1:1":{w:1080,h:1080},"4:5":{w:1080,h:1350}};function pa(t,e,r){return r==="crop"?`scale=${t}:${e}:force_original_aspect_ratio=increase,crop=${t}:${e},setsar=1`:`scale=${t}:${e}:force_original_aspect_ratio=decrease,pad=${t}:${e}:(ow-iw)/2:(oh-ih)/2,setsar=1`}function Pg(t,e,r,n="pad",o=Ju){let i=zn[r];if(!i)throw new l(`Unknown aspect "${r}".`);return["-y","-i",t,"-vf",`${pa(i.w,i.h,n)},format=yuv420p`,...Se({quality:o,audio:"copy",faststart:!0}),e]}var da=["youtube","instagram_reel","tiktok","x","square","steam_trailer","vertical_reel"],Vu={youtube:{aspect:"16:9",fps:30,videoBitrate:"8M",bufsize:"16M",audioBitrate:"192k"},instagram_reel:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},tiktok:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},x:{aspect:"16:9",fps:30,videoBitrate:"5M",bufsize:"10M",audioBitrate:"128k"},square:{aspect:"1:1",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k"},steam_trailer:{aspect:"16:9",fps:30,videoBitrate:"5.5M",bufsize:"11M",audioBitrate:"192k",cbr:!0,loudness:{sampleRate:48e3}},vertical_reel:{aspect:"9:16",fps:30,videoBitrate:"6M",bufsize:"12M",audioBitrate:"160k",blurFill:!0,loudness:{}}};function SE(t,e,r=""){return`split=2[${r}bg][${r}fg];[${r}bg]scale=${t}:${e}:force_original_aspect_ratio=increase,crop=${t}:${e},boxblur=20:2,eq=brightness=-0.08[${r}b];[${r}fg]scale=${t}:${t}:force_original_aspect_ratio=decrease:force_divisible_by=2[${r}f];[${r}b][${r}f]overlay=(W-w)/2:(H-h)/2,setsar=1`}function Qu(t,e="pad",r=""){let n=Vu[t];if(!n)throw new l(`Unknown platform "${t}".`);let o=zn[n.aspect],i=n.blurFill?SE(o.w,o.h,r):pa(o.w,o.h,e),s=n.loudness?`loudnorm=I=-14:TP=-1:LRA=11,aresample=${n.loudness.sampleRate??Tg}`:void 0;return{vf:`${i},fps=${n.fps},format=yuv420p`,...s?{af:s}:{},encode:["-c:v","libx264","-preset","medium",...n.cbr?["-profile:v","high"]:[],"-b:v",n.videoBitrate,...n.cbr?["-minrate",n.videoBitrate,"-x264-params","nal-hrd=cbr"]:[],"-maxrate",n.videoBitrate,"-bufsize",n.bufsize,"-pix_fmt","yuv420p",...Nr(n.audioBitrate),...n.loudness?.sampleRate?["-ar",String(n.loudness.sampleRate),"-ac","2"]:[],"-r",String(n.fps),...Dr],width:o.w,height:o.h}}function Ig(t,e,r,n="pad"){let{vf:o,af:i,encode:s}=Qu(r,n);return["-y","-i",t,"-vf",o,...i?["-af",i]:[],...s,e]}var _E={inputs:ma.array(ma.string().min(1)).min(2).describe("Video paths to join, in order."),output:ma.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ma.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Fg(t){t.registerTool("concat",{title:"Concatenate Videos",description:"Join videos end to end with hard cuts: stream copy when they match, else a re-encode (`mode` says which). For transitions use xfade_transition or assemble_highlights.",inputSchema:_E,outputSchema:K,annotations:I},async(e,r)=>{try{k();let n=e.inputs.map(m=>$E(m));for(let m of n)O(m);let o=await Promise.all(n.map(m=>W(m))),[i]=n,[s]=o;if(i===void 0||s===void 0)throw new l("concat needs at least two inputs.");let a=o.map(m=>Vr(m)),c=a.every(m=>m!==null)?a.reduce((m,h)=>m+h,0):null,u=Mp(n,o);if(u!==null){let m=j(e.output,"concat",Z(i),{overwrite:e.overwrite}),h=w=>w!==null&&w>=2?w-w%2:void 0,b=Yo(n,a.map(w=>w??0),m,{transition:"cut",width:h(s.width),height:h(s.height),fps:s.fps??void 0},o.map(w=>w.audioCodec!==null));return await U(b,{output:m,durationSec:c,extra:r}),S({outputPath:m,inputCount:n.length,mode:"reencode",reason:u})}let d=vE(i)||".mp4",p=j(e.output,"concat",d,{overwrite:e.overwrite,anyContainer:!0}),f=He(".txt");kE(f,Ap(n));try{await U(yn(f,p),{output:p,durationSec:c,extra:r})}finally{EE(f,{force:!0})}return S({outputPath:p,inputCount:n.length,mode:"copy"})}catch(n){return E(n)}})}import{z as Hn}from"zod";var TE={input:Hn.string().min(1).describe("Path to the source media."),format:Hn.enum(["mp4","gif","webm"]).describe("mp4 (H.264), webm (VP9), or gif (palette)."),fps:Hn.number().positive().optional().describe("gif only: fps (default 12)."),width:Hn.number().positive().optional().describe("gif only: width in px (default 720)."),output:Hn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Hn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Og(t){t.registerTool("convert",{title:"Convert Format",description:"Convert media to mp4, webm, or gif. For a size-bounded GIF/WebP prefer export_gif; for a smaller mp4, compress or export_preset.",inputSchema:TE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=e.format,o=j(e.output,"convert",`.${n}`,{overwrite:e.overwrite,anyContainer:!0}),i=Cp(e.input,o,n,{fps:e.fps,width:e.width});return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o,format:n})}catch(n){return E(n)}})}import{z as Gt}from"zod";var fa=12,ha=960,Er=1e7,Ng=5;function Dg(t,e,r){return(t==="gif"?[[1,1,256],[.83,.8,256],[.67,.67,128],[.5,.5,64],[.4,.4,32],[.33,.33,16]]:[[1,1,75],[.83,.8,65],[.67,.67,55],[.5,.5,45],[.4,.4,35],[.33,.33,25]]).map(([o,i,s])=>({fps:Math.max(1,Math.round(e*o*10)/10),width:Math.max(64,Math.round(r*i/2)*2),...t==="gif"?{colors:s}:{quality:s}}))}function Lg(t,e,r,n){let o=n-1;if(t>=o)return null;let i=Math.max(1,Math.ceil(Math.log(e/r)/Math.log(1.8)));return Math.min(o,t+i)}function Bg(t,e,r,n,o={}){if(!(n.fps>0)||!Number.isInteger(n.width)||n.width<16)throw new l("fps must be positive and width an integer of at least 16.");if(o.start!==void 0&&!(o.start>=0))throw new l("start must be >= 0.");if(o.duration!==void 0&&!(o.duration>0))throw new l("duration must be > 0.");let i=[...o.start?["-ss",String(o.start)]:[],...o.duration?["-t",String(o.duration)]:[]],s=`fps=${n.fps},scale='min(${n.width},iw)':-1:flags=lanczos`;if(r==="gif"){let a=n.colors??256;return["-y",...i,"-i",t,"-an","-vf",`${s},split[a][b];[a]palettegen=stats_mode=diff:max_colors=${a}[p];[b][p]paletteuse=dither=sierra2_4a:diff_mode=rectangle`,"-loop","0",e]}return["-y",...i,"-i",t,"-an","-vf",s,"-c:v","libwebp_anim","-lossless","0","-q:v",String(n.quality??75),"-compression_level","4","-loop","0",e]}import{basename as RE,dirname as AE,extname as ME,join as CE}from"node:path";import{renameSync as PE,rmSync as IE,statSync as FE}from"node:fs";async function Gn(t,e,r,n){let o=r.format??"gif",i=r.maxBytes??Er,s=await ue(t),a=r.duration??(s!==null?s-(r.start??0):null),c=Dg(o,r.fps??fa,r.width??ha),u=ME(e),d=f=>CE(AE(e),`${RE(e,u)}.try${f}${u}`),p=[];try{let f=0;for(;f!==null&&p.length<Ng;){let b=c[f];if(!b)break;let w=d(p.length),g={start:r.start,duration:r.duration};await U(Bg(t,w,o,b,g),{output:w,durationSec:a,extra:n});let y=FE(w).size;if(p.push({path:w,size:y,settings:b}),y<=i)break;f=Lg(f,y,i,c.length)}let m=p.find(b=>b.size<=i),h=m??p.reduce((b,w)=>w.size<b.size?w:b);return PE(h.path,e),{outputPath:e,format:o,sizeBytes:h.size,maxBytes:i,withinBudget:h.size<=i,settings:h.settings,attempts:p.map(b=>({...b.settings,sizeBytes:b.size})),...m?{}:{note:`Could not get under ${i} bytes; kept the smallest attempt. Export a shorter clip (start/duration), or try format: 'webp'.`}}}finally{for(let f of p)IE(f.path,{force:!0})}}var OE={input:Gt.string().min(1).describe("Path to the source video."),format:Gt.enum(["gif","webp"]).optional().describe("gif (default) or webp (usually much smaller)."),maxBytes:Gt.number().int().min(1e4).optional().describe(`Size budget in bytes (default ${Er}, under GitHub's 10 MB image limit).`),fps:Gt.number().positive().max(30).optional().describe(`Starting frame rate (default ${fa}).`),width:Gt.number().int().min(64).max(1920).optional().describe(`Starting width in px (default ${ha}).`),start:Gt.number().nonnegative().optional().describe("Start second."),duration:Gt.number().positive().optional().describe("Seconds to export (default: to the end)."),output:Gt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Gt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Wg(t){t.registerTool("export_gif",{title:"Export GIF or WebP",description:"Export an animated GIF or WebP that fits a size budget (for PRs, issues, READMEs), stepping fps, width, and quality down until it fits.",inputSchema:OE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=e.format??"gif",o=e.maxBytes??Er,i=j(e.output,"anim",`.${n}`,{overwrite:e.overwrite,anyContainer:!0});return S(await Gn(e.input,i,{format:n,maxBytes:o,fps:e.fps,width:e.width,start:e.start,duration:e.duration},r))}catch(n){return E(n)}})}import{z as Qr}from"zod";var NE={input:Qr.string().min(1).describe("Path to the source video."),x:Qr.number().int().nonnegative(),y:Qr.number().int().nonnegative(),width:Qr.number().int().positive(),height:Qr.number().int().positive(),output:Qr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Qr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function jg(t){t.registerTool("crop",{title:"Crop Video",description:"Crop a video to a pixel rectangle; one running off the frame is rejected.",inputSchema:NE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let{width:n,height:o,durationSec:i}=await W(e.input),s=Z(e.input),a=j(e.output,"crop",s,{overwrite:e.overwrite}),c=Pp(e.input,a,{x:e.x,y:e.y,width:e.width,height:e.height},{width:n,height:o});return await U(c,{output:a,durationSec:i,extra:r}),S({outputPath:a})}catch(n){return E(n)}})}import{z as Ko}from"zod";var DE={input:Ko.string().min(1).describe("Path to the source video."),width:Ko.number().int().positive().optional().describe("Target width in px. Omit to derive from height (keeps aspect)."),height:Ko.number().int().positive().optional().describe("Target height in px. Omit to derive from width (keeps aspect)."),output:Ko.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ko.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ug(t){t.registerTool("scale",{title:"Scale Video",description:"Resize a video to a target width and/or height and re-encode. Provide one side to keep the aspect ratio, or both to set an exact size.",inputSchema:DE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=Z(e.input),o=j(e.output,"scale",n,{overwrite:e.overwrite}),i=Fp(e.input,o,{width:e.width,height:e.height});return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o})}catch(n){return E(n)}})}import{z as Zo}from"zod";import{z as ga}from"zod";function At(t){if(t.length===0)return"0";if(t.length<=50)return t.join("+");let e=[];for(let r=0;r<t.length;r+=50)e.push(`(${t.slice(r,r+50).join("+")})`);return At(e)}var en=2,Vo=.4,qn=200;function ba(t,e,r){if(!(e>0))throw new l("minIdleSec must be positive.");return["-hide_banner","-nostats","-v","info","-i",t,"-vf",`freezedetect=n=-60dB:d=${e}`,...r?["-af",`silencedetect=n=-40dB:d=${e}`]:["-an"],"-f","null","-"]}function zg(t,e,r,n){let o=[],i=null;for(let s of t.split(/\r?\n/)){let a=s.match(e);if(a){i=Number(a[1]);continue}let c=s.match(r);c&&i!==null&&(o.push({start:i,end:Number(c[1])}),i=null)}return i!==null&&n>i&&o.push({start:i,end:n}),o}function wa(t,e){return zg(t,/freeze_start:\s*([\d.]+)/,/freeze_end:\s*([\d.]+)/,e)}function ya(t,e){return zg(t,/silence_start:\s*([\d.]+)/,/silence_end:\s*([\d.]+)/,e)}function xa(t,e){let r=[],n=0,o=0;for(;;){let i=t[n],s=e[o];if(!i||!s)break;let a=Math.max(i.start,s.start),c=Math.min(i.end,s.end);c>a&&r.push({start:a,end:c}),i.end<s.end?n++:o++}return r}function Sa(t,e,r){return t.filter(n=>n.end-n.start>=e).map(n=>({start:n.start+r,end:n.end-r})).filter(n=>n.end-n.start>.05).map(n=>({start:Number(n.start.toFixed(3)),end:Number(n.end.toFixed(3))}))}function Zu(t){if(t.length===0)throw new l("Nothing to cut.");if(t.length>qn)throw new l(`Too many idle stretches (${t.length}); raise minIdleSec.`);let e=At(t.map(n=>`between(t,${n.start},${n.end})`)),r=At(t.map(n=>`clip(T-${n.start},0,${Number((n.end-n.start).toFixed(3))})`));return{video:`select='not(${e})',setpts='(T-(${r}))/TB'`,audio:`asetnsamples=n=256:p=0,aselect='not(${e})',asetpts=N/SR/TB`}}var Zr=100,va=ga.object({start:ga.number().min(0),end:ga.number().positive(),factor:ga.number().gt(1).max(Zr)}),Qo=8;function $a(t,e){if(t.length===0)throw new l("segments needs at least one range.");if(t.length>qn)throw new l(`Too many ranges (${t.length}); at most ${qn}.`);let r=[...t].sort((n,o)=>n.start-o.start).map(n=>({start:Number(n.start.toFixed(3)),end:Number(n.end.toFixed(3)),factor:n.factor}));return r.forEach((n,o)=>{if(!(n.end>n.start)||n.start<0)throw new l(`Range ${n.start}-${n.end}s: end must be after start, from 0.`);if(!(n.factor>1)||n.factor>Zr)throw new l(`Range ${n.start}-${n.end}s: factor must be above 1 and at most ${Zr} (for slow motion, use factor on the whole clip).`);if(e!==null&&n.start>=e)throw new l(`Range ${n.start}-${n.end}s starts after the video ends (${e}s).`);let i=r[o-1];if(i&&n.start<i.end)throw new l(`Ranges ${i.start}-${i.end}s and ${n.start}-${n.end}s overlap.`)}),r}function tn(t){return t.reduce((e,r)=>e+(r.end-r.start)*(1-1/r.factor),0)}function ka(t,e){if(t.length===0)throw new l("Nothing to speed up.");let r=s=>Number((1-1/s.factor).toFixed(6)),n=At(t.map(s=>`clip(T-${s.start},0,${Number((s.end-s.start).toFixed(3))})*${r(s)}`)),o=s=>Number((s.start+(s.end-s.start)/s.factor).toFixed(3)),i=At(t.map(s=>`between(t,${o(s)},${s.end})`));return{video:`setpts='(T-(${n}))/TB'`+(e?`,fps=${Number(e.toFixed(3))}`:""),audio:`asetnsamples=n=256:p=0,aselect='not(${i})',asetpts=N/SR/TB`}}function Ea(t,e,r,n){let o=ka(r,n.fps);return["-y","-i",t,"-vf",o.video,...n.withAudio?["-af",o.audio]:["-an"],...Se({quality:n.quality??"standard",audio:n.withAudio?"aac":"omit"}),e]}function _a(t,e,r,n,o="standard"){let i=Zu(r);return["-y","-i",t,"-vf",i.video,...n?["-af",i.audio]:["-an"],...Se({quality:o,audio:n?"aac":"omit"}),e]}var LE={input:Zo.string().min(1).describe("Path to the source video."),factor:Zo.number().positive().optional().describe("Whole clip: >1 faster, <1 slower."),segments:Zo.array(va).min(1).optional().describe("Or fast-forward just these ranges (audio shortened, not pitched)."),output:Zo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Zo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Hg(t){t.registerTool("speed",{title:"Change Speed",description:"Change playback speed, or fast-forward ranges, and re-encode. Audio is retempo'd to match.",inputSchema:LE,outputSchema:K,annotations:I},async(e,r)=>{try{if(k(),O(e.input),e.factor===void 0==(e.segments===void 0))throw new l("Pass factor (the whole clip) or segments (ranges), not both.");let{audioCodec:n,durationSec:o,fps:i}=await W(e.input),s=Z(e.input),a=j(e.output,"speed",s,{overwrite:e.overwrite}),c=n!==null;if(e.segments){let p=$a(e.segments,o),f=tn(p);return await U(Ea(e.input,a,p,{withAudio:c,fps:i}),{output:a,durationSec:o!==null?o-f:null,inputDurationSec:o,extra:r}),S({outputPath:a,segments:p,savedSec:Number(f.toFixed(2)),audio:c})}let u=e.factor,d=Op(e.input,a,u,c);return await U(d,{output:a,durationSec:o!==null?o/u:null,inputDurationSec:o,extra:r}),S({outputPath:a,factor:u,audio:c})}catch(n){return E(n)}})}import{z as ft}from"zod";var BE={input:ft.string().min(1).describe("Path to the base video."),overlay:ft.string().min(1).describe("Overlay image or video path."),x:ft.number().int().nonnegative().describe("Left, px."),y:ft.number().int().nonnegative().describe("Top, px."),width:ft.number().int().positive().optional().describe("Scale to this width (other side keeps aspect)."),height:ft.number().int().positive().optional().describe("Scale to this height."),start:ft.number().nonnegative().optional().describe("Show from this second."),end:ft.number().positive().optional().describe("Hide after this second."),shape:ft.enum(["rect","circle"]).optional().describe("circle: centre square masked round (webcam)."),output:ft.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ft.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Gg(t){t.registerTool("overlay",{title:"Overlay Image or Video",description:"Composite an image or video (logo, watermark, picture-in-picture) onto a video at a pixel position, optionally scaled and time-limited; keeps the base's audio and length.",inputSchema:BE,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input),O(e.overlay,"Overlay file");let n=Z(e.input),o=j(e.output,"overlay",n,{overwrite:e.overwrite}),i=e.width!==void 0||e.height!==void 0?{width:e.width,height:e.height}:void 0,s=await ue(e.input),a=Np(e.input,e.overlay,o,{x:e.x,y:e.y,start:e.start,end:e.end,scale:i,shape:e.shape,durationSec:s});return await U(a,{output:o,durationSec:s,extra:r}),S({outputPath:o})}catch(n){return E(n)}})}import{z as st}from"zod";import{mkdtempSync as zE,rmSync as HE,writeFileSync as GE}from"node:fs";import{tmpdir as qE}from"node:os";import{join as Kg}from"node:path";var Jg=["side_by_side","stack","grid"],Ta=2,Ra=9,qg=3840,WE=1080,Xg=t=>Math.max(2,Math.round(t/2)*2);function jE(t,e){if(t==="side_by_side")return{cols:e,rows:1};if(t==="stack")return{cols:1,rows:e};let r=Math.ceil(Math.sqrt(e));return{cols:r,rows:Math.ceil(e/r)}}function UE(t,e){let r=Math.min(t.height,WE),n=t.width*r/t.height,o=Math.min(1,qg/(n*e.cols),qg/(r*e.rows));return n*=o,r*=o,{width:Xg(n),height:Xg(r)}}function el(t,e){let r=t.map(n=>Math.max(0,n.durationSec-n.skipSec));return e==="longest"?Math.max(...r):Math.min(...r)}function Yg(t,e,r){let n=t.length;if(n<Ta||n>Ra)throw new l(`compose takes ${Ta} to ${Ra} inputs.`);let o=t[0],i=jE(r.layout,n),s=UE(o,i),a=el(t,r.endWith);if(!(a>0))throw new l("Nothing is left to show after lining the inputs up.");let c=[];t.forEach((m,h)=>{let b=Math.max(0,a-(m.durationSec-m.skipSec)),w=m.label?`,drawtext=fontfile=${ye(m.label.fontFile)}:textfile=${ye(m.label.textFile)}:expansion=none:fontcolor=white:fontsize=${Math.max(14,Math.round(s.height/18))}:x=12:y=12:box=1:boxcolor=black@0.6:boxborderw=8`:"";c.push(`[${h}:v]fps=${r.fps},scale=${s.width}:${s.height}:force_original_aspect_ratio=decrease,pad=${s.width}:${s.height}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,format=yuv420p`+(b>.001?`,tpad=stop_mode=clone:stop_duration=${b.toFixed(3)}`:"")+`${w}[c${h}]`)});let u=t.map((m,h)=>`${h%i.cols*s.width}_${Math.floor(h/i.cols)*s.height}`).join("|");c.push(`${t.map((m,h)=>`[c${h}]`).join("")}xstack=inputs=${n}:layout=${u}:fill=black[v]`);let d=t.map((m,h)=>m.hasAudio?h:-1).filter(m=>m>=0),p=[];if(r.audio==="mix"&&d.length>0)c.push(`${d.map(m=>`[${m}:a]`).join("")}amix=inputs=${d.length}:normalize=0:duration=longest,apad[a]`),p=["-map","[a]"];else if(typeof r.audio=="number"){if(!t[r.audio])throw new l(`audio ${r.audio} is not an input (0-${n-1}).`);if(!t[r.audio].hasAudio)throw new l(`Input ${r.audio} has no audio; pick another, "mix", or "none".`);c.push(`[${r.audio}:a]apad[a]`),p=["-map","[a]"]}let f=p.length>0;return["-y",...t.flatMap(m=>[...m.skipSec>0?["-ss",m.skipSec.toFixed(3)]:[],"-i",m.path]),"-filter_complex",c.join(";"),"-map","[v]",...p,"-t",a.toFixed(3),...Se({quality:r.quality??"standard",audio:f?"aac":"omit"}),e]}var XE={inputs:st.array(st.object({path:st.string().min(1),label:st.string().min(1).max(80).optional()})).min(Ta).max(Ra).describe('Videos in reading order, each with an optional label (e.g. "Before").'),layout:st.enum(Jg).optional().describe("side_by_side (default), stack, or grid."),alignMarker:st.string().min(1).optional().describe("Line inputs up on this add_marker label."),endWith:st.enum(["longest","shortest"]).optional().describe("longest (default; shorter ones hold their last frame) or shortest."),audio:st.union([st.number().int().min(0),st.enum(["mix","none"])]).optional().describe('Input index whose audio to keep (default 0), "mix", or "none".'),output:st.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:st.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Vg(t){t.registerTool("compose",{title:"Compose Videos",description:"Lay 2-9 videos out side by side, stacked, or in a grid (before/after, app and terminal), labelled and in sync.",inputSchema:XE,outputSchema:K,annotations:I},async(e,r)=>{let n=zE(Kg(qE(),"screencast-compose-"));try{k();let o=[],i=[];for(let[f,m]of e.inputs.entries()){O(m.path,`Input ${f}`);let h=await W(m.path);if(!h.width||!h.height||h.durationSec===null)throw new l(`Input ${f} has no readable video: ${m.path}`);let b=0;if(e.alignMarker){let g=We(m.path).find(y=>y.label===e.alignMarker);if(!g)throw new l(`Input ${f} has no marker "${e.alignMarker}".`,"Add one with add_marker, or leave alignMarker out.");b=g.t}let w;if(m.label){let g=kt(m.label);g.warning&&i.push(g.warning);let y=Kg(n,`label${f}.txt`);GE(y,m.label),w={textFile:y,fontFile:g.fontFile}}o.push({path:m.path,width:h.width,height:h.height,durationSec:h.durationSec,hasAudio:h.audioCodec!==null,skipSec:b,label:w})}if(e.alignMarker){let f=Math.min(...o.map(m=>m.skipSec));for(let m of o)m.skipSec-=f}let s=e.endWith??"longest",a=e.audio??(o[0].hasAudio?0:"none"),c=(await W(o[0].path)).fps??30,u=j(e.output,"compose",".mp4",{overwrite:e.overwrite}),d=Yg(o,u,{layout:e.layout??"side_by_side",endWith:s,audio:a,fps:Math.min(60,Math.round(c))}),p=el(o,s);return await U(d,{output:u,durationSec:p,extra:r}),S({outputPath:u,durationSec:Number(p.toFixed(2)),layout:e.layout??"side_by_side",...e.alignMarker?{alignedOn:e.alignMarker,skipSec:o.map(f=>Number(f.skipSec.toFixed(3)))}:{},...i.length?{warnings:i}:{}})}catch(o){return E(o)}finally{HE(n,{recursive:!0,force:!0})}})}import{z as rn}from"zod";import{existsSync as KE,mkdtempSync as VE,readFileSync as QE,rmSync as ZE,writeFileSync as e_}from"node:fs";import{tmpdir as t_}from"node:os";import{join as nb}from"node:path";var Zg=["cpu","sysCpu","rssMB","sysMem"],eb=["top_left","top_right","bottom_left","bottom_right"],JE=120,tl={cpu:"App CPU %",sysCpu:"CPU %",rssMB:"App memory MB",sysMem:"Memory %"};function tb(t,e,r,n=JE){if(!(r>0))throw new l("The video has no duration.");let o=new Array(n).fill(null);for(let s of t){let a=s[e];if(a===void 0||!Number.isFinite(a)||s.t<0||s.t>=r)continue;let c=Math.min(n-1,Math.floor(s.t/r*n));o[c]=Math.max(o[c]??-1/0,a)}let i=null;return o.map(s=>s===null?i:i=s)}function YE(t,e){if(t!=="rssMB")return 100;let r=Math.max(0,...e.map(n=>n??0));return r>0?Math.ceil(r/50)*50:1}var Qg=t=>Math.max(2,Math.round(t/2)*2);function rb(t,e,r,n){let o=Qg(n.width),i=Qg(n.height);if(o>n.videoWidth||i>n.videoHeight)throw new l("The chart is larger than the video.");let s=YE(n.metric,r),a=Math.round(i*.25),c=i-a-4,u=o/r.length,d=r.flatMap((y,v)=>{if(y===null||y<=0)return[];let x=Math.max(1,Math.round(Math.min(y,s)/s*c)),R=n.metric!=="rssMB"&&n.metric!=="sysMem"&&y>=hu;return[`drawbox=x=${Math.floor(v*u)}:y=${i-2-x}:w=${Math.max(1,Math.ceil(u))}:h=${x}:color=${R?"0xFF5252":"0x4FC3F7"}@0.95:t=fill`]}),p=Number(n.durationSec.toFixed(3)),f=n.label?`,drawtext=fontfile=${ye(n.label.fontFile)}:textfile=${ye(n.label.textFile)}:expansion=none:fontcolor=white:fontsize=${Math.max(10,Math.round(a*.7))}:x=6:y=${Math.round(a*.15)}`:"",m=Math.round(Math.min(n.videoWidth,n.videoHeight)*.02),h=n.corner.endsWith("left")?m:n.videoWidth-o-m,b=n.corner.startsWith("top")?m:n.videoHeight-i-m,w=[`color=c=0x1E1E1E:s=${o}x${i}:d=${p}:r=30`,"format=yuv420p",...d].join(",")+f,g=`color=c=white:s=2x${i-a}:d=${p}:r=30`;return["-y","-i",t,"-filter_complex",`${w}[c];${g}[p];[c][p]overlay=x='min(${o-2},t/${p}*${o})':y=${a}:shortest=1[g];[0:v][g]overlay=x=${h}:y=${b}:shortest=1[v]`,"-map","[v]","-map","0:a?",...Se({quality:n.quality??"standard",audio:n.hasAudio?"copy":"omit",faststart:!0}),e]}var r_={input:rn.string().min(1).describe("A recording made with perf: true."),perf:rn.string().optional().describe("Its .perf.jsonl (default: next to input)."),metric:rn.enum(Zg).optional().describe("Default cpu (the app's) if sampled, else sysCpu."),corner:rn.enum(eb).optional().describe("Default top_right."),width:rn.number().int().min(80).max(1920).optional().describe("Chart width px (default video/4)."),output:rn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:rn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function ob(t){t.registerTool("perf_overlay",{title:"Performance Overlay",description:"Draw a recording's CPU or memory track as a small chart with a moving playhead (spikes in red).",inputSchema:r_,outputSchema:K,annotations:I},async(e,r)=>{let n=VE(nb(t_(),"screencast-perf-"));try{k(),O(e.input);let o=e.perf??vt(e.input);if(!KE(o))throw new l(`No performance track at ${o}.`,"Record with start_recording perf: true, or pass perf.");let i=Cn(QE(o,"utf8"));if(i.length===0)throw new l(`${o} has no samples.`);let s=await W(e.input);if(!s.width||!s.height||!s.durationSec)throw new l(`Could not read the size and length of ${e.input}.`);let a=e.metric??(i.some(h=>h.cpu!==void 0)?"cpu":"sysCpu"),c=tb(i,a,s.durationSec);if(c.every(h=>h===null))throw new l(`The track has no ${a} values.`);let u=e.width??Math.max(160,Math.round(s.width/4)),d=kt(tl[a]),p=nb(n,"label.txt");e_(p,tl[a]);let f=j(e.output,"perf",Z(e.input),{overwrite:e.overwrite}),m=rb(e.input,f,c,{metric:a,corner:e.corner??"top_right",width:u,height:Math.round(u*.4),videoWidth:s.width,videoHeight:s.height,durationSec:s.durationSec,label:{textFile:p,fontFile:d.fontFile},hasAudio:s.audioCodec!==null});return await U(m,{output:f,durationSec:s.durationSec,extra:r}),S({outputPath:f,metric:a,samples:i.length})}catch(o){return E(o)}finally{ZE(n,{recursive:!0,force:!0})}})}import{z as Xn}from"zod";import{existsSync as n_,readFileSync as o_,writeFileSync as i_}from"node:fs";var rl=2e3,s_={input:Xn.string().min(1).describe("The .srt to translate (e.g. from transcribe)."),language:Xn.string().regex(/^[a-z]{3}$/).optional().describe('With translations: ISO 639-2 code, e.g. "spa".'),translations:Xn.array(Xn.string().max(Ys)).max(rl).optional().describe("One translated string per cue, in order. Omit to get the cues to translate."),output:Xn.string().optional().describe("Default: <input>.<language>.srt."),overwrite:Xn.boolean().optional().describe("Allow replacing an existing output file.")};function ib(t){t.registerTool("translate_subtitles",{title:"Translate Subtitles",description:"Translate an SRT without breaking its timing: call once for the numbered cues, translate them, then call with translations to write <input>.<language>.srt for chapters' subtitleTracks.",inputSchema:s_,annotations:I},async e=>{try{if(O(e.input,"Subtitle file"),!/\.srt$/i.test(e.input))throw new l("input must be an .srt file.");let r=Ue(o_(e.input,"utf8"));if(r.length===0)throw new l(`No cues in ${e.input}.`);if(r.length>rl)throw new l(`${r.length} cues; at most ${rl} per file.`);if(!e.translations)return S({input:e.input,count:r.length,cues:r.map((i,s)=>`${s+1}. ${i.text.replace(/\s*\n\s*/g," / ")}`),next:`Translate each cue's text (keep " / " as a line break), then call again with language and translations: ${r.length} strings, in order.`});if(!e.language)throw new l('translations needs language (ISO 639-2, e.g. "spa").');let n=Fh(r,e.translations.map(i=>i.replace(/\s+\/\s+/g,`
339
+ `))),o=e.output??Oh(e.input,e.language);if(!/\.srt$/i.test(o))throw new l("output must end in .srt.");if(rr(o),n_(o)){if(!e.overwrite)throw new l(`${o} already exists.`,"Pass overwrite: true to replace it.");yc(o)}return i_(o,it(n)),S({outputPath:o,language:e.language,count:n.length})}catch(r){return E(r)}})}import{z as Ca}from"zod";import{join as c_}from"node:path";import{mkdtempSync as u_,rmSync as l_}from"node:fs";import{tmpdir as p_}from"node:os";import{z as xe}from"zod";var Jn=(t,e)=>{if(!Number.isFinite(t)||t<0)throw new l(`${e} must be a non-negative number.`);return Math.round(t)};function nl(t){let e=Fi(t.from,t.to);return e?`:enable='${e}'`:""}function sb(t){let e=t.x2-t.x1,r=t.y2-t.y1,n=Math.round(Math.hypot(e,r)),o=Math.max(2,Math.round(t.thickness??8));if(n<o*3)throw new l("An arrow must be at least three times as long as it is thick.");return{length:n,thickness:o,angle:Math.atan2(r,e),cx:(t.x1+t.x2)/2,cy:(t.y1+t.y2)/2}}function ab(t,e){let{length:r,thickness:n,angle:o}=sb(t),i=Be(t.color??"red"),s=n*3,a=o.toFixed(6),c=`if(lt(X,W-H),if(lt(abs(Y-H/2),${n}/2),255,0),if(lt(abs(Y-H/2),(W-X)/2),255,0))`;return["-y","-v","error","-f","lavfi","-i",`color=c=${i}:s=${r}x${s}`,"-vf",`format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${c}',rotate=a=${a}:ow=rotw(${a}):oh=roth(${a}):c=none`,"-frames:v","1",...Te(e)]}function il(t,e,r,n,o){if(t.length===0)throw new l("Give at least one callout.");let i=[],s=[],a=r;return t.forEach((c,u)=>{let d=`[${o}c${u}]`;if(c.type==="box"){let p=Be(c.color??"red"),f=c.fill?"fill":String(Math.max(1,Math.round(c.thickness??4)));s.push(`${a}drawbox=x=${Jn(c.x,"x")}:y=${Jn(c.y,"y")}:w=${Jn(c.width,"width")}:h=${Jn(c.height,"height")}:color=${p}:t=${f}${nl(c)}${d}`)}else if(c.type==="text"){let p=e.textFiles[u];if(!p)throw new l("Internal: missing text file for a text callout.");let f=Be(c.color??"white"),m=Math.max(8,Math.round(c.size??32)),h=c.background===!1?"":`:box=1:boxcolor=black@0.6:boxborderw=${Math.round(m/3)}`;s.push(`${a}drawtext=fontfile=${ye(e.fontFiles?.[u]??e.fontFile)}:textfile=${ye(p)}:expansion=none:x=${Jn(c.x,"x")}:y=${Jn(c.y,"y")}:fontsize=${m}:fontcolor=${f}${h}${nl(c)}${d}`)}else{let p=e.arrowFiles[u];if(!p)throw new l("Internal: missing image for an arrow callout.");let{cx:f,cy:m}=sb(c),h=n+i.length/4;i.push("-loop","1","-i",p),s.push(`${a}[${h}:v]overlay=x=${f.toFixed(1)}-w/2:y=${m.toFixed(1)}-h/2:shortest=1${nl(c)}${d}`)}a=d}),{steps:s,out:a,extraInputs:i}}function cb(t,e,r,n,o="standard",i=!1){let s=i?r.map(({from:d,to:p,...f})=>f):r,{steps:a,out:c,extraInputs:u}=il(s,n,"[0:v]",1,"");return i?["-y","-i",t,...u,"-filter_complex",a.join(";"),"-map",c,"-frames:v","1",...Te(e)]:["-y","-i",t,...u,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...Re(o),"-c:a","copy",e]}var ol={from:xe.number().nonnegative().optional(),to:xe.number().positive().optional(),color:xe.string().optional()},_r=xe.string().min(1).optional().describe("Font: a .ttf/.otf/.ttc path or a C:\\Windows\\Fonts file name. Default: bundled Inter, with a covering system font for scripts it lacks (CJK, emoji, Arabic, ...)."),Aa=xe.discriminatedUnion("type",[xe.object({type:xe.literal("box"),x:xe.number(),y:xe.number(),width:xe.number().positive(),height:xe.number().positive(),thickness:xe.number().positive().optional().describe("Outline px (default 4)."),fill:xe.boolean().optional().describe("Fill instead of outline."),...ol}),xe.object({type:xe.literal("text"),x:xe.number(),y:xe.number(),text:xe.string().min(1),size:xe.number().positive().optional().describe("Font size px (default 32)."),background:xe.boolean().optional().describe("Dark panel behind the text (default true)."),...ol}),xe.object({type:xe.literal("arrow"),x1:xe.number(),y1:xe.number(),x2:xe.number().describe("Head (x2,y2) is the point the arrow points at."),y2:xe.number(),thickness:xe.number().positive().optional().describe("Shaft px (default 8)."),...ol})]);import{join as ub}from"node:path";import{writeFileSync as a_}from"node:fs";function sl(t,e){let r={fontFiles:[],fallbackFonts:[],warnings:[]};return t.forEach((n,o)=>{if(n.type!=="text"){r.fontFiles.push(null);return}let i=kt(n.text,{weight:"bold",fontFile:e});r.fontFiles.push(i.fontFile),i.fallback&&r.fallbackFonts.push({item:o,fontFile:i.fontFile}),i.warning&&r.warnings.push(`Item ${o}: ${i.warning}`)}),r}async function Ma(t,e,r="",n){let o=sl(t,n),i=t.map((a,c)=>{if(a.type!=="text")return null;let u=ub(e,`${r}text_${c}.txt`);return a_(u,a.text),u}),s=[];for(let[a,c]of t.entries()){if(c.type!=="arrow"){s.push(null);continue}let u=ub(e,`${r}arrow_${a}.png`);await te(ab(c,u),3e4),s.push(u)}return{fontFile:Ut("bold"),textFiles:i,arrowFiles:s,...o}}var d_={input:Ca.string().min(1).describe("Path to the source video or image (png/jpg; from/to are ignored for an image)."),items:Ca.array(Aa).min(1).max(50).describe("Boxes, text labels, and arrows, drawn in order (later on top), in video pixels. Each shows from..to seconds (default: whole video); color is a name, #RRGGBB, or name@alpha."),fontFile:_r,output:Ca.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ca.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function lb(t){t.registerTool("callout",{title:"Add Callouts",description:"Annotate a video or screenshot with timed boxes, text labels, and arrows. Fallback fonts used are listed in fallbackFonts; characters no font covers are reported in warnings.",inputSchema:d_,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=e.items,{still:o,ext:i}=Ni(e.input,e.output),s=j(e.output,"callout",i,{overwrite:e.overwrite,anyContainer:!0}),a=u_(c_(p_(),"screencast-callout-"));try{let c=await Ma(n,a,"",e.fontFile),u=cb(e.input,s,n,c,void 0,o);return await U(u,{output:s,durationSec:o?null:await ue(e.input),extra:r}),S({outputPath:s,callouts:n.length,...c.fallbackFonts.length>0&&{fallbackFonts:c.fallbackFonts},...c.warnings.length>0&&{warnings:c.warnings}})}finally{l_(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as ti}from"zod";import{join as __}from"node:path";import{mkdtempSync as T_,rmSync as R_}from"node:fs";import{tmpdir as A_}from"node:os";import{z as qt}from"zod";import{existsSync as m_,readFileSync as f_,writeFileSync as h_}from"node:fs";import{join as g_}from"node:path";var b_=["bottom","bottom-left","bottom-right","top","top-left","top-right"],al=1.2,w_=.5,pb=8,db=100,mb="Typing\u2026",y_=new Set(["Ctrl","Alt","Shift","Win"]),x_=/^(?:[A-Z0-9]|F\d{1,2}|Enter|Tab|Esc|Space|Backspace|Delete|Insert|Left|Up|Right|Down|Home|End|PageUp|PageDown|[=\-,./`[\];'\\])$/;function S_(t,e="shortcuts"){let r=t.split("+"),n=r.pop();return n===void 0||r.length===0||!x_.test(n)||!r.every(o=>y_.has(o))||new Set(r).size!==r.length?null:[...r,e==="masked"?"\u2026":n].join(" + ")}var v_={left:"Click",right:"Right click",middle:"Middle click",x1:"Back button",x2:"Forward button"},Pa=t=>Math.round(t*1e3)/1e3;function $_(t,e={}){let r=e.lingerSec??al;if(!(r>0))throw new l("lingerSec must be positive.");let n=e.keys??"shortcuts",o=[...t].filter(a=>Number.isFinite(a.t)&&a.t>=0).sort((a,c)=>a.t-c.t),i=[];for(let a of o)if(a.type==="key"&&a.keys){let c=S_(a.keys,n);if(!c)continue;let u=i.at(-1);if(u&&u.kind==="shortcut"&&u.base===c&&a.t-u.last<=r){u.count++,u.last=a.t,u.label=`${c} \xD7${u.count}`,u.to=a.t+r;continue}i.push({from:a.t,to:a.t+r,label:c,base:c,kind:"shortcut",count:1,last:a.t})}else if(a.type==="down"&&e.clicks!==!1&&a.inFrame){let c=v_[a.button??"left"]??"Click",u=i.at(-1);if(c==="Click"&&u&&u.kind==="click"&&u.base==="Click"&&u.count<3&&a.t-u.last<=w_&&Math.abs(a.x-(u.x??a.x))<=pb&&Math.abs(a.y-(u.y??a.y))<=pb){u.count++,u.last=a.t,u.label=u.count===2?"Double click":"Triple click",u.to=a.t+r;continue}i.push({from:a.t,to:a.t+r,label:c,base:c,kind:"click",count:1,x:a.x,y:a.y,last:a.t})}else if(a.type==="typing"&&e.typing!==!1){let c=a.t+Math.max(a.durationSec??0,0),u=i.at(-1);if(u&&u.kind==="typing"&&a.t<=u.to){u.to=Math.max(u.to,c+r/2),u.last=a.t;continue}i.push({from:a.t,to:c+r/2,label:mb,base:mb,kind:"typing",count:1,last:a.t})}let s=[];return i.forEach((a,c)=>{let u=i[c+1],d=u?Math.min(a.to,u.from):a.to;d-a.from>=.05&&s.push({from:Pa(a.from),to:Pa(d),label:a.label,kind:a.kind})}),s}function Ia(t){let e=new Map;for(let r of t){let n=e.get(r.label);n||(n={label:r.label,windows:[]},e.set(r.label,n)),n.windows.push([r.from,r.to])}if(e.size>db)throw new l(`${e.size} different badges is more than ${db}; trim the video or turn off keys or clicks.`);return[...e.values()]}function k_(t,e){return t.flatMap(r=>{let n=e(r.from,r.to);return n&&n[1]-n[0]>=.05?[{...r,from:Pa(n[0]),to:Pa(n[1])}]:[]})}function fb(t,e){return k_(t,(r,n)=>Gr(r,n,e))}function E_(t,e){if(e!==void 0){if(!(e>=8&&e<=400))throw new l("size must be between 8 and 400.");return Math.round(e)}return Math.max(14,Math.round(t*.045))}function cl(t,e,r,n,o,i){if(t.length===0)throw new l("No badges to draw.");let s=E_(n.height,r.size),a=Math.round(s/3),c=a+Math.round(s*.6),u=r.position??"bottom",d=u.endsWith("left")?`${c}`:u.endsWith("right")?`w-tw-${c}`:"(w-tw)/2",p=u.startsWith("top")?`${c}`:`h-lh-${c}`,f=Be(r.color??"white"),m=[],h=o;return t.forEach((b,w)=>{let g=e.textFiles[b.label];if(!g)throw new l(`Internal: no text file for badge "${b.label}".`);let y=At(b.windows.map(([x,R])=>`between(t,${x},${R})`)),v=`[${i}k${w}]`;m.push(`${h}drawtext=fontfile=${ye(e.fontFile)}:textfile=${ye(g)}:expansion=none:fontsize=${s}:fontcolor=${f}:box=1:boxcolor=black@0.6:boxborderw=${a}:x=${d}:y=${p}:enable='${y}'${v}`),h=v}),{steps:m,out:h}}function hb(t,e,r,n,o,i,s="standard"){let{steps:a,out:c}=cl(r,n,o,i,"[0:v]","");return["-y","-i",t,"-filter_complex",a.join(";"),"-map",c,"-map","0:a?",...Re(s),"-c:a","copy",e]}var Fa={events:qt.string().optional(),clicks:qt.boolean().optional(),typing:qt.boolean().optional(),keys:qt.enum(["shortcuts","masked"]).optional(),lingerSec:qt.number().positive().max(10).optional(),position:qt.enum(b_).optional(),size:qt.number().min(8).max(400).optional(),color:qt.string().optional(),fontFile:qt.string().min(1).optional()};function Oa(t,e,r){let n=e??ke(t).jsonl;if(!m_(n))throw new l(`No event log for ${t} (looked for ${n}). Record with start_recording events: true (keys: "shortcuts" to name shortcuts), or pass events: <path to .events.jsonl>.`);let o=ze(f_(n,"utf8"));return{badges:$_(o,r),shortcutsLogged:o.filter(i=>i.type==="key").length,path:n}}function ei(t,e,r="",n){let o=kt(t.join(" "),{weight:"bold",fontFile:n}),i={};return t.forEach((s,a)=>{if(e===null){i[s]=`<badge ${a}>`;return}let c=g_(e,`${r}badge_${a}.txt`);h_(c,s),i[s]=c}),{fontFile:o.fontFile,textFiles:i,...o.fallback&&{fallbackFont:o.fontFile},warnings:o.warning?[o.warning]:[]}}var Tr=Fa,M_={input:ti.string().min(1).describe("Path to the recording."),events:Tr.events.describe("Event log (default: the input's .events.jsonl)."),clicks:Tr.clicks.describe("Show clicks (default true)."),typing:Tr.typing.describe('Show typing as "Typing\u2026" (default true).'),keys:Tr.keys.describe("shortcuts (default): the chord (Ctrl + S); masked: modifiers only (Ctrl + \u2026)."),lingerSec:Tr.lingerSec.describe(`Seconds a badge stays up (default ${al}).`),position:Tr.position.describe("Default bottom (centred)."),size:Tr.size.describe("Font px (default 4.5% of the frame height)."),color:Tr.color.describe("Text color (default white)."),fontFile:_r,dryRun:ti.boolean().optional().describe("Return the planned badges; write nothing."),output:ti.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ti.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function gb(t){t.registerTool("keystroke_overlay",{title:"Keystroke Overlay",description:"Burn keycast-style badges for shortcuts, clicks, and typing from the recording's input event log (start_recording events: true). Never shows typed text: the log has none.",inputSchema:M_,outputSchema:B({badges:ti.number().int()}),annotations:I},async(e,r)=>{try{k(),O(e.input);let n={clicks:e.clicks,typing:e.typing,keys:e.keys,lingerSec:e.lingerSec},{badges:o,shortcutsLogged:i}=Oa(e.input,e.events,n),s=i===0?'The log names no shortcuts (recorded with keys: "masked"), so only clicks and typing can show.':void 0;if(o.length===0)return S({badges:0,note:"Nothing to show: the log has no clicks, shortcuts, or typing; nothing written."});let a=Ia(o);if(e.dryRun){let p=ei(a.map(f=>f.label),null,"",e.fontFile);return S({dryRun:!0,badges:o.length,plan:o,...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}let c=await W(e.input);if(!c.height)throw new l(`Could not read the size of ${e.input}.`);let u=j(e.output,"keys",Z(e.input),{overwrite:e.overwrite}),d=T_(__(A_(),"screencast-keys-"));try{let p=ei(a.map(h=>h.label),d,"",e.fontFile),f={position:e.position,size:e.size,color:e.color},m=hb(e.input,u,a,p,f,{height:c.height});return await U(m,{output:u,durationSec:c.durationSec,extra:r}),S({outputPath:u,badges:o.length,labels:a.map(h=>h.label),...p.fallbackFont&&{fallbackFont:p.fallbackFont},...p.warnings.length>0&&{warnings:p.warnings},...s&&{note:s}})}finally{R_(d,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as ni}from"zod";import{join as Sb}from"node:path";import{mkdtempSync as Y_,rmSync as K_,writeFileSync as V_}from"node:fs";import{tmpdir as Q_}from"node:os";import{z as Yn}from"zod";import{existsSync as C_,readFileSync as P_}from"node:fs";var ri={w:114,h:168,hotX:9,hotY:9,arrowH:135};function Na(){return _n("cursor","arrow.png")}var I_=.5,ul=2,ll=1.5,F_=.4,bb=240,O_=4,N_=.35,D_=new Set(["move","down","up","wheel"]),Kn=t=>Math.round(t*1e3)/1e3;function L_(t){let e=6+(1-t)*34;return{omega:e,lead:Math.min(2/e,.2)}}function B_(t){let e=[],r=hc/1e3;for(let n of t){let o=e.at(-1);o&&n.t-o.t>r*2&&(o.x!==n.x||o.y!==n.y)&&e.push({t:n.t-r,x:o.x,y:o.y}),o&&n.t===o.t?e[e.length-1]=n:e.push(n)}return e}function W_(t,e,r=0){if(t.length===0)return{x:0,y:0,i:0};let n=Math.max(0,Math.min(r,t.length-1));for(;n>0&&t[n].t>e;)n--;for(;n<t.length-1&&t[n+1].t<=e;)n++;let o=t[n],i=t[n+1];if(!i||e<=o.t)return{x:o.x,y:o.y,i:n};let s=(e-o.t)/(i.t-o.t);return{x:o.x+(i.x-o.x)*s,y:o.y+(i.y-o.y)*s,i:n}}function j_(t,e,r,n,o){if(t.length===0)return[];let i=1/bb,s=0,a=w=>{let g=W_(t,w+r,s);return s=g.i,g},c=a(n),u=c.x,d=c.y,p=0,f=0,m=[{t:Kn(n),x:u,y:d}],h=Math.exp(-e*i),b=Math.max(0,Math.ceil((o-n)*bb));for(let w=1;w<=b;w++){let g=Math.min(o,n+w*i),y=a(g),v=u-y.x,x=d-y.y,R=(p+e*v)*i,T=(f+e*x)*i;p=(p-e*R)*h,f=(f-e*T)*h,u=y.x+(v+R)*h,d=y.y+(x+T)*h,(w%O_===0||w===b)&&m.push({t:Kn(g),x:u,y:d})}return m}function U_(t,e=N_){if(t.length<=2)return[...t];let r=new Uint8Array(t.length);r[0]=1,r[t.length-1]=1;let n=[[0,t.length-1]];for(;n.length>0;){let[o,i]=n.pop(),s=t[o],a=t[i],c=-1,u=-1;for(let d=o+1;d<i;d++){let p=t[d],f=a.t>s.t?(p.t-s.t)/(a.t-s.t):0,m=Math.hypot(p.x-(s.x+(a.x-s.x)*f),p.y-(s.y+(a.y-s.y)*f));m>c&&(c=m,u=d)}c>e&&(r[u]=1,n.push([o,u],[u,i]))}return t.filter((o,i)=>r[i]===1)}function z_(t){let e=[];for(let r of[...t].sort((n,o)=>n[0]-o[0])){let n=e.at(-1);n&&r[0]<=n[1]?n[1]=Math.max(n[1],r[1]):e.push([r[0],r[1]])}return e}function H_(t,e={},r=null){let n=e.smoothing??I_;if(!(n>=0&&n<=1))throw new l("smoothing must be between 0 and 1.");let o=e.hideAfterSec??ul;if(!(o>=0))throw new l("hideAfterSec must be 0 or more.");let i=t.filter(h=>D_.has(h.type)&&Number.isFinite(h.t)&&h.t>=0&&Number.isFinite(h.x)&&Number.isFinite(h.y)).filter(h=>r===null||h.t<=r).sort((h,b)=>h.t-b.t);if(i.length===0)return{path:[],visible:[],clicks:[]};let s=B_(i.map(h=>({t:h.t,x:h.x,y:h.y}))),a=s[0].t,c=s.at(-1).t,u,d=0;if(n===0)u=s.map(h=>({...h})),r!==null&&r>c&&u.push({...s.at(-1),t:r});else{let h=L_(n);d=h.lead;let b=Math.max(0,a-d),w=Math.max(b,r??c+8/h.omega);u=j_(s,h.omega,d,b,w)}let p=Math.max(0,a-d),f=o===0?[[p,r??1/0]]:z_(i.map(h=>[Math.max(0,h.t-d),h.t+o])),m=i.filter(h=>h.type==="down").map(h=>({t:h.t,x:h.x,y:h.y}));return{path:u,visible:f.map(([h,b])=>[Kn(h),r!==null?Math.min(b,r):b]).filter(([h,b])=>b>h),clicks:m}}var G_={sx:1,sy:1,ox:0,oy:0};function Da(t,e=[],r=G_){let n=a=>{let c=as(a.t,e);return c===null?null:{t:Kn(c),x:a.x*r.sx+r.ox,y:a.y*r.sy+r.oy}},o=[];for(let a of t.path){let c=n(a);c&&(o.length>0&&o.at(-1).t>=c.t?o[o.length-1]={...c,t:o.at(-1).t}:o.push(c))}let i=t.visible.flatMap(([a,c])=>{let u=Gr(a,c,e);return u&&u[1]-u[0]>=.05?[[Kn(u[0]),Number.isFinite(u[1])?Kn(u[1]):u[1]]]:[]}),s=t.clicks.flatMap(a=>{let c=n(a);return c?[c]:[]});return{path:U_(o),visible:i,clicks:s}}var Ie=(t,e=2)=>{let r=Number(t.toFixed(e));return Object.is(r,-0)?"0":String(r)};function wb(t,e,r){let n=Number(r.toFixed(3));return n===0?Ie(t):`${Ie(t)}${n<0?"-":"+"}(t-${Ie(e,3)})*${Ie(Math.abs(n),3)}`}function q_(t,e=ll){if(!(e>=.25&&e<=8))throw new l("size must be between 0.25 and 8.");let r=Math.max(8,t*.025*e),n=r/ri.arrowH,o=Math.max(12,Math.round(r*2.2));return{spriteW:Math.max(2,Math.round(ri.w*n)),spriteH:Math.max(2,Math.round(ri.h*n)),hotX:ri.hotX*n,hotY:ri.hotY*n,ripples:[.45,.72,1].map(i=>Math.max(6,Math.round(o*i/2)*2)),spotRadius:Math.max(24,Math.round(t*.12))}}function X_(t){let e=new Map;for(let r of[...t].sort((n,o)=>n.t-o.t)){let n=Ie(Math.max(0,r.t),3),o=e.get(n)??[];o.push(r.text),e.set(n,o)}return[...e.entries()].map(([r,n])=>`${r} ${n.join(", ")};`).join(`
339
340
  `)+`
340
- `}function bb(t,e,r,n){return t.map((o,i)=>{let s=t[i+1],a=s?s.t-o.t:0,c=s&&a>0?(s.x-o.x)/a:0,u=s&&a>0?(s.y-o.y)/a:0;return{t:o.t,text:`${e} x ${gb(o.x+r,o.t,c)}, ${e} y ${gb(o.y+n,o.t,u)}`}})}function D_(t,e){return t.flatMap(([r,n])=>[{t:r,text:`${e} enable 1`},...Number.isFinite(n)?[{t:n,text:`${e} enable 0`}]:[]])}function ll(t,e,r,n,o,i,s,a){if(t.path.length===0)throw new l("No cursor positions to draw.");let c=O_(r.height,e.size),{width:u,height:d}=r,p=g=>`overlay@${i}c${g}`,f=[],m=[],h=t.path[0],b=`[${i}cm]`;f.push(`${n}sendcmd=f=${ye(a)}${b}`);let w=(g,y,$,S,C)=>{let M=`[${i}c${y}o]`;f.push(`${b}${g}${p(y)}=x=${Ce(h.x+$)}:y=${Ce(h.y+S)}:enable=0${M}`),m.push(...D_(C,p(y))),b=M};if(e.spotlight){let y=Math.ceil(2*u/4),$=Math.ceil(2*d/4),S=c.spotRadius/4,C=S*.8,M=`255*0.55*clip((hypot(X-${Ce(y/2)},Y-${Ce($/2)})-${Ce(S)})/${Ce(C)},0,1)`;f.push(`color=c=black:s=${y}x${$}:r=1:d=1,format=rgba,geq=r=0:g=0:b=0:a='${M}',scale=${2*u}:${2*d}[${i}csm]`);let R=c.spriteW*.25-u,P=c.spriteH*.3-d;w(`[${i}csm]`,"s",R,P,t.visible),m.push(...bb(t.path,p("s"),R,P))}if(e.clicks!==!1&&t.clicks.length>0){let g=$_/3;c.ripples.forEach((y,$)=>{let S=y/2,C=Math.max(1.5,y*.05),M=`abs(hypot(X-${Ce(S-.5)},Y-${Ce(S-.5)})-${Ce(S-C-1)})`,R=[.9,.65,.4][$],P=`255*lt(${M},${Ce(C*.45)})`;f.push(`color=c=black:s=${y}x${y}:r=1:d=1,format=rgba,geq=r='${P}':g='${P}':b='${P}':a='255*${R}*clip(${Ce(C)}-${M},0,1)'[${i}cr${$}]`);let j=t.clicks.map(X=>[X.t+$*g,X.t+($+1)*g]);w(`[${i}cr${$}]`,`r${$}`,-S,-S,[]);for(let[X,D]of t.clicks.entries()){let[ae,ee]=j[X],J=j[X+1];m.push({t:ae,text:`${p(`r${$}`)} x ${Ce(D.x-S)}, ${p(`r${$}`)} y ${Ce(D.y-S)}, ${p(`r${$}`)} enable 1`}),(!J||J[0]>=ee)&&m.push({t:ee,text:`${p(`r${$}`)} enable 0`})}})}return f.push(`[${o}:v]scale=${c.spriteW}:${c.spriteH}:flags=lanczos,format=rgba[${i}csp]`),w(`[${i}csp]`,"p",-c.hotX,-c.hotY,t.visible),m.push(...bb(t.path,p("p"),-c.hotX,-c.hotY)),{steps:f,out:b,extraInputs:["-i",s],commands:N_(m)}}function wb(t,e,r,n,o,i,s,a="standard"){let{steps:c,out:u,extraInputs:d,commands:p}=ll(r,n,o,"[0:v]",1,"",i,s);return{args:["-y","-i",t,...d,"-filter_complex",c.join(";"),"-map",u,"-map","0:a?",..._e(a),"-c:a","copy",e],commands:p}}var La={events:Xn.string().optional(),size:Xn.number().min(.25).max(8).optional(),smoothing:Xn.number().min(0).max(1).optional(),hideAfterSec:Xn.number().min(0).max(600).optional(),clicks:Xn.boolean().optional(),spotlight:Xn.boolean().optional()};function Ba(t,e,r,n){let o=e??$e(t).jsonl;if(!x_(o))throw new l(`No event log for ${t} (looked for ${o}). Record with start_recording cursor: "events" (no OS cursor in the video, events logged), or pass events: <path to .events.jsonl>.`);let i=I_(je(S_(o,"utf8")),r,n);if(i.path.length===0)throw new l(`The event log ${o} has no cursor positions to draw.`);return i}var Yn=La,U_={input:ri.string().min(1).describe("Path to the recording."),events:Yn.events.describe("Event log (default: the input's .events.jsonl)."),size:Yn.size.describe(`Times a typical cursor's size (default ${ul}).`),smoothing:Yn.smoothing.describe("0 = as logged, 1 = floaty (default 0.5)."),hideAfterSec:Yn.hideAfterSec.describe(`Hide when the mouse rests this long; 0 = never (default ${cl}).`),clicks:Yn.clicks.describe("Ripple on clicks (default true)."),spotlight:Yn.spotlight.describe("Dim all but the area around the cursor."),dryRun:ri.boolean().optional().describe("Return the plan; write nothing."),output:ri.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ri.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function xb(t){t.registerTool("cursor",{title:"Re-rendered Cursor",description:'Draw a smoothed, scaled cursor that hides when idle from the event log of a start_recording cursor: "events" recording (no OS cursor in the video), with click ripples and an optional spotlight.',inputSchema:U_,outputSchema:N({segments:ri.number().int()}),annotations:I},async(e,r)=>{try{k(),F(e.input);let n=await L(e.input);if(!n.width||!n.height)throw new l(`Could not read the size of ${e.input}.`);let o=Da(Ba(e.input,e.events,e,n.durationSec)),i={segments:o.path.length,clicks:o.clicks.length,shownSec:Math.round(o.visible.reduce((c,[u,d])=>c+(Math.min(d,n.durationSec??d)-u),0)*10)/10};if(e.dryRun)return v({dryRun:!0,...i,visible:o.visible});let s=B(e.output,"cursor",V(e.input),{overwrite:e.overwrite}),a=L_(yb(j_(),"screencast-cursor-"));try{let c=yb(a,"cursor.cmd"),{args:u,commands:d}=wb(e.input,s,o,{size:e.size,clicks:e.clicks,spotlight:e.spotlight},{width:n.width,height:n.height},Na(),c);return W_(c,d),await W(u,{output:s,durationSec:n.durationSec,extra:r}),v({outputPath:s,...i})}finally{B_(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as Kn}from"zod";import{existsSync as J_}from"node:fs";import{extname as Y_}from"node:path";import{z as Ht}from"zod";var $b={desktop:["#1B2330","#0A0D12"],rec:["#FF4545","#5C0F1A"],amber:["#FFB454","#FF4545"],light:["#F4F7FA","#B9C4D0"]},z_=Object.keys($b),H_="desktop",dl=4,G_=.5,Sb=t=>2*Math.round(t/2),Wa=t=>2*Math.floor(t/2);function pl(t,e,r){if(t!==void 0){if(!Number.isFinite(t)||t<0||t>r)throw new l(`${e} must be between 0 and ${r}.`);return Math.round(t)}}function q_(t,e,r={}){if(!(t>0&&e>0))throw new l("The input has no frame size.");let n=pl(r.padding,"padding",2e3),o=pl(r.radius,"radius",1e3),i=pl(r.shadow,"shadow",200),s,a,c=t,u=e,d,p,f,m=!1;if(r.aspect){let $=jn[r.aspect];if(!$)throw new l(`Unknown aspect "${r.aspect}".`);s=$.w,a=$.h,f=Sb(n??Math.max(s,a)*.06);let S=s-2*f,C=a-2*f;if(S<16||C<16)throw new l(`padding ${f} leaves no room on a ${r.aspect} canvas.`);let M=Math.min(S/t,C/e);c=Math.max(2,Wa(t*M)),u=Math.max(2,Wa(e*M)),m=c!==t||u!==e,d=Wa((s-c)/2),p=Wa((a-u)/2)}else f=Sb(n??Math.max(t,e)*.06),s=t+2*f+t%2,a=e+2*f+e%2,d=f,p=f;let h=Math.max(c,u),b=Math.min(o??Math.round(h*.012),Math.floor(Math.min(c,u)/2)),w=i??Math.round(h*.025),g=a-p-u,y=w>0?Math.max(0,Math.min(Math.round(w/2),g)):0;return{canvasW:s,canvasH:a,contentW:c,contentH:u,x:d,y:p,padding:f,radius:b,shadow:w,shadowOffset:y,scaled:m}}function X_(t){if(t.colors!==void 0){if(t.colors.length<1||t.colors.length>dl)throw new l(`colors takes 1 to ${dl} colors.`);return t.colors.map((n,o)=>De(n,`colors[${o}]`))}let e=t.preset??H_,r=$b[e];if(!r)throw new l(`Unknown backdrop preset "${e}".`);return[...r]}function vb(t,e=!1){let r=t,n=`max(max(${r}-X-0.5,X+0.5-(W-${r})),0)`,o=`max(max(${r}-Y-0.5,Y+0.5-(H-${r})),0)`,i=`clip(${r}+0.5-hypot(${n},${o}),0,1)`;return e?`255-255*${i}`:`255*${i}`}function ml(t,e,r,n,o,i=!1){let s=q_(e.width,e.height,t);if(t.shadowOpacity!==void 0&&!(t.shadowOpacity>=0&&t.shadowOpacity<=1))throw new l("shadowOpacity must be between 0 and 1.");let a=t.shadowOpacity??G_,{canvasW:c,canvasH:u,contentW:d,contentH:p,x:f,y:m}=s,h=":r=1:d=1",b=[],w=[],g=`[${o}bg]`;if(t.image)w.push("-i",t.image),b.push(`[${n}:v]scale=${c}:${u}:force_original_aspect_ratio=increase,crop=${c}:${u},setsar=1,trim=end_frame=1,format=rgba${g}`);else{let j=X_(t);if(j.length===1)b.push(`color=c=${j[0]}:s=${c}x${u}${h},format=rgba${g}`);else{let X=j.map((D,ae)=>`c${ae}=${D}`).join(":");b.push(`gradients=s=${c}x${u}:${X}:n=${j.length}:x0=0:y0=0:x1=${c}:y1=${u}:r=1,trim=end_frame=1,format=rgba${g}`)}}let y=g;if(s.shadow>0&&a>0){let j=`[${o}sa]`,X=`[${o}sc]`,D=`[${o}sh]`,ae=`[${o}bs]`,ee=s.radius>0?`format=gray,geq=lum='${vb(s.radius)}'`:"format=gray";b.push(`color=c=white:s=${d}x${p}${h},${ee},pad=${c}:${u}:${f}:${m+s.shadowOffset}:color=black,gblur=sigma=${(s.shadow/2).toFixed(2)}${j}`),b.push(`color=c=black:s=${c}x${u}${h}${X}`),b.push(`${X}${j}alphamerge,format=rgba,colorchannelmixer=aa=${a}${D}`),b.push(`${y}${D}overlay=0:0:format=rgb${ae}`),y=ae}let $=`[${o}hole]`,S=`[${o}frame]`,C=s.radius>0?`format=gray,geq=lum='${vb(s.radius,!0)}'`:"format=gray";b.push(`color=c=black:s=${d}x${p}${h},${C},pad=${c}:${u}:${f}:${m}:color=white${$}`),b.push(`${y}${$}alphamerge,format=rgba${S}`);let M=`[${o}pad]`,R=`[${o}bd]`,P=s.scaled?`scale=${d}:${p},setsar=1,`:"";return b.push(`${r}${P}pad=${c}:${u}:${f}:${m}:color=black${M}`),b.push(`${M}${S}overlay=0:0${i?":format=rgb":""}${R}`),{steps:b,out:R,extraInputs:w,layout:s}}function kb(t,e,r,n,o=!1,i="standard"){let{steps:s,out:a,extraInputs:c,layout:u}=ml(r,n,"[0:v]",1,"",o),d="[vout]";s.push(`${a}format=${o?"rgb24":"yuv420p"}${d}`);let p=["-y","-i",t,...c,"-filter_complex",s.join(";"),"-map",d];return{args:o?[...p,"-frames:v","1",...Ee(e)]:[...p,"-map","0:a?",..._e(i),"-c:a","copy","-movflags","+faststart",e],layout:u}}var ja={preset:Ht.enum(z_).optional(),colors:Ht.array(Ht.string()).min(1).max(dl).optional(),image:Ht.string().min(1).optional(),padding:Ht.number().int().nonnegative().max(2e3).optional(),radius:Ht.number().int().nonnegative().max(1e3).optional(),shadow:Ht.number().int().nonnegative().max(200).optional(),shadowOpacity:Ht.number().min(0).max(1).optional(),aspect:Ht.enum(Wn).optional()};var Eb=/\.(png|jpe?g|bmp|tiff?|webp)$/i,kr=ja,K_={input:Kn.string().min(1).describe("Path to the source video or image (png/jpg)."),preset:kr.preset.describe("Gradient: desktop (default, dark slate), rec (red), amber, light."),colors:kr.colors.describe("Instead: 1 color = solid, 2-4 = diagonal gradient."),image:kr.image.describe("Instead: a wallpaper image, scaled to cover."),padding:kr.padding.describe("px around the content (default 6% of the longer side)."),radius:kr.radius.describe("Corner radius px (default ~1.2% of the longer side; 0 = square)."),shadow:kr.shadow.describe("Shadow blur px (default ~2.5%; 0 = none)."),shadowOpacity:kr.shadowOpacity.describe("Default 0.5."),aspect:kr.aspect.describe("Output on this aspect's canvas (1920x1080, ...), content scaled to fit."),output:Kn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits (screenshots for an image)."),overwrite:Kn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function _b(t){t.registerTool("backdrop",{title:"Add Backdrop",description:"Frame a video or screenshot on a gradient, color, or wallpaper with padding, rounded corners, and a drop shadow, optionally on a 16:9/1:1/9:16/4:5 canvas.",inputSchema:K_,outputSchema:N({outputPath:Kn.string(),width:Kn.number().int(),height:Kn.number().int()}),annotations:I},async(e,r)=>{try{if(k(),F(e.input),e.image&&!J_(e.image))throw new l(`Background image not found: ${e.image}`);let n=Eb.test(e.input);if(n&&e.output&&!Eb.test(e.output))throw new l("An image input writes an image: give the output a .png or .jpg extension.");n||Nr(e.output);let o=await L(e.input);if(!o.width||!o.height)throw new l(`Could not read the size of ${e.input}.`);let i=n?/\.jpe?g$/i.test(e.input)?Y_(e.input).toLowerCase():".png":V(e.input),s=er(e.output,we(n?"screenshots":"edits"),`backdrop-${ge()}-${be()}${i}`,e.overwrite),a={preset:e.preset,colors:e.colors,image:e.image,padding:e.padding,radius:e.radius,shadow:e.shadow,shadowOpacity:e.shadowOpacity,aspect:e.aspect},{args:c,layout:u}=kb(e.input,s,a,{width:o.width,height:o.height},n);return await W(c,{output:s,durationSec:n?null:o.durationSec,extra:r}),v({outputPath:s,width:u.canvasW,height:u.canvasH,content:{x:u.x,y:u.y,width:u.contentW,height:u.contentH},padding:u.padding,radius:u.radius,shadow:u.shadow,background:e.image?"image":e.colors?"colors":e.preset??"desktop"})}catch(n){return E(n)}})}import{z as ni}from"zod";var V_={input:ni.string().min(1).describe("Path to the source video."),level:ni.enum(["light","medium","heavy"]).optional().describe("CRF 23 / 28 / 32 (default medium)."),maxWidth:ni.number().int().positive().optional().describe("Width cap in px (only downscales)."),output:ni.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ni.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Tb(t){t.registerTool("compress",{title:"Compress Video",description:"Re-encode a video smaller (H.264 CRF ladder, optional width cap). For a platform target use export_preset.",inputSchema:V_,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=V(e.input),o=B(e.output,"compress",n,{overwrite:e.overwrite}),i=Op(e.input,o,{level:e.level,maxWidth:e.maxWidth});return await W(i,{output:o,durationSec:await se(e.input),extra:r}),v({outputPath:o,level:e.level??"medium"})}catch(n){return E(n)}})}import{z as Ua}from"zod";var Q_={mp3:"mp3",aac:"m4a",wav:"wav"},Z_={input:Ua.string().min(1).describe("Path to the source media."),format:Ua.enum(["mp3","aac","wav","copy"]).describe("Audio output codec. copy keeps the source codec without re-encoding."),output:Ua.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ua.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ab(t){t.registerTool("extract_audio",{title:"Extract Audio",description:"Extract the audio track of a media file to its own file (mp3, aac, wav, or copy). Returns the output path.",inputSchema:Z_,outputSchema:Y,annotations:I},async(e,r)=>{try{let{ffprobe:n}=k();F(e.input);let o=e.format,i=null,s;if(o==="copy"){let c=await ne(n,Or(e.input),3e4,{signal:r.signal});if(c.code!==0)throw new l(`ffprobe failed (exit ${c.code}): ${c.stderr.trim().slice(-400)}`);if(i=Fr(JSON.parse(c.stdout)).audioCodec,!i)throw new l(`Input has no audio stream to extract: ${e.input}`);s=Np(i)}else s=Q_[o];let a=B(e.output,"audio",`.${s}`,{overwrite:e.overwrite,anyContainer:!0});return await W(Dp(e.input,a,o),{output:a,durationSec:await se(e.input),extra:r}),v({outputPath:a,format:o,...i?{sourceAudioCodec:i}:{}})}catch(n){return E(n)}})}import{z as wl}from"zod";import{extname as eT}from"node:path";import{z as fl}from"zod";var tT=["youtube","podcast","broadcast"],za=fl.union([fl.enum(tT),fl.number().min(-70).max(-5)]),Rb={youtube:{i:-14,tp:-1,lra:11},podcast:{i:-16,tp:-1.5,lra:11},broadcast:{i:-23,tp:-1,lra:7}};function Vn(t){if(t===void 0)return Rb.youtube;if(typeof t=="number"){if(!Number.isFinite(t)||t<-70||t>-5)throw new l("target LUFS must be between -70 and -5 (e.g. -14).");return{i:t,tp:-1,lra:11}}let e=Rb[t];if(!e)throw new l(`Unknown loudness target "${t}".`);return e}var hl=t=>`I=${t.i}:TP=${t.tp}:LRA=${t.lra}`;function oi(t,e){return["-hide_banner","-nostats","-i",t,"-vn","-af",`loudnorm=${hl(e)}:print_format=json`,"-f","null","-"]}function ii(t){let r=t.match(/\{[^{}]*"input_i"[^{}]*\}/g)?.at(-1);if(r===void 0)throw new l("Could not measure loudness (no loudnorm report). Does the file have audio?");let n=JSON.parse(r),o=s=>Number(n[s]),i={input_i:o("input_i"),input_tp:o("input_tp"),input_lra:o("input_lra"),input_thresh:o("input_thresh"),target_offset:o("target_offset"),...n.output_i!==void 0?{output_i:o("output_i")}:{}};if(!Number.isFinite(i.input_i))throw new l("The audio is silent (loudness is -inf), so there is nothing to normalize.");return i}function Mb(t){return Pi(t)?["-map","0:a:0","-vn"]:["-map","0:v?","-map","0:a:0","-c:v","copy"]}function Ha(t){switch(eT(t).toLowerCase()){case".wav":return["-c:a","pcm_s16le"];case".mp3":return["-c:a","libmp3lame","-b:a","192k"];default:return["-c:a","aac","-b:a","192k"]}}function gl(t,e){if(!e)return`loudnorm=${hl(t)}`;let r=`measured_I=${e.input_i}:measured_TP=${e.input_tp}:measured_LRA=${e.input_lra}:measured_thresh=${e.input_thresh}:offset=${e.target_offset}`;return`loudnorm=${hl(t)}:${r}:linear=true`}function Cb(t,e,r,n){return["-y","-hide_banner","-i",t,...Mb(e),"-af",`${gl(r,n)}:print_format=json`,"-ar","48000",...Ha(e),e]}var Ga=["light","medium","strong"],rT={light:6,medium:12,strong:20};function qa(t){return["-hide_banner","-nostats","-i",t,"-vn","-af","aresample=48000,asetnsamples=4800,astats=metadata=1:reset=1,ametadata=print:key=lavfi.astats.Overall.RMS_level:file=-","-f","null","-"]}function Xa(t){let e=[...t.matchAll(/RMS_level=(-?[\d.]+)/g)].map(r=>Number(r[1])).filter(Number.isFinite);return e.length===0?null:(e.sort((r,n)=>r-n),e[Math.floor(e.length*.1)]??null)}function nT(t){return t===null?-50:Math.max(-80,Math.min(-20,Math.round(t+5)))}function bl(t,e){let r=rT[t];if(r===void 0)throw new l(`Unknown denoise strength "${t}".`);return`afftdn=nr=${r}:nf=${nT(e)}`}function Pb(t,e,r="medium",n=null){return["-y","-i",t,...Mb(e),"-af",bl(r,n),...Ha(e),e]}var oT={input:wl.string().min(1).describe("Path to the source video or audio file."),target:za.optional().describe("youtube (-14 LUFS, default), podcast (-16), broadcast (-23), or a LUFS number (-70 to -5)."),output:wl.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:wl.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ib(t){t.registerTool("normalize_audio",{title:"Normalize Loudness",description:"Normalize loudness to a delivery target (two-pass EBU R128 loudnorm); video is copied. Reports loudness before and after.",inputSchema:oT,outputSchema:Y,annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();F(e.input);let o=await L(e.input);if(!o.audioCodec)throw new l(`Input has no audio stream: ${e.input}`);let i=Vn(e.target),s=V(e.input,{audio:!0}),a=B(e.output,"loudnorm",s,{overwrite:e.overwrite}),c=le(o.durationSec),u=await ne(n,oi(e.input,i),c,{signal:r.signal}),d=ii(u.stderr);await W(Cb(e.input,a,i,d),{output:a,durationSec:o.durationSec,extra:r});let p=ii((await ne(n,oi(a,i),c,{signal:r.signal})).stderr);return v({outputPath:a,target:{lufs:i.i,truePeakDb:i.tp,lra:i.lra},before:{lufs:d.input_i,truePeakDb:d.input_tp},after:{lufs:p.input_i,truePeakDb:p.input_tp}})}catch(n){return E(n)}})}import{z as Ja}from"zod";var iT={input:Ja.string().min(1).describe("Path to the source video or audio file."),strength:Ja.enum(Ga).optional().describe("How hard to reduce noise: light (6 dB), medium (12 dB, default), strong (20 dB)."),output:Ja.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ja.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Fb(t){t.registerTool("denoise",{title:"Denoise Audio",description:"Reduce steady background noise (fan, hum, hiss) in a recording's audio with an adaptive FFT denoiser. Video is copied untouched. Returns the output path.",inputSchema:iT,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=await L(e.input);if(!n.audioCodec)throw new l(`Input has no audio stream: ${e.input}`);let o=e.strength??"medium",i=V(e.input,{audio:!0}),s=B(e.output,"denoise",i,{overwrite:e.overwrite}),a=await ne(k().ffmpeg,qa(e.input),le(n.durationSec),{signal:r.signal}),c=Xa(a.stdout);return await W(Pb(e.input,s,o,c),{output:s,durationSec:n.durationSec,extra:r}),v({outputPath:s,strength:o,noiseFloorDb:c===null?null:Number(c.toFixed(1)),note:"Works best on steady noise (fans, hum, hiss); it does little for intermittent sounds."})}catch(n){return E(n)}})}import{z as Gt}from"zod";import{existsSync as sT,readFileSync as aT,rmSync as cT,writeFileSync as uT}from"node:fs";var lT={input:Gt.string().min(1).describe("Path to the video or audio to transcribe."),model:Gt.string().optional().describe(`Path to a whisper.cpp model file (ggml-*.bin). Defaults to ${Ks}.`),language:Gt.string().optional().describe("Spoken language code, e.g. 'en', or 'auto' (default)."),words:Gt.boolean().optional().describe("One word per cue, for word timing (cut_by_transcript)."),output:Gt.string().optional().describe("Optional output .srt path. Defaults under SCREENCAST_HOME/edits."),overwrite:Gt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ob(t){t.registerTool("transcribe",{title:"Transcribe Speech",description:"Transcribe a recording's speech to an SRT subtitle file, locally, with FFmpeg 8's whisper filter (needs a whisper.cpp model file). Returns the SRT path and the text. Pair with burn_subtitles to caption the video.",inputSchema:lT,outputSchema:N({srtPath:Gt.string(),cues:Gt.number().int(),text:Gt.string()}),annotations:I},async(e,r)=>{try{if(k(),F(e.input),!Ye("whisper"))throw new l("This ffmpeg has no whisper filter.","transcribe needs FFmpeg 8 built with whisper.cpp (--enable-whisper); recent Windows builds such as `winget install Gyan.FFmpeg` include it. Check with `ffmpeg -h filter=whisper`.");let n=br(e.model),o=await L(e.input);if(!o.audioCodec)throw new l(`Input has no audio to transcribe: ${e.input}`);let i=B(e.output,"captions",".srt",{overwrite:e.overwrite,anyContainer:!0}),s=Ue(".srt");try{await Z(On(e.input,n,s,e.language??"auto",e.words),le(o.durationSec),{signal:r.signal});let a=sT(s)?ut(Mh(We(aT(s,"utf8")))):[];uT(i,nt(a));let c=a.map(u=>u.text.replace(/\n/g," ")).join(" ");return v({srtPath:i,cues:a.length,text:c.length>4e3?`${c.slice(0,4e3)}\u2026`:c,...a.length===0?{note:"No speech was recognised."}:{}})}finally{cT(s,{force:!0})}}catch(n){return E(n)}})}import{z as si}from"zod";import{dirname as pT}from"node:path";import{existsSync as dT}from"node:fs";var mT={input:si.string().min(1).describe("Path to the source video."),subtitles:si.string().min(1).describe("Path to an .srt (e.g. from transcribe) or .ass subtitle file."),style:si.enum(Vs).optional().describe("clean (default for .srt): outlined line. social: big bold text on a dark box. .ass keeps its own styling unless set."),output:si.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:si.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Nb(t){t.registerTool("burn_subtitles",{title:"Burn In Subtitles",description:"Burn SRT/ASS subtitles (e.g. from transcribe) into a video in the bundled font.",inputSchema:mT,outputSchema:Y,annotations:I},async(e,r)=>{try{k();for(let a of[e.input,e.subtitles])if(!dT(a))throw new l(`File not found: ${a}`);if(!Ye("subtitles"))throw new l("This ffmpeg has no subtitles filter (it needs libass).","Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");let n=V(e.input),o=B(e.output,"subtitled",n,{overwrite:e.overwrite}),i=pT(Bt("regular")),s=e.style??(/\.(ass|ssa)$/i.test(e.subtitles)?null:"clean");return await W(Ch(e.input,e.subtitles,o,i,s),{output:o,durationSec:(await L(e.input)).durationSec,extra:r}),v({outputPath:o,style:s??"file"})}catch(n){return E(n)}})}import{z as Tt}from"zod";var fT={input:Tt.string().min(1).describe("Path to the source video."),segments:Tt.array(Tt.object({start:Tt.number().nonnegative(),end:Tt.number().positive()})).min(1).describe("{start, end} segments in seconds; each becomes its own file."),output:Tt.string().optional().describe("Optional output path. Only honored for a single segment; multi-segment output lands under SCREENCAST_HOME/edits."),overwrite:Tt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Db(t){t.registerTool("clip",{title:"Extract Clips",description:"Extract several frame-exact segments, each to its own file. For one segment, trim does the same.",inputSchema:fT,outputSchema:N({outputs:Tt.array(Tt.string()),count:Tt.number().int()}),annotations:I},async(e,r)=>{try{k(),F(e.input),Nr(e.output);let n=V(e.input),o=e.segments.length===1,i=[];for(let[s,a]of e.segments.entries()){let c=B(o?e.output:void 0,"clip",`-${String(s).padStart(2,"0")}${n}`,{overwrite:e.overwrite});await W(Lp(e.input,c,a),{output:c,durationSec:a.end-a.start,extra:r}),i.push(c)}return v({outputs:i,count:i.length})}catch(n){return E(n)}})}import{z as qt}from"zod";var hT={input:qt.string().min(1).describe("Path to the source video."),minIdleSec:qt.number().positive().optional().describe(`Only cut still stretches at least this long (default ${Yr}).`),keepSec:qt.number().min(0).optional().describe(`Seconds kept at each edge of a cut (default ${Ko}).`),useAudio:qt.boolean().optional().describe("Require silent audio too (default true when there is audio)."),action:qt.enum(["cut","speed"]).optional().describe("cut (default), or speed: fast-forward them."),factor:qt.number().gt(1).max(Jr).optional().describe(`speed: times faster (default ${Vo}).`),dryRun:qt.boolean().optional().describe("Only report what would be cut."),output:qt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:qt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Lb(t){t.registerTool("cut_idle",{title:"Cut Idle Stretches",description:"Remove dead air: cut stretches where the screen is frozen (and silent), keeping a short pad. Returns the time saved.",inputSchema:hT,annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();F(e.input);let o=await L(e.input),i=o.durationSec;if(i===null)throw new l(`Could not read duration of ${e.input}.`);let s=e.minIdleSec??Yr,a=e.keepSec??Ko,c=o.audioCodec!==null,u=(e.useAudio??!0)&&c,d=await ne(n,ba(e.input,s,u),le(i),{signal:r.signal});if(d.code!==0)throw new l(`Idle scan failed (exit ${d.code}): ${d.stderr.trim().slice(-400)}`);let p=wa(d.stderr,i),f=u?xa(p,ya(d.stderr,i)):p,m=Sa(f,s,a),h=e.action==="speed",b=e.factor??Vo,w=m.map(M=>({...M,factor:b})),g=Number((h?Kr(w):m.reduce((M,R)=>M+(R.end-R.start),0)).toFixed(2)),y={cuts:m,...h?{action:"speed",factor:b}:{},removedSec:g,originalSec:Number(i.toFixed(2)),newDurationSec:Number((i-g).toFixed(2)),idleRule:u?"frozen video and silent audio":"frozen video"};if(e.dryRun||m.length===0)return v({...y,...m.length===0?{note:"No idle stretches found; nothing to cut."}:{dryRun:!0}});let $=V(e.input),S=B(e.output,"trimmed-idle",$,{overwrite:e.overwrite}),C=h?Ea(e.input,S,w,{withAudio:c,fps:o.fps}):_a(e.input,S,m,c);return await W(C,{output:S,durationSec:i-g,inputDurationSec:i,extra:r}),v({outputPath:S,...y})}catch(n){return E(n)}})}import{z as Qe}from"zod";import{existsSync as Gb,readFileSync as vT,writeFileSync as $T}from"node:fs";var gT=["um","umm","uh","uhh","uhm","erm","er","ah","hmm","hm","mm","mhm"],Bb=.5,jb=t=>t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),Er=t=>Number(t.toFixed(3));function Ub(t){let e=[];return t.forEach((r,n)=>{let o=r.text.replace(/\s+/g," ").trim(),i=[...o.matchAll(/\S+/g)],s=o.length||1,a=r.end-r.start;i.forEach((c,u)=>{let d=c.index;e.push({cue:n,raw:c[0],norm:jb(c[0]),start:u===0?r.start:r.start+d/s*a,end:u===i.length-1?r.end:r.start+(d+c[0].length)/s*a,first:u===0,last:u===i.length-1})})}),e}var bT=t=>t.flatMap((e,r)=>e.norm?[r]:[]);function wT(t,e){let r=e.split(/\s+/).map(jb).filter(Boolean);if(r.length===0)throw new l(`Quote "${e}" has no words to match.`);let n=bT(t),o=[];for(let i=0;i+r.length<=n.length;i++)r.every((s,a)=>t[n[i+a]].norm===s)&&o.push([n[i],n[i+r.length-1]]);return o}function yT(t,e,r){let n=r;for(;t[n+1]&&!t[n+1].norm&&t[n+1].cue===t[r].cue;)n++;let o=t[e],i=t[n];return{start:Er(o.start),end:Er(i.end),text:t.slice(e,n+1).map(s=>s.raw).join(" "),exact:o.first&&i.last}}function xT(t){let e=[...t].filter(n=>n.end-n.start>.001).sort((n,o)=>n.start-o.start),r=[];for(let n of e){let o=r[r.length-1];o&&n.start<=o.end+.01?(n.end>o.end&&(o.end=n.end),o.text.includes(n.text)||(o.text=`${o.text} ${n.text}`),o.exact&&=n.exact):r.push({...n})}return r}function ST(t,e){let r=t.flatMap(o=>o.index===void 0?[]:[o.index]);if(r.length===0){let o=Number.isInteger(e)?t[e-1]:void 0;if(!o)throw new l(`No cue ${e}: the transcript has cues 1-${t.length}.`);return o}let n=t.filter(o=>o.index===e);if(n.length>1)throw new l(`The transcript numbers ${n.length} cues ${e}; quote the text to cut instead.`);if(n.length===0)throw new l(`No cue ${e}: the transcript's cues are numbered ${Math.min(...r)}-${Math.max(...r)} (a cue with no duration, or wholly overlapped by the next, has no time to cut).`);return n[0]}function zb(t,e){let r=Ub(t),n=[];for(let i of e.remove??[]){if(typeof i=="number"){let a=ST(t,i);n.push({start:Er(a.start),end:Er(a.end),text:a.text.replace(/\s+/g," "),exact:!0});continue}let s=wT(r,i);if(s.length===0)throw new l(`Quote not found in the transcript: "${i}".`);if(s.length>1)throw new l(`Quote "${i}" occurs ${s.length} times; quote more words or use cue numbers.`);n.push(yT(r,...s[0]))}let o=0;if(e.fillers){let i=new Set(gT);r.forEach(s=>{if(!i.has(s.norm))return;if(!r.every(p=>p.cue!==s.cue||p===s||!p.norm)){o++;return}let c=t[s.cue],u=Math.max(t[s.cue-1]?.end??0,c.start-Bb),d=Math.min(t[s.cue+1]?.start??1/0,c.end+Bb);n.push({start:Er(Math.min(u,c.start)),end:Er(Math.max(d,c.end)),text:r.filter(p=>p.cue===s.cue).map(p=>p.raw).join(" "),exact:!0})})}return{cuts:xT(n),skippedFillers:o}}function Wb(t,e){let r=0;for(let n of e){if(t<=n.start)break;r+=Math.min(t,n.end)-n.start}return t-r}function Hb(t,e){let r=Ub(t),n=i=>e.some(s=>i.start>=s.start-5e-4&&i.end<=s.end+5e-4),o=[];return t.forEach((i,s)=>{let a=r.filter(f=>f.cue===s),c=a.filter(f=>!n(f));if(!c.some(f=>f.norm))return;let u=c.length===a.length?i.text:c.map(f=>f.raw).join(" "),d=Er(Wb(i.start,e)),p=Er(Wb(i.end,e));p>d&&o.push({start:d,end:p,text:u})}),o}var kT={input:Qe.string().min(1).describe("Path to the source video."),srt:Qe.string().min(1).describe("Its .srt (transcribe; words: true for word timing)."),remove:Qe.array(Qe.union([Qe.number().int().min(0).max(99999),Qe.string().min(1)])).optional().describe("Cue numbers as the .srt numbers them, or transcript text quoted exactly (must occur once)."),fillers:Qe.boolean().optional().describe("Also cut fillers (um, uh...) that have their own cue."),dryRun:Qe.boolean().optional().describe("Only report the cuts."),output:Qe.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Qe.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function qb(t){t.registerTool("cut_by_transcript",{title:"Cut By Transcript",description:"Edit a video by its transcript: cut quoted text, cue numbers, or fillers. Also writes the re-timed .srt.",inputSchema:kT,outputSchema:N({cuts:Qe.array(Qe.unknown()),removedSec:Qe.number()}),annotations:I},async(e,r)=>{try{k();for(let b of[e.input,e.srt])if(!Gb(b))throw new l(`File not found: ${b}`);if(!e.remove?.length&&!e.fillers)throw new l("Nothing to cut: pass remove and/or fillers: true.");let n=await L(e.input),o=n.durationSec;if(o===null||!n.videoCodec)throw new l(`Not a readable video: ${e.input}`);let i=ut(We(vT(e.srt,"utf8"),{index:!0}));if(i.length===0)throw new l(`No cues in ${e.srt}.`);let{cuts:s,skippedFillers:a}=zb(i,{remove:e.remove,fillers:e.fillers});if(s.length>Hn)throw new l(`Too many cuts (${s.length}, max ${Hn}); cut in batches.`);let c=Number(s.reduce((b,w)=>b+Math.min(w.end,o)-Math.min(w.start,o),0).toFixed(2)),u=Hb(i,s),d=[s.length===0&&"Nothing matched; nothing to cut.",a>0&&`${a} filler(s) inside longer cues were kept; transcribe with words: true to cut them.`,s.some(b=>!b.exact)&&"Some edges were estimated inside a cue; transcribe with words: true for word timing."].filter(Boolean),p={cuts:s,removedSec:c,originalSec:Number(o.toFixed(2)),newDurationSec:Number((o-c).toFixed(2)),...d.length?{note:d.join(" ")}:{}};if(e.dryRun||s.length===0){let b=u.map(w=>w.text.replace(/\n/g," ")).join(" ");return v({...p,...s.length?{dryRun:!0}:{},text:b.length>4e3?`${b.slice(0,4e3)}\u2026`:b})}let f=V(e.input),m=B(e.output,"cut-transcript",f,{overwrite:e.overwrite}),h=m.replace(/\.[^.\\/]+$/,"")+".srt";if(!e.overwrite&&Gb(h))throw new l(`Output already exists: ${h}. Pass overwrite: true to replace it.`);return await W(_a(e.input,m,s,n.audioCodec!==null),{output:m,durationSec:o-c,inputDurationSec:o,extra:r}),$T(h,nt(u)),v({outputPath:m,srtPath:h,...p})}catch(n){return E(n)}})}import{z as Qr}from"zod";var ET={input:Qr.string().min(1).describe("Path to the source video or image (png/jpg; time ranges are ignored for an image)."),regions:Qr.array(gn).min(1).describe("Pixel rectangles (x, y, width, height), each optionally limited to start..end seconds."),style:Qr.enum(Fi).optional().describe("box (default): irreversible fill; blur/pixelate are partially recoverable."),pad:Qr.number().int().nonnegative().optional().describe("Grow each region by this many px (default 0)."),color:Qr.string().optional().describe("Box fill color (default black)."),output:Qr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Qr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Xb(t){t.registerTool("redact_region",{title:"Redact Regions",description:"Cover given rectangles in a video or screenshot (e.g. secrets on screen). Not automatic detection: find them with find_text redact: true. Off-frame regions are rejected.",inputSchema:ET,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let{width:n,height:o,durationSec:i}=await L(e.input),{still:s,ext:a}=Oi(e.input,e.output),c=B(e.output,"redact",a,{overwrite:e.overwrite,anyContainer:!0}),u=Bp(e.input,c,e.regions,{style:e.style,pad:e.pad,color:e.color},{width:n,height:o},s);return await W(u,{output:c,durationSec:s?null:i,extra:r}),v({outputPath:c,regions:e.regions.length,style:e.style??"box"})}catch(n){return E(n)}})}import{z as Ya}from"zod";function Jb(t){t.registerTool("list_audio_devices",{title:"List Audio Devices",description:"List DirectShow audio devices and flag a likely loopback (Stereo Mix or a virtual-audio driver), for start_recording's audio.device.",inputSchema:{},outputSchema:N({devices:Ya.array(Ya.unknown()),loopbackDevice:Ya.string().nullable(),note:Ya.string()}),annotations:he},async()=>{try{k();let e=await eu(!0),r=Zc(e);return v({devices:e,loopbackDevice:r,note:r?`Pass "${r}" as the audio device to capture system audio.`:`No loopback device detected. ${Mo}`})}catch(e){return E(e)}})}import{z as fe}from"zod";function Kb(t){return t.hwnd!==void 0?`window:hwnd=${t.hwnd}`:`window:${t.title}`}function _T(t){let e=/^.*?[.!?](?=\s|$)/.exec(t);return e?e[0]:t}function Yb(t,e,r){try{return Nc(t,Kb(e).slice(7),{allowCloaked:r,exactOnly:!0}),{ok:!0}}catch(n){return{ok:!1,reason:_T(U(n))}}}function Vb(t,e,r){let n=r.filter??{},o=n.exe?Oc(`exe=${n.exe}`):null,i=o?.kind==="exe"?o.exe:null,s=n.titleContains?.trim().toLowerCase()||null,a=wo(t),c=t.length>0?a:e.virtual,u=[];for(let d of Array.isArray(e.windows)?e.windows:[]){if(i!==null&&(d.exe??"").toLowerCase().replace(/\.exe$/,"")!==i||s!==null&&!d.title.toLowerCase().includes(s))continue;let p=Yb(e,d,!1),f=r.wgcAvailable&&d.hwnd!==void 0?Yb(e,d,!0):{ok:!1};n.capturableOnly&&!p.ok&&!f.ok||u.push({target:Kb(d),title:d.title,exe:d.exe||null,pid:typeof d.pid=="number"?d.pid:null,hwnd:d.hwnd??null,bounds:{x:d.left,y:d.top,width:d.right-d.left,height:d.bottom-d.top},minimized:!!d.minimized,cloaked:!!d.cloaked,capturable:p.ok,wgcCapturable:f.ok,...p.ok?{}:{reason:p.reason}})}return{full:{target:"full",bounds:{x:c.x,y:c.y,width:c.w,height:c.h}},monitors:t.map(d=>({target:`monitor:${d.index}`,index:d.index,primary:d.primary,bounds:{x:d.x,y:d.y,width:d.width,height:d.height},dpi:d.dpi??null,scale:d.dpi?Math.round(d.dpi/96*100)/100:null})),windows:u,wgcAvailable:r.wgcAvailable}}var TT={exe:fe.string().min(1).optional().describe("Only list windows of this executable, e.g. 'Code.exe' or 'code'."),titleContains:fe.string().min(1).optional().describe("Only list windows whose title contains this text (case-insensitive)."),capturableOnly:fe.boolean().optional().describe("Leave out windows neither backend can capture (minimized, off screen). Default false.")},yl=fe.object({x:fe.number(),y:fe.number(),width:fe.number(),height:fe.number()}),AT=N({full:fe.looseObject({target:fe.literal("full"),bounds:yl}),monitors:fe.array(fe.looseObject({target:fe.string(),index:fe.number(),primary:fe.boolean(),bounds:yl,dpi:fe.number().nullable(),scale:fe.number().nullable()})),windows:fe.array(fe.looseObject({target:fe.string(),title:fe.string(),exe:fe.string().nullable(),pid:fe.number().nullable(),hwnd:fe.number().nullable(),bounds:yl,minimized:fe.boolean(),cloaked:fe.boolean(),capturable:fe.boolean(),wgcCapturable:fe.boolean()})),wgcAvailable:fe.boolean(),note:fe.string()});function Qb(t){t.registerTool("list_targets",{title:"List Capture Targets",description:"List the desktop, monitors, and visible windows (topmost first, with capturability per backend). Each entry has a `target` string to pass as-is to capture tools; use it instead of guessing a title.",inputSchema:TT,outputSchema:AT,annotations:he},async e=>{try{let[r,n]=await Promise.all([ar(),Dc()]),o=Vb(r,n,{wgcAvailable:ir(),filter:{exe:e.exe,titleContains:e.titleContains,capturableOnly:e.capturableOnly}});return v({...o,note:'Pass a target string unchanged. A window handle lasts until the app closes the window; list again after an app restarts, or target it by window:exe=<app.exe>. A window with capturable false but wgcCapturable true needs backend: "wgc".'})}catch(r){return E(r)}})}import{existsSync as xl}from"node:fs";import{join as Sl}from"node:path";import{z as pe}from"zod";var Zb=200,ew=1e3,Ka=.5,Va=3,Zr=t=>Math.round(t*1e3)/1e3;function rw(t,e){if(t.length===0)throw new l("lines is empty: give at least one { t | marker, text }.");if(t.length>Zb)throw new l(`At most ${Zb} lines are allowed (got ${t.length}).`);return t.map((n,o)=>{let i=n.text.replace(/\s+/g," ").trim();if(!i)throw new l(`lines[${o}] has no text.`);if(i.length>ew)throw new l(`lines[${o}] is ${i.length} characters; at most ${ew} are allowed. Split it.`);if(n.t!==void 0&&n.marker!==void 0)throw new l(`lines[${o}] has both t and marker; give one.`);if(n.t!==void 0){if(!Number.isFinite(n.t)||n.t<0)throw new l(`lines[${o}].t must be a non-negative number.`);return{t:Zr(n.t),text:i}}if(n.marker!==void 0){let s=n.marker.trim().toLowerCase(),a=e.find(c=>c.label.trim().toLowerCase()===s);if(!a){let c=e.map(u=>`"${u.label}"`).join(", ");throw new l(`lines[${o}]: no marker labelled "${n.marker}".`,c?`Markers on this video: ${c}.`:"This video has no markers; add_marker stamps one, or give t.")}return{t:Zr(a.t),text:i}}throw new l(`lines[${o}] needs t (seconds) or marker (a marker label).`)}).sort((n,o)=>n.t-o.t)}function nw(t,e){let r=[];return t.forEach((n,o)=>{let i=n.t+n.durationSec,s=t[o+1],a=`"${n.text.length>40?`${n.text.slice(0,40)}...`:n.text}"`;n.t>=e?r.push(`Line at ${n.t}s ${a} starts after the video ends (${Zr(e)}s) and is not heard.`):s&&i>s.t+.05?r.push(`Line at ${n.t}s ${a} runs ${Zr(i-s.t)}s past the next line (${s.t}s); they overlap. Move the next line, shorten this one, or raise rate.`):i>e+.05&&r.push(`Line at ${n.t}s ${a} runs ${Zr(i-e)}s past the end of the video and is cut off.`)}),r}function ow(t,e){return t.map((r,n)=>{let o=t[n+1],i=Math.min(r.t+r.durationSec,o?o.t:1/0,e);return{start:r.t,end:Zr(i),text:r.text}}).filter(r=>r.end>r.start)}function iw(t){if(t.length<12||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WAVE")throw new l("The speech engine did not return a WAV file.");let e=0;for(let r=12;r+8<=t.length;){let n=t.toString("ascii",r,r+4),o=t.readUInt32LE(r+4);if(n==="fmt "&&r+16<=t.length&&(e=t.readUInt32LE(r+16)),n==="data"){if(e<=0)break;let i=t.length-(r+8);return(o===0||o===4294967295||o>i?i:o)/e}r+=8+o+o%2}throw new l("Could not read the WAV header the speech engine wrote.")}function sw(t,e,r,n,o,i){if(!Number.isFinite(o)||o<=0)throw new l("video duration must be known and positive.");if(e.length===0||e.length!==n.length)throw new l("Every placed line needs its WAV.");let s=Zr(o),a=h=>`amix=inputs=${h}:duration=longest:dropout_transition=0:normalize=0`,c=n.map((h,b)=>{let w=Math.round(h.t*1e3);return`[${b+1}:a]aresample=48000,aformat=channel_layouts=mono,adelay=${w}[l${b}]`}),u=n.map((h,b)=>`[l${b}]`).join(""),d=!(i.hasAudio&&i.channels===1),p=`apad,atrim=end=${s}${d?",pan=stereo|c0=c0|c1=c0":""}`,f=i.hasAudio?"voice":"aout";c.push(n.length>1?`${u}${a(n.length)},${p}[${f}]`:`[l0]${p}[${f}]`),i.hasAudio&&(c.push(`[0:a]aresample=48000,aformat=channel_layouts=${d?"stereo":"mono"}[orig]`),i.duck??!0?(c.push("[voice]asplit=2[vo][key]"),c.push("[orig][key]sidechaincompress=threshold=0.02:ratio=8:attack=20:release=400[bed]"),c.push(`[bed][vo]${a(2)}[aout]`)):c.push(`[orig][voice]${a(2)}[aout]`));let m=Pi(r);return["-y","-i",t,...e.flatMap(h=>["-i",h]),"-filter_complex",c.join(";"),...m?[]:["-map","0:v?","-c:v","copy"],"-map","[aout]","-t",String(s),...Ha(r),.../\.(mp4|mov|m4a)$/i.test(r)?["-movflags","+faststart"]:[],r]}var RT=3e4,MT=1e4,tw=3e4,aw=t=>Array.isArray(t)?t:t==null?[]:[t];function cw(t){return aw(t.voices).map(e=>({name:String(e.name??""),language:String(e.language??""),gender:String(e.gender??"")}))}function CT(t){return{script:IT,payload:JSON.stringify(t)}}async function uw(t,e,r){if(process.platform!=="win32")throw new l("narrate uses the speech engine built into Windows and runs on Windows only.");let{script:n,payload:o}=CT(t),i="list"in t,s=await st(n,i?"speech voices":"the speech engine",{timeoutMs:e,signal:r,payload:o,failure:i?"Could not list speech voices":"Could not synthesize speech"});try{return JSON.parse(s)}catch(a){throw new l(`Could not parse the speech engine's output: ${U(a)}`)}}async function PT(t){let e=await uw({list:!0},sr(15e3),t);if(e.error)throw new l(`Windows speech is unavailable: ${e.error}`);return cw(e)}async function lw(){if(process.platform!=="win32")return{available:!1,voices:[],error:"Windows speech is available on Windows only."};try{let t=(await PT()).map(e=>`${e.name} (${e.language})`);return{available:t.length>0,voices:t,...t.length?{}:{error:"No speech voices are installed."}}}catch(t){return{available:!1,voices:[],error:U(t)}}}async function pw(t,e){let r=e.rate??1;if(!Number.isFinite(r)||r<Ka||r>Va)throw new l(`rate must be between ${Ka} and ${Va} (1 is normal speed).`);let n=await uw({voice:e.voice??null,rate:r,items:t},sr(RT+t.length*MT),e.signal);if(n.error){let o=cw(n);throw n.error==="unknown voice"?new l(`No installed voice matches "${e.voice}".`,o.length?`Installed voices: ${o.map(i=>`${i.name} (${i.language})`).join(", ")}.`:"No voices are installed."):new l(`Windows speech is unavailable: ${n.error}`,"Install a voice: Settings > Time & language > Speech > Manage voices.")}return aw(n.results).forEach((o,i)=>{if(o.error)throw new l(`Could not synthesize line ${i+1}: ${o.error}`)}),String(n.voice??"")}var IT=`
341
+ `}function yb(t,e,r,n){return t.map((o,i)=>{let s=t[i+1],a=s?s.t-o.t:0,c=s&&a>0?(s.x-o.x)/a:0,u=s&&a>0?(s.y-o.y)/a:0;return{t:o.t,text:`${e} x ${wb(o.x+r,o.t,c)}, ${e} y ${wb(o.y+n,o.t,u)}`}})}function J_(t,e){return t.flatMap(([r,n])=>[{t:r,text:`${e} enable 1`},...Number.isFinite(n)?[{t:n,text:`${e} enable 0`}]:[]])}function pl(t,e,r,n,o,i,s,a){if(t.path.length===0)throw new l("No cursor positions to draw.");let c=q_(r.height,e.size),{width:u,height:d}=r,p=g=>`overlay@${i}c${g}`,f=[],m=[],h=t.path[0],b=`[${i}cm]`;f.push(`${n}sendcmd=f=${ye(a)}${b}`);let w=(g,y,v,x,R)=>{let T=`[${i}c${y}o]`;f.push(`${b}${g}${p(y)}=x=${Ie(h.x+v)}:y=${Ie(h.y+x)}:enable=0${T}`),m.push(...J_(R,p(y))),b=T};if(e.spotlight){let y=Math.ceil(2*u/4),v=Math.ceil(2*d/4),x=c.spotRadius/4,R=x*.8,T=`255*0.55*clip((hypot(X-${Ie(y/2)},Y-${Ie(v/2)})-${Ie(x)})/${Ie(R)},0,1)`;f.push(`color=c=black:s=${y}x${v}:r=1:d=1,format=rgba,geq=r=0:g=0:b=0:a='${T}',scale=${2*u}:${2*d}[${i}csm]`);let M=c.spriteW*.25-u,H=c.spriteH*.3-d;w(`[${i}csm]`,"s",M,H,t.visible),m.push(...yb(t.path,p("s"),M,H))}if(e.clicks!==!1&&t.clicks.length>0){let g=F_/3;c.ripples.forEach((y,v)=>{let x=y/2,R=Math.max(1.5,y*.05),T=`abs(hypot(X-${Ie(x-.5)},Y-${Ie(x-.5)})-${Ie(x-R-1)})`,M=[.9,.65,.4][v],H=`255*lt(${T},${Ie(R*.45)})`;f.push(`color=c=black:s=${y}x${y}:r=1:d=1,format=rgba,geq=r='${H}':g='${H}':b='${H}':a='255*${M}*clip(${Ie(R)}-${T},0,1)'[${i}cr${v}]`);let G=t.clicks.map(L=>[L.t+v*g,L.t+(v+1)*g]);w(`[${i}cr${v}]`,`r${v}`,-x,-x,[]);for(let[L,C]of t.clicks.entries()){let[ne,V]=G[L],Y=G[L+1];m.push({t:ne,text:`${p(`r${v}`)} x ${Ie(C.x-x)}, ${p(`r${v}`)} y ${Ie(C.y-x)}, ${p(`r${v}`)} enable 1`}),(!Y||Y[0]>=V)&&m.push({t:V,text:`${p(`r${v}`)} enable 0`})}})}return f.push(`[${o}:v]scale=${c.spriteW}:${c.spriteH}:flags=lanczos,format=rgba[${i}csp]`),w(`[${i}csp]`,"p",-c.hotX,-c.hotY,t.visible),m.push(...yb(t.path,p("p"),-c.hotX,-c.hotY)),{steps:f,out:b,extraInputs:["-i",s],commands:X_(m)}}function xb(t,e,r,n,o,i,s,a="standard"){let{steps:c,out:u,extraInputs:d,commands:p}=pl(r,n,o,"[0:v]",1,"",i,s);return{args:["-y","-i",t,...d,"-filter_complex",c.join(";"),"-map",u,"-map","0:a?",...Re(a),"-c:a","copy",e],commands:p}}var La={events:Yn.string().optional(),size:Yn.number().min(.25).max(8).optional(),smoothing:Yn.number().min(0).max(1).optional(),hideAfterSec:Yn.number().min(0).max(600).optional(),clicks:Yn.boolean().optional(),spotlight:Yn.boolean().optional()};function Ba(t,e,r,n){let o=e??ke(t).jsonl;if(!C_(o))throw new l(`No event log for ${t} (looked for ${o}). Record with start_recording cursor: "events" (no OS cursor in the video, events logged), or pass events: <path to .events.jsonl>.`);let i=H_(ze(P_(o,"utf8")),r,n);if(i.path.length===0)throw new l(`The event log ${o} has no cursor positions to draw.`);return i}var Vn=La,Z_={input:ni.string().min(1).describe("Path to the recording."),events:Vn.events.describe("Event log (default: the input's .events.jsonl)."),size:Vn.size.describe(`Times a typical cursor's size (default ${ll}).`),smoothing:Vn.smoothing.describe("0 = as logged, 1 = floaty (default 0.5)."),hideAfterSec:Vn.hideAfterSec.describe(`Hide when the mouse rests this long; 0 = never (default ${ul}).`),clicks:Vn.clicks.describe("Ripple on clicks (default true)."),spotlight:Vn.spotlight.describe("Dim all but the area around the cursor."),dryRun:ni.boolean().optional().describe("Return the plan; write nothing."),output:ni.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ni.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function vb(t){t.registerTool("cursor",{title:"Re-rendered Cursor",description:'Draw a smoothed, scaled cursor that hides when idle from the event log of a start_recording cursor: "events" recording (no OS cursor in the video), with click ripples and an optional spotlight.',inputSchema:Z_,outputSchema:B({segments:ni.number().int()}),annotations:I},async(e,r)=>{try{k(),O(e.input);let n=await W(e.input);if(!n.width||!n.height)throw new l(`Could not read the size of ${e.input}.`);let o=Da(Ba(e.input,e.events,e,n.durationSec)),i={segments:o.path.length,clicks:o.clicks.length,shownSec:Math.round(o.visible.reduce((c,[u,d])=>c+(Math.min(d,n.durationSec??d)-u),0)*10)/10};if(e.dryRun)return S({dryRun:!0,...i,visible:o.visible});let s=j(e.output,"cursor",Z(e.input),{overwrite:e.overwrite}),a=Y_(Sb(Q_(),"screencast-cursor-"));try{let c=Sb(a,"cursor.cmd"),{args:u,commands:d}=xb(e.input,s,o,{size:e.size,clicks:e.clicks,spotlight:e.spotlight},{width:n.width,height:n.height},Na(),c);return V_(c,d),await U(u,{output:s,durationSec:n.durationSec,extra:r}),S({outputPath:s,...i})}finally{K_(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as Qn}from"zod";import{existsSync as iT}from"node:fs";import{extname as sT}from"node:path";import{z as Xt}from"zod";var Eb={desktop:["#1B2330","#0A0D12"],rec:["#FF4545","#5C0F1A"],amber:["#FFB454","#FF4545"],light:["#F4F7FA","#B9C4D0"]},eT=Object.keys(Eb),tT="desktop",ml=4,rT=.5,$b=t=>2*Math.round(t/2),Wa=t=>2*Math.floor(t/2);function dl(t,e,r){if(t!==void 0){if(!Number.isFinite(t)||t<0||t>r)throw new l(`${e} must be between 0 and ${r}.`);return Math.round(t)}}function nT(t,e,r={}){if(!(t>0&&e>0))throw new l("The input has no frame size.");let n=dl(r.padding,"padding",2e3),o=dl(r.radius,"radius",1e3),i=dl(r.shadow,"shadow",200),s,a,c=t,u=e,d,p,f,m=!1;if(r.aspect){let v=zn[r.aspect];if(!v)throw new l(`Unknown aspect "${r.aspect}".`);s=v.w,a=v.h,f=$b(n??Math.max(s,a)*.06);let x=s-2*f,R=a-2*f;if(x<16||R<16)throw new l(`padding ${f} leaves no room on a ${r.aspect} canvas.`);let T=Math.min(x/t,R/e);c=Math.max(2,Wa(t*T)),u=Math.max(2,Wa(e*T)),m=c!==t||u!==e,d=Wa((s-c)/2),p=Wa((a-u)/2)}else f=$b(n??Math.max(t,e)*.06),s=t+2*f+t%2,a=e+2*f+e%2,d=f,p=f;let h=Math.max(c,u),b=Math.min(o??Math.round(h*.012),Math.floor(Math.min(c,u)/2)),w=i??Math.round(h*.025),g=a-p-u,y=w>0?Math.max(0,Math.min(Math.round(w/2),g)):0;return{canvasW:s,canvasH:a,contentW:c,contentH:u,x:d,y:p,padding:f,radius:b,shadow:w,shadowOffset:y,scaled:m}}function oT(t){if(t.colors!==void 0){if(t.colors.length<1||t.colors.length>ml)throw new l(`colors takes 1 to ${ml} colors.`);return t.colors.map((n,o)=>Be(n,`colors[${o}]`))}let e=t.preset??tT,r=Eb[e];if(!r)throw new l(`Unknown backdrop preset "${e}".`);return[...r]}function kb(t,e=!1){let r=t,n=`max(max(${r}-X-0.5,X+0.5-(W-${r})),0)`,o=`max(max(${r}-Y-0.5,Y+0.5-(H-${r})),0)`,i=`clip(${r}+0.5-hypot(${n},${o}),0,1)`;return e?`255-255*${i}`:`255*${i}`}function fl(t,e,r,n,o,i=!1){let s=nT(e.width,e.height,t);if(t.shadowOpacity!==void 0&&!(t.shadowOpacity>=0&&t.shadowOpacity<=1))throw new l("shadowOpacity must be between 0 and 1.");let a=t.shadowOpacity??rT,{canvasW:c,canvasH:u,contentW:d,contentH:p,x:f,y:m}=s,h=":r=1:d=1",b=[],w=[],g=`[${o}bg]`;if(t.image)w.push("-i",t.image),b.push(`[${n}:v]scale=${c}:${u}:force_original_aspect_ratio=increase,crop=${c}:${u},setsar=1,trim=end_frame=1,format=rgba${g}`);else{let G=oT(t);if(G.length===1)b.push(`color=c=${G[0]}:s=${c}x${u}${h},format=rgba${g}`);else{let L=G.map((C,ne)=>`c${ne}=${C}`).join(":");b.push(`gradients=s=${c}x${u}:${L}:n=${G.length}:x0=0:y0=0:x1=${c}:y1=${u}:r=1,trim=end_frame=1,format=rgba${g}`)}}let y=g;if(s.shadow>0&&a>0){let G=`[${o}sa]`,L=`[${o}sc]`,C=`[${o}sh]`,ne=`[${o}bs]`,V=s.radius>0?`format=gray,geq=lum='${kb(s.radius)}'`:"format=gray";b.push(`color=c=white:s=${d}x${p}${h},${V},pad=${c}:${u}:${f}:${m+s.shadowOffset}:color=black,gblur=sigma=${(s.shadow/2).toFixed(2)}${G}`),b.push(`color=c=black:s=${c}x${u}${h}${L}`),b.push(`${L}${G}alphamerge,format=rgba,colorchannelmixer=aa=${a}${C}`),b.push(`${y}${C}overlay=0:0:format=rgb${ne}`),y=ne}let v=`[${o}hole]`,x=`[${o}frame]`,R=s.radius>0?`format=gray,geq=lum='${kb(s.radius,!0)}'`:"format=gray";b.push(`color=c=black:s=${d}x${p}${h},${R},pad=${c}:${u}:${f}:${m}:color=white${v}`),b.push(`${y}${v}alphamerge,format=rgba${x}`);let T=`[${o}pad]`,M=`[${o}bd]`,H=s.scaled?`scale=${d}:${p},setsar=1,`:"";return b.push(`${r}${H}pad=${c}:${u}:${f}:${m}:color=black${T}`),b.push(`${T}${x}overlay=0:0${i?":format=rgb":""}${M}`),{steps:b,out:M,extraInputs:w,layout:s}}function _b(t,e,r,n,o=!1,i="standard"){let{steps:s,out:a,extraInputs:c,layout:u}=fl(r,n,"[0:v]",1,"",o),d="[vout]";s.push(`${a}format=${o?"rgb24":"yuv420p"}${d}`);let p=["-y","-i",t,...c,"-filter_complex",s.join(";"),"-map",d];return{args:o?[...p,"-frames:v","1",...Te(e)]:[...p,"-map","0:a?",...Re(i),"-c:a","copy","-movflags","+faststart",e],layout:u}}var ja={preset:Xt.enum(eT).optional(),colors:Xt.array(Xt.string()).min(1).max(ml).optional(),image:Xt.string().min(1).optional(),padding:Xt.number().int().nonnegative().max(2e3).optional(),radius:Xt.number().int().nonnegative().max(1e3).optional(),shadow:Xt.number().int().nonnegative().max(200).optional(),shadowOpacity:Xt.number().min(0).max(1).optional(),aspect:Xt.enum(Un).optional()};var Tb=/\.(png|jpe?g|bmp|tiff?|webp)$/i,Rr=ja,aT={input:Qn.string().min(1).describe("Path to the source video or image (png/jpg)."),preset:Rr.preset.describe("Gradient: desktop (default, dark slate), rec (red), amber, light."),colors:Rr.colors.describe("Instead: 1 color = solid, 2-4 = diagonal gradient."),image:Rr.image.describe("Instead: a wallpaper image, scaled to cover."),padding:Rr.padding.describe("px around the content (default 6% of the longer side)."),radius:Rr.radius.describe("Corner radius px (default ~1.2% of the longer side; 0 = square)."),shadow:Rr.shadow.describe("Shadow blur px (default ~2.5%; 0 = none)."),shadowOpacity:Rr.shadowOpacity.describe("Default 0.5."),aspect:Rr.aspect.describe("Output on this aspect's canvas (1920x1080, ...), content scaled to fit."),output:Qn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits (screenshots for an image)."),overwrite:Qn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Rb(t){t.registerTool("backdrop",{title:"Add Backdrop",description:"Frame a video or screenshot on a gradient, color, or wallpaper with padding, rounded corners, and a drop shadow, optionally on a 16:9/1:1/9:16/4:5 canvas.",inputSchema:aT,outputSchema:B({outputPath:Qn.string(),width:Qn.number().int(),height:Qn.number().int()}),annotations:I},async(e,r)=>{try{if(k(),O(e.input),e.image&&!iT(e.image))throw new l(`Background image not found: ${e.image}`);let n=Tb.test(e.input);if(n&&e.output&&!Tb.test(e.output))throw new l("An image input writes an image: give the output a .png or .jpg extension.");n||jr(e.output);let o=await W(e.input);if(!o.width||!o.height)throw new l(`Could not read the size of ${e.input}.`);let i=n?/\.jpe?g$/i.test(e.input)?sT(e.input).toLowerCase():".png":Z(e.input),s=nr(e.output,we(n?"screenshots":"edits"),`backdrop-${he()}-${ge()}${i}`,e.overwrite),a={preset:e.preset,colors:e.colors,image:e.image,padding:e.padding,radius:e.radius,shadow:e.shadow,shadowOpacity:e.shadowOpacity,aspect:e.aspect},{args:c,layout:u}=_b(e.input,s,a,{width:o.width,height:o.height},n);return await U(c,{output:s,durationSec:n?null:o.durationSec,extra:r}),S({outputPath:s,width:u.canvasW,height:u.canvasH,content:{x:u.x,y:u.y,width:u.contentW,height:u.contentH},padding:u.padding,radius:u.radius,shadow:u.shadow,background:e.image?"image":e.colors?"colors":e.preset??"desktop"})}catch(n){return E(n)}})}import{z as oi}from"zod";var cT={input:oi.string().min(1).describe("Path to the source video."),level:oi.enum(["light","medium","heavy"]).optional().describe("CRF 23 / 28 / 32 (default medium)."),maxWidth:oi.number().int().positive().optional().describe("Width cap in px (only downscales)."),output:oi.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:oi.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ab(t){t.registerTool("compress",{title:"Compress Video",description:"Re-encode a video smaller (H.264 CRF ladder, optional width cap). For a platform target use export_preset.",inputSchema:cT,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=Z(e.input),o=j(e.output,"compress",n,{overwrite:e.overwrite}),i=Dp(e.input,o,{level:e.level,maxWidth:e.maxWidth});return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o,level:e.level??"medium"})}catch(n){return E(n)}})}import{z as Ua}from"zod";var uT={mp3:"mp3",aac:"m4a",wav:"wav"},lT={input:Ua.string().min(1).describe("Path to the source media."),format:Ua.enum(["mp3","aac","wav","copy"]).describe("Audio output codec. copy keeps the source codec without re-encoding."),output:Ua.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ua.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Mb(t){t.registerTool("extract_audio",{title:"Extract Audio",description:"Extract the audio track of a media file to its own file (mp3, aac, wav, or copy). Returns the output path.",inputSchema:lT,outputSchema:K,annotations:I},async(e,r)=>{try{let{ffprobe:n}=k();O(e.input);let o=e.format,i=null,s;if(o==="copy"){let c=await se(n,Wr(e.input),3e4,{signal:r.signal});if(c.code!==0)throw new l(`ffprobe failed (exit ${c.code}): ${c.stderr.trim().slice(-400)}`);if(i=Br(JSON.parse(c.stdout)).audioCodec,!i)throw new l(`Input has no audio stream to extract: ${e.input}`);s=Lp(i)}else s=uT[o];let a=j(e.output,"audio",`.${s}`,{overwrite:e.overwrite,anyContainer:!0});return await U(Bp(e.input,a,o),{output:a,durationSec:await ue(e.input),extra:r}),S({outputPath:a,format:o,...i?{sourceAudioCodec:i}:{}})}catch(n){return E(n)}})}import{z as yl}from"zod";import{extname as pT}from"node:path";import{z as hl}from"zod";var dT=["youtube","podcast","broadcast"],za=hl.union([hl.enum(dT),hl.number().min(-70).max(-5)]),Cb={youtube:{i:-14,tp:-1,lra:11},podcast:{i:-16,tp:-1.5,lra:11},broadcast:{i:-23,tp:-1,lra:7}};function Zn(t){if(t===void 0)return Cb.youtube;if(typeof t=="number"){if(!Number.isFinite(t)||t<-70||t>-5)throw new l("target LUFS must be between -70 and -5 (e.g. -14).");return{i:t,tp:-1,lra:11}}let e=Cb[t];if(!e)throw new l(`Unknown loudness target "${t}".`);return e}var gl=t=>`I=${t.i}:TP=${t.tp}:LRA=${t.lra}`;function ii(t,e){return["-hide_banner","-nostats","-i",t,"-vn","-af",`loudnorm=${gl(e)}:print_format=json`,"-f","null","-"]}function si(t){let r=t.match(/\{[^{}]*"input_i"[^{}]*\}/g)?.at(-1);if(r===void 0)throw new l("Could not measure loudness (no loudnorm report). Does the file have audio?");let n=JSON.parse(r),o=s=>Number(n[s]),i={input_i:o("input_i"),input_tp:o("input_tp"),input_lra:o("input_lra"),input_thresh:o("input_thresh"),target_offset:o("target_offset"),...n.output_i!==void 0?{output_i:o("output_i")}:{}};if(!Number.isFinite(i.input_i))throw new l("The audio is silent (loudness is -inf), so there is nothing to normalize.");return i}function Pb(t){return Ii(t)?["-map","0:a:0","-vn"]:["-map","0:v?","-map","0:a:0","-c:v","copy"]}function Ha(t){switch(pT(t).toLowerCase()){case".wav":return["-c:a","pcm_s16le"];case".mp3":return["-c:a","libmp3lame","-b:a","192k"];default:return["-c:a","aac","-b:a","192k"]}}function bl(t,e){if(!e)return`loudnorm=${gl(t)}`;let r=`measured_I=${e.input_i}:measured_TP=${e.input_tp}:measured_LRA=${e.input_lra}:measured_thresh=${e.input_thresh}:offset=${e.target_offset}`;return`loudnorm=${gl(t)}:${r}:linear=true`}function Ib(t,e,r,n){return["-y","-hide_banner","-i",t,...Pb(e),"-af",`${bl(r,n)}:print_format=json`,"-ar","48000",...Ha(e),e]}var Ga=["light","medium","strong"],mT={light:6,medium:12,strong:20};function qa(t){return["-hide_banner","-nostats","-i",t,"-vn","-af","aresample=48000,asetnsamples=4800,astats=metadata=1:reset=1,ametadata=print:key=lavfi.astats.Overall.RMS_level:file=-","-f","null","-"]}function Xa(t){let e=[...t.matchAll(/RMS_level=(-?[\d.]+)/g)].map(r=>Number(r[1])).filter(Number.isFinite);return e.length===0?null:(e.sort((r,n)=>r-n),e[Math.floor(e.length*.1)]??null)}function fT(t){return t===null?-50:Math.max(-80,Math.min(-20,Math.round(t+5)))}function wl(t,e){let r=mT[t];if(r===void 0)throw new l(`Unknown denoise strength "${t}".`);return`afftdn=nr=${r}:nf=${fT(e)}`}function Fb(t,e,r="medium",n=null){return["-y","-i",t,...Pb(e),"-af",wl(r,n),...Ha(e),e]}var hT={input:yl.string().min(1).describe("Path to the source video or audio file."),target:za.optional().describe("youtube (-14 LUFS, default), podcast (-16), broadcast (-23), or a LUFS number (-70 to -5)."),output:yl.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:yl.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ob(t){t.registerTool("normalize_audio",{title:"Normalize Loudness",description:"Normalize loudness to a delivery target (two-pass EBU R128 loudnorm); video is copied. Reports loudness before and after.",inputSchema:hT,outputSchema:K,annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();O(e.input);let o=await W(e.input);if(!o.audioCodec)throw new l(`Input has no audio stream: ${e.input}`);let i=Zn(e.target),s=Z(e.input,{audio:!0}),a=j(e.output,"loudnorm",s,{overwrite:e.overwrite}),c=pe(o.durationSec),u=await se(n,ii(e.input,i),c,{signal:r.signal}),d=si(u.stderr);await U(Ib(e.input,a,i,d),{output:a,durationSec:o.durationSec,extra:r});let p=si((await se(n,ii(a,i),c,{signal:r.signal})).stderr);return S({outputPath:a,target:{lufs:i.i,truePeakDb:i.tp,lra:i.lra},before:{lufs:d.input_i,truePeakDb:d.input_tp},after:{lufs:p.input_i,truePeakDb:p.input_tp}})}catch(n){return E(n)}})}import{z as Ja}from"zod";var gT={input:Ja.string().min(1).describe("Path to the source video or audio file."),strength:Ja.enum(Ga).optional().describe("How hard to reduce noise: light (6 dB), medium (12 dB, default), strong (20 dB)."),output:Ja.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ja.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Nb(t){t.registerTool("denoise",{title:"Denoise Audio",description:"Reduce steady background noise (fan, hum, hiss) in a recording's audio with an adaptive FFT denoiser. Video is copied untouched. Returns the output path.",inputSchema:gT,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=await W(e.input);if(!n.audioCodec)throw new l(`Input has no audio stream: ${e.input}`);let o=e.strength??"medium",i=Z(e.input,{audio:!0}),s=j(e.output,"denoise",i,{overwrite:e.overwrite}),a=await se(k().ffmpeg,qa(e.input),pe(n.durationSec),{signal:r.signal}),c=Xa(a.stdout);return await U(Fb(e.input,s,o,c),{output:s,durationSec:n.durationSec,extra:r}),S({outputPath:s,strength:o,noiseFloorDb:c===null?null:Number(c.toFixed(1)),note:"Works best on steady noise (fans, hum, hiss); it does little for intermittent sounds."})}catch(n){return E(n)}})}import{z as Jt}from"zod";import{existsSync as bT,readFileSync as wT,rmSync as yT,writeFileSync as xT}from"node:fs";var ST={input:Jt.string().min(1).describe("Path to the video or audio to transcribe."),model:Jt.string().optional().describe(`Path to a whisper.cpp model file (ggml-*.bin). Defaults to ${Ks}.`),language:Jt.string().optional().describe("Spoken language code, e.g. 'en', or 'auto' (default)."),words:Jt.boolean().optional().describe("One word per cue, for word timing (cut_by_transcript)."),output:Jt.string().optional().describe("Optional output .srt path. Defaults under SCREENCAST_HOME/edits."),overwrite:Jt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Db(t){t.registerTool("transcribe",{title:"Transcribe Speech",description:"Transcribe a recording's speech to an SRT subtitle file, locally, with FFmpeg 8's whisper filter (needs a whisper.cpp model file). Returns the SRT path and the text. Pair with burn_subtitles to caption the video.",inputSchema:ST,outputSchema:B({srtPath:Jt.string(),cues:Jt.number().int(),text:Jt.string()}),annotations:I},async(e,r)=>{try{if(k(),O(e.input),!Ve("whisper"))throw new l("This ffmpeg has no whisper filter.","transcribe needs FFmpeg 8 built with whisper.cpp (--enable-whisper); recent Windows builds such as `winget install Gyan.FFmpeg` include it. Check with `ffmpeg -h filter=whisper`.");let n=Sr(e.model),o=await W(e.input);if(!o.audioCodec)throw new l(`Input has no audio to transcribe: ${e.input}`);let i=j(e.output,"captions",".srt",{overwrite:e.overwrite,anyContainer:!0}),s=He(".srt");try{await te(Dn(e.input,n,s,e.language??"auto",e.words),pe(o.durationSec),{signal:r.signal});let a=bT(s)?pt(Ph(Ue(wT(s,"utf8")))):[];xT(i,it(a));let c=a.map(u=>u.text.replace(/\n/g," ")).join(" ");return S({srtPath:i,cues:a.length,text:c.length>4e3?`${c.slice(0,4e3)}\u2026`:c,...a.length===0?{note:"No speech was recognised."}:{}})}finally{yT(s,{force:!0})}}catch(n){return E(n)}})}import{z as ai}from"zod";import{dirname as vT}from"node:path";import{existsSync as $T}from"node:fs";var kT={input:ai.string().min(1).describe("Path to the source video."),subtitles:ai.string().min(1).describe("Path to an .srt (e.g. from transcribe) or .ass subtitle file."),style:ai.enum(Vs).optional().describe("clean (default for .srt): outlined line. social: big bold text on a dark box. .ass keeps its own styling unless set."),output:ai.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ai.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Lb(t){t.registerTool("burn_subtitles",{title:"Burn In Subtitles",description:"Burn SRT/ASS subtitles (e.g. from transcribe) into a video in the bundled font.",inputSchema:kT,outputSchema:K,annotations:I},async(e,r)=>{try{k();for(let a of[e.input,e.subtitles])if(!$T(a))throw new l(`File not found: ${a}`);if(!Ve("subtitles"))throw new l("This ffmpeg has no subtitles filter (it needs libass).","Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");let n=Z(e.input),o=j(e.output,"subtitled",n,{overwrite:e.overwrite}),i=vT(Ut("regular")),s=e.style??(/\.(ass|ssa)$/i.test(e.subtitles)?null:"clean");return await U(Ih(e.input,e.subtitles,o,i,s),{output:o,durationSec:(await W(e.input)).durationSec,extra:r}),S({outputPath:o,style:s??"file"})}catch(n){return E(n)}})}import{z as Mt}from"zod";var ET={input:Mt.string().min(1).describe("Path to the source video."),segments:Mt.array(Mt.object({start:Mt.number().nonnegative(),end:Mt.number().positive()})).min(1).describe("{start, end} segments in seconds; each becomes its own file."),output:Mt.string().optional().describe("Optional output path. Only honored for a single segment; multi-segment output lands under SCREENCAST_HOME/edits."),overwrite:Mt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Bb(t){t.registerTool("clip",{title:"Extract Clips",description:"Extract several frame-exact segments, each to its own file. For one segment, trim does the same.",inputSchema:ET,outputSchema:B({outputs:Mt.array(Mt.string()),count:Mt.number().int()}),annotations:I},async(e,r)=>{try{k(),O(e.input),jr(e.output);let n=Z(e.input),o=e.segments.length===1,i=[];for(let[s,a]of e.segments.entries()){let c=j(o?e.output:void 0,"clip",`-${String(s).padStart(2,"0")}${n}`,{overwrite:e.overwrite});await U(Wp(e.input,c,a),{output:c,durationSec:a.end-a.start,extra:r}),i.push(c)}return S({outputs:i,count:i.length})}catch(n){return E(n)}})}import{z as Yt}from"zod";var _T={input:Yt.string().min(1).describe("Path to the source video."),minIdleSec:Yt.number().positive().optional().describe(`Only cut still stretches at least this long (default ${en}).`),keepSec:Yt.number().min(0).optional().describe(`Seconds kept at each edge of a cut (default ${Vo}).`),useAudio:Yt.boolean().optional().describe("Require silent audio too (default true when there is audio)."),action:Yt.enum(["cut","speed"]).optional().describe("cut (default), or speed: fast-forward them."),factor:Yt.number().gt(1).max(Zr).optional().describe(`speed: times faster (default ${Qo}).`),dryRun:Yt.boolean().optional().describe("Only report what would be cut."),output:Yt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Yt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Wb(t){t.registerTool("cut_idle",{title:"Cut Idle Stretches",description:"Remove dead air: cut stretches where the screen is frozen (and silent), keeping a short pad. Returns the time saved.",inputSchema:_T,annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k();O(e.input);let o=await W(e.input),i=o.durationSec;if(i===null)throw new l(`Could not read duration of ${e.input}.`);let s=e.minIdleSec??en,a=e.keepSec??Vo,c=o.audioCodec!==null,u=(e.useAudio??!0)&&c,d=await se(n,ba(e.input,s,u),pe(i),{signal:r.signal});if(d.code!==0)throw new l(`Idle scan failed (exit ${d.code}): ${d.stderr.trim().slice(-400)}`);let p=wa(d.stderr,i),f=u?xa(p,ya(d.stderr,i)):p,m=Sa(f,s,a),h=e.action==="speed",b=e.factor??Qo,w=m.map(T=>({...T,factor:b})),g=Number((h?tn(w):m.reduce((T,M)=>T+(M.end-M.start),0)).toFixed(2)),y={cuts:m,...h?{action:"speed",factor:b}:{},removedSec:g,originalSec:Number(i.toFixed(2)),newDurationSec:Number((i-g).toFixed(2)),idleRule:u?"frozen video and silent audio":"frozen video"};if(e.dryRun||m.length===0)return S({...y,...m.length===0?{note:"No idle stretches found; nothing to cut."}:{dryRun:!0}});let v=Z(e.input),x=j(e.output,"trimmed-idle",v,{overwrite:e.overwrite}),R=h?Ea(e.input,x,w,{withAudio:c,fps:o.fps}):_a(e.input,x,m,c);return await U(R,{output:x,durationSec:i-g,inputDurationSec:i,extra:r}),S({outputPath:x,...y})}catch(n){return E(n)}})}import{z as et}from"zod";import{existsSync as Xb,readFileSync as IT,writeFileSync as FT}from"node:fs";var TT=["um","umm","uh","uhh","uhm","erm","er","ah","hmm","hm","mm","mhm"],jb=.5,zb=t=>t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),Ar=t=>Number(t.toFixed(3));function Hb(t){let e=[];return t.forEach((r,n)=>{let o=r.text.replace(/\s+/g," ").trim(),i=[...o.matchAll(/\S+/g)],s=o.length||1,a=r.end-r.start;i.forEach((c,u)=>{let d=c.index;e.push({cue:n,raw:c[0],norm:zb(c[0]),start:u===0?r.start:r.start+d/s*a,end:u===i.length-1?r.end:r.start+(d+c[0].length)/s*a,first:u===0,last:u===i.length-1})})}),e}var RT=t=>t.flatMap((e,r)=>e.norm?[r]:[]);function AT(t,e){let r=e.split(/\s+/).map(zb).filter(Boolean);if(r.length===0)throw new l(`Quote "${e}" has no words to match.`);let n=RT(t),o=[];for(let i=0;i+r.length<=n.length;i++)r.every((s,a)=>t[n[i+a]].norm===s)&&o.push([n[i],n[i+r.length-1]]);return o}function MT(t,e,r){let n=r;for(;t[n+1]&&!t[n+1].norm&&t[n+1].cue===t[r].cue;)n++;let o=t[e],i=t[n];return{start:Ar(o.start),end:Ar(i.end),text:t.slice(e,n+1).map(s=>s.raw).join(" "),exact:o.first&&i.last}}function CT(t){let e=[...t].filter(n=>n.end-n.start>.001).sort((n,o)=>n.start-o.start),r=[];for(let n of e){let o=r[r.length-1];o&&n.start<=o.end+.01?(n.end>o.end&&(o.end=n.end),o.text.includes(n.text)||(o.text=`${o.text} ${n.text}`),o.exact&&=n.exact):r.push({...n})}return r}function PT(t,e){let r=t.flatMap(o=>o.index===void 0?[]:[o.index]);if(r.length===0){let o=Number.isInteger(e)?t[e-1]:void 0;if(!o)throw new l(`No cue ${e}: the transcript has cues 1-${t.length}.`);return o}let n=t.filter(o=>o.index===e);if(n.length>1)throw new l(`The transcript numbers ${n.length} cues ${e}; quote the text to cut instead.`);if(n.length===0)throw new l(`No cue ${e}: the transcript's cues are numbered ${Math.min(...r)}-${Math.max(...r)} (a cue with no duration, or wholly overlapped by the next, has no time to cut).`);return n[0]}function Gb(t,e){let r=Hb(t),n=[];for(let i of e.remove??[]){if(typeof i=="number"){let a=PT(t,i);n.push({start:Ar(a.start),end:Ar(a.end),text:a.text.replace(/\s+/g," "),exact:!0});continue}let s=AT(r,i);if(s.length===0)throw new l(`Quote not found in the transcript: "${i}".`);if(s.length>1)throw new l(`Quote "${i}" occurs ${s.length} times; quote more words or use cue numbers.`);n.push(MT(r,...s[0]))}let o=0;if(e.fillers){let i=new Set(TT);r.forEach(s=>{if(!i.has(s.norm))return;if(!r.every(p=>p.cue!==s.cue||p===s||!p.norm)){o++;return}let c=t[s.cue],u=Math.max(t[s.cue-1]?.end??0,c.start-jb),d=Math.min(t[s.cue+1]?.start??1/0,c.end+jb);n.push({start:Ar(Math.min(u,c.start)),end:Ar(Math.max(d,c.end)),text:r.filter(p=>p.cue===s.cue).map(p=>p.raw).join(" "),exact:!0})})}return{cuts:CT(n),skippedFillers:o}}function Ub(t,e){let r=0;for(let n of e){if(t<=n.start)break;r+=Math.min(t,n.end)-n.start}return t-r}function qb(t,e){let r=Hb(t),n=i=>e.some(s=>i.start>=s.start-5e-4&&i.end<=s.end+5e-4),o=[];return t.forEach((i,s)=>{let a=r.filter(f=>f.cue===s),c=a.filter(f=>!n(f));if(!c.some(f=>f.norm))return;let u=c.length===a.length?i.text:c.map(f=>f.raw).join(" "),d=Ar(Ub(i.start,e)),p=Ar(Ub(i.end,e));p>d&&o.push({start:d,end:p,text:u})}),o}var OT={input:et.string().min(1).describe("Path to the source video."),srt:et.string().min(1).describe("Its .srt (transcribe; words: true for word timing)."),remove:et.array(et.union([et.number().int().min(0).max(99999),et.string().min(1)])).optional().describe("Cue numbers as the .srt numbers them, or transcript text quoted exactly (must occur once)."),fillers:et.boolean().optional().describe("Also cut fillers (um, uh...) that have their own cue."),dryRun:et.boolean().optional().describe("Only report the cuts."),output:et.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:et.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Jb(t){t.registerTool("cut_by_transcript",{title:"Cut By Transcript",description:"Edit a video by its transcript: cut quoted text, cue numbers, or fillers. Also writes the re-timed .srt.",inputSchema:OT,outputSchema:B({cuts:et.array(et.unknown()),removedSec:et.number()}),annotations:I},async(e,r)=>{try{k();for(let b of[e.input,e.srt])if(!Xb(b))throw new l(`File not found: ${b}`);if(!e.remove?.length&&!e.fillers)throw new l("Nothing to cut: pass remove and/or fillers: true.");let n=await W(e.input),o=n.durationSec;if(o===null||!n.videoCodec)throw new l(`Not a readable video: ${e.input}`);let i=pt(Ue(IT(e.srt,"utf8"),{index:!0}));if(i.length===0)throw new l(`No cues in ${e.srt}.`);let{cuts:s,skippedFillers:a}=Gb(i,{remove:e.remove,fillers:e.fillers});if(s.length>qn)throw new l(`Too many cuts (${s.length}, max ${qn}); cut in batches.`);let c=Number(s.reduce((b,w)=>b+Math.min(w.end,o)-Math.min(w.start,o),0).toFixed(2)),u=qb(i,s),d=[s.length===0&&"Nothing matched; nothing to cut.",a>0&&`${a} filler(s) inside longer cues were kept; transcribe with words: true to cut them.`,s.some(b=>!b.exact)&&"Some edges were estimated inside a cue; transcribe with words: true for word timing."].filter(Boolean),p={cuts:s,removedSec:c,originalSec:Number(o.toFixed(2)),newDurationSec:Number((o-c).toFixed(2)),...d.length?{note:d.join(" ")}:{}};if(e.dryRun||s.length===0){let b=u.map(w=>w.text.replace(/\n/g," ")).join(" ");return S({...p,...s.length?{dryRun:!0}:{},text:b.length>4e3?`${b.slice(0,4e3)}\u2026`:b})}let f=Z(e.input),m=j(e.output,"cut-transcript",f,{overwrite:e.overwrite}),h=m.replace(/\.[^.\\/]+$/,"")+".srt";if(!e.overwrite&&Xb(h))throw new l(`Output already exists: ${h}. Pass overwrite: true to replace it.`);return await U(_a(e.input,m,s,n.audioCodec!==null),{output:m,durationSec:o-c,inputDurationSec:o,extra:r}),FT(h,it(u)),S({outputPath:m,srtPath:h,...p})}catch(n){return E(n)}})}import{z as nn}from"zod";var NT={input:nn.string().min(1).describe("Path to the source video or image (png/jpg; time ranges are ignored for an image)."),regions:nn.array(xn).min(1).describe("Pixel rectangles (x, y, width, height), each optionally limited to start..end seconds."),style:nn.enum(Oi).optional().describe("box (default): irreversible fill; blur/pixelate are partially recoverable."),pad:nn.number().int().nonnegative().optional().describe("Grow each region by this many px (default 0)."),color:nn.string().optional().describe("Box fill color (default black)."),output:nn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:nn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Yb(t){t.registerTool("redact_region",{title:"Redact Regions",description:"Cover given rectangles in a video or screenshot (e.g. secrets on screen). Not automatic detection: find them with find_text redact: true. Off-frame regions are rejected.",inputSchema:NT,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let{width:n,height:o,durationSec:i}=await W(e.input),{still:s,ext:a}=Ni(e.input,e.output),c=j(e.output,"redact",a,{overwrite:e.overwrite,anyContainer:!0}),u=jp(e.input,c,e.regions,{style:e.style,pad:e.pad,color:e.color},{width:n,height:o},s);return await U(u,{output:c,durationSec:s?null:i,extra:r}),S({outputPath:c,regions:e.regions.length,style:e.style??"box"})}catch(n){return E(n)}})}import{z as Ya}from"zod";function Kb(t){t.registerTool("list_audio_devices",{title:"List Audio Devices",description:"List DirectShow audio devices and flag a likely loopback (Stereo Mix or a virtual-audio driver), for start_recording's audio.device.",inputSchema:{},outputSchema:B({devices:Ya.array(Ya.unknown()),loopbackDevice:Ya.string().nullable(),note:Ya.string()}),annotations:fe},async()=>{try{k();let e=await tu(!0),r=eu(e);return S({devices:e,loopbackDevice:r,note:r?`Pass "${r}" as the audio device to capture system audio.`:`No loopback device detected. ${Co}`})}catch(e){return E(e)}})}import{z as me}from"zod";function Qb(t){return t.hwnd!==void 0?`window:hwnd=${t.hwnd}`:`window:${t.title}`}function DT(t){let e=/^.*?[.!?](?=\s|$)/.exec(t);return e?e[0]:t}function Vb(t,e,r){try{return Dc(t,Qb(e).slice(7),{allowCloaked:r,exactOnly:!0}),{ok:!0}}catch(n){return{ok:!1,reason:DT(z(n))}}}function Zb(t,e,r){let n=r.filter??{},o=n.exe?Nc(`exe=${n.exe}`):null,i=o?.kind==="exe"?o.exe:null,s=n.titleContains?.trim().toLowerCase()||null,a=yo(t),c=t.length>0?a:e.virtual,u=[];for(let d of Array.isArray(e.windows)?e.windows:[]){if(i!==null&&(d.exe??"").toLowerCase().replace(/\.exe$/,"")!==i||s!==null&&!d.title.toLowerCase().includes(s))continue;let p=Vb(e,d,!1),f=r.wgcAvailable&&d.hwnd!==void 0?Vb(e,d,!0):{ok:!1};n.capturableOnly&&!p.ok&&!f.ok||u.push({target:Qb(d),title:d.title,exe:d.exe||null,pid:typeof d.pid=="number"?d.pid:null,hwnd:d.hwnd??null,bounds:{x:d.left,y:d.top,width:d.right-d.left,height:d.bottom-d.top},minimized:!!d.minimized,cloaked:!!d.cloaked,capturable:p.ok,wgcCapturable:f.ok,...p.ok?{}:{reason:p.reason}})}return{full:{target:"full",bounds:{x:c.x,y:c.y,width:c.w,height:c.h}},monitors:t.map(d=>({target:`monitor:${d.index}`,index:d.index,primary:d.primary,bounds:{x:d.x,y:d.y,width:d.width,height:d.height},dpi:d.dpi??null,scale:d.dpi?Math.round(d.dpi/96*100)/100:null})),windows:u,wgcAvailable:r.wgcAvailable}}var LT={exe:me.string().min(1).optional().describe("Only list windows of this executable, e.g. 'Code.exe' or 'code'."),titleContains:me.string().min(1).optional().describe("Only list windows whose title contains this text (case-insensitive)."),capturableOnly:me.boolean().optional().describe("Leave out windows neither backend can capture (minimized, off screen). Default false.")},xl=me.object({x:me.number(),y:me.number(),width:me.number(),height:me.number()}),BT=B({full:me.looseObject({target:me.literal("full"),bounds:xl}),monitors:me.array(me.looseObject({target:me.string(),index:me.number(),primary:me.boolean(),bounds:xl,dpi:me.number().nullable(),scale:me.number().nullable()})),windows:me.array(me.looseObject({target:me.string(),title:me.string(),exe:me.string().nullable(),pid:me.number().nullable(),hwnd:me.number().nullable(),bounds:xl,minimized:me.boolean(),cloaked:me.boolean(),capturable:me.boolean(),wgcCapturable:me.boolean()})),wgcAvailable:me.boolean(),note:me.string()});function ew(t){t.registerTool("list_targets",{title:"List Capture Targets",description:"List the desktop, monitors, and visible windows (topmost first, with capturability per backend). Each entry has a `target` string to pass as-is to capture tools; use it instead of guessing a title.",inputSchema:LT,outputSchema:BT,annotations:fe},async e=>{try{let[r,n]=await Promise.all([lr(),Lc()]),o=Zb(r,n,{wgcAvailable:cr(),filter:{exe:e.exe,titleContains:e.titleContains,capturableOnly:e.capturableOnly}});return S({...o,note:'Pass a target string unchanged. A window handle lasts until the app closes the window; list again after an app restarts, or target it by window:exe=<app.exe>. A window with capturable false but wgcCapturable true needs backend: "wgc".'})}catch(r){return E(r)}})}import{existsSync as Qa}from"node:fs";import{dirname as JT,join as vl}from"node:path";import{z as de}from"zod";import{readdir as WT,stat as jT,statfs as UT}from"node:fs/promises";import{join as rw}from"node:path";var nw=2*1024**3,tw=["recordings","edits","screenshots","frames"];async function ow(t){let e;try{e=await WT(t,{withFileTypes:!0})}catch{return 0}let r=0;for(let n of e){let o=rw(t,n.name);n.isDirectory()?r+=await ow(o):n.isFile()&&(r+=await jT(o).then(i=>i.size,()=>0))}return r}async function Sl(t){try{let e=await UT(t);return Number(e.bavail)*Number(e.bsize)}catch{return null}}async function iw(t){let[e,...r]=await Promise.all([Sl(t),...tw.map(o=>ow(rw(t,o)))]),n=Object.fromEntries(tw.map((o,i)=>[o,r[i]??0]));return{freeBytes:e??null,bytes:n}}function sw(t){let e=["B","KB","MB","GB","TB"],r=t,n=0;for(;r>=1024&&n<e.length-1;)r/=1024,n++;return`${n===0?r:r.toFixed(1)} ${e[n]}`}var aw=200,cw=1e3,Ka=.5,Va=3,on=t=>Math.round(t*1e3)/1e3;function lw(t,e){if(t.length===0)throw new l("lines is empty: give at least one { t | marker, text }.");if(t.length>aw)throw new l(`At most ${aw} lines are allowed (got ${t.length}).`);return t.map((n,o)=>{let i=n.text.replace(/\s+/g," ").trim();if(!i)throw new l(`lines[${o}] has no text.`);if(i.length>cw)throw new l(`lines[${o}] is ${i.length} characters; at most ${cw} are allowed. Split it.`);if(n.t!==void 0&&n.marker!==void 0)throw new l(`lines[${o}] has both t and marker; give one.`);if(n.t!==void 0){if(!Number.isFinite(n.t)||n.t<0)throw new l(`lines[${o}].t must be a non-negative number.`);return{t:on(n.t),text:i}}if(n.marker!==void 0){let s=n.marker.trim().toLowerCase(),a=e.find(c=>c.label.trim().toLowerCase()===s);if(!a){let c=e.map(u=>`"${u.label}"`).join(", ");throw new l(`lines[${o}]: no marker labelled "${n.marker}".`,c?`Markers on this video: ${c}.`:"This video has no markers; add_marker stamps one, or give t.")}return{t:on(a.t),text:i}}throw new l(`lines[${o}] needs t (seconds) or marker (a marker label).`)}).sort((n,o)=>n.t-o.t)}function pw(t,e){let r=[];return t.forEach((n,o)=>{let i=n.t+n.durationSec,s=t[o+1],a=`"${n.text.length>40?`${n.text.slice(0,40)}...`:n.text}"`;n.t>=e?r.push(`Line at ${n.t}s ${a} starts after the video ends (${on(e)}s) and is not heard.`):s&&i>s.t+.05?r.push(`Line at ${n.t}s ${a} runs ${on(i-s.t)}s past the next line (${s.t}s); they overlap. Move the next line, shorten this one, or raise rate.`):i>e+.05&&r.push(`Line at ${n.t}s ${a} runs ${on(i-e)}s past the end of the video and is cut off.`)}),r}function dw(t,e){return t.map((r,n)=>{let o=t[n+1],i=Math.min(r.t+r.durationSec,o?o.t:1/0,e);return{start:r.t,end:on(i),text:r.text}}).filter(r=>r.end>r.start)}function mw(t){if(t.length<12||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WAVE")throw new l("The speech engine did not return a WAV file.");let e=0;for(let r=12;r+8<=t.length;){let n=t.toString("ascii",r,r+4),o=t.readUInt32LE(r+4);if(n==="fmt "&&r+16<=t.length&&(e=t.readUInt32LE(r+16)),n==="data"){if(e<=0)break;let i=t.length-(r+8);return(o===0||o===4294967295||o>i?i:o)/e}r+=8+o+o%2}throw new l("Could not read the WAV header the speech engine wrote.")}function fw(t,e,r,n,o,i){if(!Number.isFinite(o)||o<=0)throw new l("video duration must be known and positive.");if(e.length===0||e.length!==n.length)throw new l("Every placed line needs its WAV.");let s=on(o),a=h=>`amix=inputs=${h}:duration=longest:dropout_transition=0:normalize=0`,c=n.map((h,b)=>{let w=Math.round(h.t*1e3);return`[${b+1}:a]aresample=48000,aformat=channel_layouts=mono,adelay=${w}[l${b}]`}),u=n.map((h,b)=>`[l${b}]`).join(""),d=!(i.hasAudio&&i.channels===1),p=`apad,atrim=end=${s}${d?",pan=stereo|c0=c0|c1=c0":""}`,f=i.hasAudio?"voice":"aout";c.push(n.length>1?`${u}${a(n.length)},${p}[${f}]`:`[l0]${p}[${f}]`),i.hasAudio&&(c.push(`[0:a]aresample=48000,aformat=channel_layouts=${d?"stereo":"mono"}[orig]`),i.duck??!0?(c.push("[voice]asplit=2[vo][key]"),c.push("[orig][key]sidechaincompress=threshold=0.02:ratio=8:attack=20:release=400[bed]"),c.push(`[bed][vo]${a(2)}[aout]`)):c.push(`[orig][voice]${a(2)}[aout]`));let m=Ii(r);return["-y","-i",t,...e.flatMap(h=>["-i",h]),"-filter_complex",c.join(";"),...m?[]:["-map","0:v?","-c:v","copy"],"-map","[aout]","-t",String(s),...Ha(r),.../\.(mp4|mov|m4a)$/i.test(r)?["-movflags","+faststart"]:[],r]}var zT=3e4,HT=1e4,uw=3e4,hw=t=>Array.isArray(t)?t:t==null?[]:[t];function gw(t){return hw(t.voices).map(e=>({name:String(e.name??""),language:String(e.language??""),gender:String(e.gender??"")}))}function GT(t){return{script:XT,payload:JSON.stringify(t)}}async function bw(t,e,r){if(process.platform!=="win32")throw new l("narrate uses the speech engine built into Windows and runs on Windows only.");let{script:n,payload:o}=GT(t),i="list"in t,s=await ct(n,i?"speech voices":"the speech engine",{timeoutMs:e,signal:r,payload:o,failure:i?"Could not list speech voices":"Could not synthesize speech"});try{return JSON.parse(s)}catch(a){throw new l(`Could not parse the speech engine's output: ${z(a)}`)}}async function qT(t){let e=await bw({list:!0},ur(15e3),t);if(e.error)throw new l(`Windows speech is unavailable: ${e.error}`);return gw(e)}async function ww(){if(process.platform!=="win32")return{available:!1,voices:[],error:"Windows speech is available on Windows only."};try{let t=(await qT()).map(e=>`${e.name} (${e.language})`);return{available:t.length>0,voices:t,...t.length?{}:{error:"No speech voices are installed."}}}catch(t){return{available:!1,voices:[],error:z(t)}}}async function yw(t,e){let r=e.rate??1;if(!Number.isFinite(r)||r<Ka||r>Va)throw new l(`rate must be between ${Ka} and ${Va} (1 is normal speed).`);let n=await bw({voice:e.voice??null,rate:r,items:t},ur(zT+t.length*HT),e.signal);if(n.error){let o=gw(n);throw n.error==="unknown voice"?new l(`No installed voice matches "${e.voice}".`,o.length?`Installed voices: ${o.map(i=>`${i.name} (${i.language})`).join(", ")}.`:"No voices are installed."):new l(`Windows speech is unavailable: ${n.error}`,"Install a voice: Settings > Time & language > Speech > Manage voices.")}return hw(n.results).forEach((o,i)=>{if(o.error)throw new l(`Could not synthesize line ${i+1}: ${o.error}`)}),String(n.voice??"")}var XT=`
341
342
  $ErrorActionPreference = 'Stop'
342
343
  function Out($o) { ConvertTo-Json -InputObject $o -Depth 5 -Compress }
343
344
  try {
@@ -361,7 +362,7 @@ try {
361
362
  $results = foreach ($item in @($req.items)) {
362
363
  try {
363
364
  $task = $asTask.MakeGenericMethod([Windows.Media.SpeechSynthesis.SpeechSynthesisStream]).Invoke($null, @($synth.SynthesizeTextToStreamAsync([string]$item.text)))
364
- if (-not $task.Wait(${tw})) { throw "The speech engine did not answer within ${tw/1e3} s." }
365
+ if (-not $task.Wait(${uw})) { throw "The speech engine did not answer within ${uw/1e3} s." }
365
366
  $stream = $task.Result
366
367
  $in = [System.IO.WindowsRuntimeStreamExtensions]::AsStreamForRead($stream)
367
368
  $fs = [System.IO.File]::Create([string]$item.path)
@@ -371,10 +372,10 @@ try {
371
372
  }
372
373
  Out ([pscustomobject]@{ voice = $synth.Voice.DisplayName; results = @($results) })
373
374
  } catch { Out ([pscustomobject]@{ error = $_.Exception.Message }) }
374
- `;var FT=wt(),dw=pe.looseObject({found:pe.boolean(),path:pe.string().nullable(),version:pe.string().nullable(),major:pe.number().nullable()}),OT=N({ok:pe.boolean(),problems:pe.array(pe.string()),server:pe.looseObject({version:pe.string(),node:pe.string(),platform:pe.string(),arch:pe.string()}),ffmpeg:dw.extend({meetsFfmpeg8:pe.boolean().nullable()}),ffprobe:dw,filters:pe.record(pe.string(),pe.boolean()),devices:pe.looseObject({gdigrab:pe.boolean(),dshow:pe.boolean()}),wgc:pe.looseObject({available:pe.boolean()}),ocr:pe.looseObject({available:pe.boolean(),language:pe.string().nullable(),languages:pe.array(pe.string())}),storage:pe.looseObject({home:pe.string(),homeExists:pe.boolean()}),env:pe.record(pe.string(),pe.string().nullable())});function NT(t){let e=E(t).content[0];return e?.type==="text"?e.text.replace(/\s*\n+\s*/g," "):String(t)}function mw(t){let e=ua(t),r=ca(e??"");return{found:e!==null,path:e!==null?fg(t):null,version:r.version,major:r.major,...r.inferred?{majorInferred:!0}:{}}}function fw(t){t.registerTool("doctor",{title:"Check Setup",description:`Check the setup: ffmpeg/ffprobe (FFmpeg ${Hr}+?), optional filters, capture devices, Windows OCR, settings, and enabled toolsets; \`problems\` says what is missing and how to fix it. Call on first use or when a tool reports a missing feature.`,inputSchema:{},outputSchema:OT,annotations:he},async()=>{try{let e=[],r=null;try{r=Rc()}catch(b){e.push(NT(b))}let n=mw(r?.ffmpeg??(process.env.FFMPEG_PATH?.trim()||"ffmpeg")),o=mw(r?.ffprobe??(process.env.FFPROBE_PATH?.trim()||"ffprobe")),i=n.major===null?null:n.major>=Hr;r&&i===!1&&e.push(`FFmpeg ${n.version} is older than ${Hr}: transcribe and backend "wgc" need FFmpeg ${Hr}+. Windows: \`winget install Gyan.FFmpeg\`.`);let s={},a={gdigrab:!1,dshow:!1};if(r){for(let w of bg)s[w.filter]=w.filter==="gfxcapture"?ir():Ye(w.filter),!s[w.filter]&&!(w.filter==="gfxcapture"&&process.platform!=="win32")&&e.push(`No ${w.filter} filter: ${w.tools} unavailable (needs ${w.why}).`);let b=dg(mg(r.ffmpeg)??"");a={gdigrab:b.includes("gdigrab"),dshow:b.includes("dshow")},process.platform==="win32"&&!a.gdigrab&&e.push("This ffmpeg has no gdigrab device: screenshot and start_recording cannot capture the screen.")}process.platform!=="win32"&&e.push("Not Windows: capture (screenshot, start_recording, list_targets) and OCR are unavailable; the watch and edit tools work.");let c=r?{ddagrab:process.platform==="win32"&&Ye("ddagrab"),encoders:await Uc(r.ffmpeg)}:null,[u,d]=await Promise.all([wr(),lw()]);process.platform==="win32"&&!u.available&&e.push(`Windows OCR unavailable: find_text cannot read the screen. ${u.error??"Install an OCR language (Settings > Time & language > Language)."}`),process.platform==="win32"&&!d.available&&e.push(`Windows speech unavailable: narrate cannot speak. ${d.error??""} Install a voice (Settings > Time & language > Speech).`.replace(/\s+/g," "));let p=gg(),f=p.SCREENCAST_WHISPER_MODEL;f&&!xl(f)&&e.push(`SCREENCAST_WHISPER_MODEL points at a missing file: ${f}`);let m=Me();for(let b of ho())xl(b)||e.push(`SCREENCAST_ALLOWED_DIRS names a missing folder: ${b}`);let h=gi(p.SCREENCAST_TOOLSETS??void 0);return h.unknown.length>0&&e.push(`SCREENCAST_TOOLSETS names unknown toolsets (ignored): ${h.unknown.join(", ")}.`),e.push(...hg()),v({ok:e.length===0,problems:e,server:{version:FT,node:process.version,platform:process.platform,arch:process.arch},ffmpeg:{...n,meetsFfmpeg8:i},ffprobe:o,filters:s,devices:a,wgc:{available:s.gfxcapture===!0},...c?{gpu:c}:{},ocr:u,tts:d,storage:{home:m,homeExists:xl(m),recordings:Sl(m,"recordings"),screenshots:Sl(m,"screenshots"),edits:Sl(m,"edits"),allowedOutputDirs:Mr()},env:p,toolsets:{enabled:h.enabled,available:["all",...hi]}})}catch(e){return E(e)}})}import{z as Qn}from"zod";var DT={inputA:Qn.string().min(1).describe("Outgoing video."),inputB:Qn.string().min(1).describe("Incoming video."),transition:Qn.string().optional().describe("xfade name (default fade): fade, wipeleft, slideup, circleopen, dissolve, ..."),duration:Qn.number().positive().optional().describe(`Transition length in seconds (default ${Bn}).`),output:Qn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Qn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function hw(t){t.registerTool("xfade_transition",{title:"Crossfade Transition",description:"Join two videos with an xfade transition (audio crossfaded); they need not match in size, fps, or audio. For more clips use assemble_highlights.",inputSchema:DT,outputSchema:Y,annotations:I},async(e,r)=>{try{k();for(let p of[e.inputA,e.inputB])F(p);let[n,o]=await Promise.all([L(e.inputA),L(e.inputB)]),i=qr(n),s=qr(o);if(i===null||s===null)throw new l(`Could not read duration of ${i===null?e.inputA:e.inputB}.`);let a=[n.audioCodec!==null,o.audioCodec!==null],c=a[0]||a[1],u=B(e.output,"xfade",".mp4",{overwrite:e.overwrite}),d=Tg(e.inputA,e.inputB,[i,s],u,{transition:e.transition,duration:e.duration},a);return await W(d,{output:u,durationSec:i+s,extra:r}),v({outputPath:u,audio:c})}catch(n){return E(n)}})}import{z as Xt}from"zod";var LT={clips:Xt.array(Xt.string().min(1)).min(2).describe("Clip paths, in order."),transition:Xt.string().optional().describe("cut (default) or an xfade name (fade, wipeleft, slideup, ...)."),duration:Xt.number().positive().optional().describe(`Transition seconds (default ${Bn}).`),width:Xt.number().int().positive().optional().describe("Common output width (default 1920)."),height:Xt.number().int().positive().optional().describe("Common output height (default 1080)."),fps:Xt.number().int().positive().optional().describe("Common output fps (default 30)."),output:Xt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Xt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function gw(t){t.registerTool("assemble_highlights",{title:"Assemble Highlights",description:"Stitch clips (including title cards) into one video with cuts or xfade transitions; they need not match in size, fps, or audio.",inputSchema:LT,outputSchema:Y,annotations:I},async(e,r)=>{try{k();for(let c of e.clips)F(c);let n=await Promise.all(e.clips.map(c=>L(c))),o=n.map(c=>qr(c)??0),i=n.map(c=>c.audioCodec!==null),s=B(e.output,"highlights",".mp4",{overwrite:e.overwrite}),a=Jo(e.clips,o,s,{transition:e.transition,duration:e.duration,width:e.width,height:e.height,fps:e.fps},i);return await W(a,{output:s,durationSec:o.reduce((c,u)=>c+u,0)||null,extra:r}),v({outputPath:s,clips:e.clips.length,transition:e.transition??"cut",audio:i.some(Boolean)})}catch(n){return E(n)}})}import{z as mt}from"zod";import{writeFileSync as BT,rmSync as WT}from"node:fs";var jT={text:mt.string().min(1).describe("Title text. Multiple lines are allowed (use \\n)."),duration:mt.number().positive().optional().describe("Card length in seconds (default 3)."),width:mt.number().int().positive().optional().describe("Card width (default 1920)."),height:mt.number().int().positive().optional().describe("Card height (default 1080)."),fps:mt.number().int().positive().optional().describe("Card fps (default 30)."),bg:mt.string().optional().describe("Background color (default black)."),fontColor:mt.string().optional().describe("Text color (default white)."),fontSize:mt.number().int().positive().optional().describe("Text size in px (default 96)."),bold:mt.boolean().optional().describe("Use the bold weight (default true)."),fontFile:vr,output:mt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:mt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function bw(t){t.registerTool("title_card",{title:"Title Card",description:"Generate a title card clip (centered text on a solid background, silent audio track) to stitch in with assemble_highlights. Uncoverable characters are reported in warnings.",inputSchema:jT,outputSchema:Y,annotations:I},async(e,r)=>{try{k();let n=B(e.output,"title",".mp4",{overwrite:e.overwrite}),o=vt(e.text,{weight:e.bold===!1?"regular":"bold",fontFile:e.fontFile}),i=Ue(".txt");BT(i,e.text);try{let s=Ag(i,o.fontFile,n,{duration:e.duration,width:e.width,height:e.height,fps:e.fps,bg:e.bg,fontColor:e.fontColor,fontSize:e.fontSize});await W(s,{output:n,durationSec:e.duration??Yu,extra:r})}finally{WT(i,{force:!0})}return v({outputPath:n,...(o.fallback||e.fontFile)&&{fontFile:o.fontFile},...o.warning&&{warnings:[o.warning]}})}catch(n){return E(n)}})}import{z as _r}from"zod";var UT={video:_r.string().min(1).describe("Path to the video."),music:_r.string().min(1).describe("Music audio file."),musicVolume:_r.number().nonnegative().optional().describe("0..1 (default 0.25 over existing audio, 0.8 alone)."),fadeIn:_r.number().nonnegative().optional().describe("Fade-in seconds (default 1)."),fadeOut:_r.number().nonnegative().optional().describe("Fade-out seconds (default 2)."),duck:_r.boolean().optional().describe("Duck the music under the original audio (default false)."),output:_r.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:_r.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function ww(t){t.registerTool("music_bed",{title:"Add Music Bed",description:"Lay music under a video: looped or trimmed to length, faded, leveled, and mixed with any existing audio. Video is stream-copied.",inputSchema:UT,outputSchema:Y,annotations:I},async(e,r)=>{try{k();for(let a of[e.video,e.music])F(a);let n=await L(e.video);if(n.durationSec===null)throw new l(`Could not read duration of ${e.video}.`);let o=V(e.video),i=B(e.output,"music",o,{overwrite:e.overwrite}),s=Rg(e.video,e.music,i,n.durationSec,n.audioCodec!==null,{musicVolume:e.musicVolume,fadeIn:e.fadeIn,fadeOut:e.fadeOut,duck:e.duck});return await W(s,{output:i,durationSec:n.durationSec,extra:r}),v({outputPath:i,mixedWithOriginal:n.audioCodec!==null})}catch(n){return E(n)}})}import{z as ft}from"zod";import{existsSync as zT,mkdtempSync as HT,readFileSync as GT,rmSync as qT,writeFileSync as XT}from"node:fs";import{tmpdir as JT}from"node:os";import{join as yw}from"node:path";var YT={video:ft.string().min(1).describe("Path to the video."),lines:ft.array(ft.object({t:ft.number().nonnegative().optional().describe("Seconds."),marker:ft.string().optional().describe("Or a marker label."),text:ft.string().min(1)})).min(1),voice:ft.string().optional().describe("Voice name or part (doctor lists them)."),rate:ft.number().min(Ka).max(Va).optional().describe("Default 1."),duck:ft.boolean().optional().describe("Duck the original audio (default true)."),output:ft.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ft.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function xw(t){t.registerTool("narrate",{title:"Narrate",description:"Offline voiceover with the built-in Windows voices: speaks each line at its time or marker over the audio, plus an SRT.",inputSchema:YT,outputSchema:Y,annotations:I},async(e,r)=>{let n=null;try{k(),F(e.video);let o=await L(e.video);if(o.durationSec===null)throw new l(`Could not read duration of ${e.video}.`);let s=e.lines.some(w=>w.marker!==void 0)?(await mr(e.video,r.signal)).markers:[],a=rw(e.lines,s),c=B(e.output,"narrated",V(e.video),{overwrite:e.overwrite}),u=c.replace(/\.[^./\\]+$/,"")+".srt";if(!e.overwrite&&zT(u))throw new l(`Output already exists: ${u}. Pass overwrite: true to replace it.`);n=HT(yw(JT(),"screencast-tts-"));let d=a.map((w,g)=>yw(n,`line-${g}.wav`)),p=await pw(a.map((w,g)=>({text:w.text,path:d[g]})),{voice:e.voice,rate:e.rate,signal:r.signal}),f=a.map((w,g)=>({...w,durationSec:iw(GT(d[g]))})),m=nw(f,o.durationSec),h=sw(e.video,d,c,f,o.durationSec,{hasAudio:o.audioCodec!==null,channels:o.channels,duck:e.duck});await W(h,{output:c,durationSec:o.durationSec,extra:r}),XT(u,nt(ow(f,o.durationSec)));let b=Le(e.video);return b.length>0&&dr(c,b),v({outputPath:c,srtPath:u,voice:p,lines:f.map(w=>({t:w.t,durationSec:Math.round(w.durationSec*100)/100})),mixedWithOriginal:o.audioCodec!==null,...m.length?{warnings:m}:{}})}catch(o){return E(o)}finally{n&&qT(n,{recursive:!0,force:!0})}})}import{z as ai}from"zod";var KT={input:ai.string().min(1).describe("Path to the source video."),aspect:ai.enum(Wn).describe("Target aspect ratio."),fit:ai.enum(la).optional().describe("pad (default): letterbox, nothing lost. crop: fill and center-crop."),output:ai.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ai.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Sw(t){t.registerTool("reframe",{title:"Reframe Aspect Ratio",description:"Re-aspect a video to 16:9, 9:16, 1:1, or 4:5 by padding or cropping.",inputSchema:KT,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=V(e.input),o=B(e.output,"reframe",n,{overwrite:e.overwrite}),i=Mg(e.input,o,e.aspect,e.fit??"pad");return await W(i,{output:o,durationSec:await se(e.input),extra:r}),v({outputPath:o,aspect:e.aspect,fit:e.fit??"pad"})}catch(n){return E(n)}})}import{z as Xe}from"zod";import{z as en}from"zod";import{existsSync as VT,readFileSync as QT}from"node:fs";var Jt=.6,ui=6,Qa=2.5;function Za(t,e,r,n=ui){if(t.length===0)throw new l("Give at least one keyframe.");let i=[...t].sort((s,a)=>s.t-a.t).map(s=>{if(!Number.isFinite(s.t)||s.t<0)throw new l("Keyframe t must be a non-negative number.");if(s.full||s.width===void 0||s.height===void 0)return{t:s.t,z:1,cx:e/2,cy:r/2};if(!(s.width>0)||!(s.height>0))throw new l("Keyframe width and height must be positive.");let a=Math.max(1,Math.min(n,e/s.width,r/s.height));return{t:s.t,z:a,cx:(s.x??0)+s.width/2,cy:(s.y??0)+s.height/2}});return i[0]&&i[0].t>0&&i.unshift({t:0,z:1,cx:e/2,cy:r/2}),i}var Ze=t=>Number(t.toFixed(4)).toString();function vl(t,e,r){let[n,...o]=t;if(!n)throw new l("Give at least one keyframe.");let i=[Ze(n[e])],s=n;for(let a of o){let c=s[e],u=a[e],d=s.t;if(s=a,c===u)continue;let p=a.t,f=Math.max(.001,Math.min(r,p-d)),m=`clip((it-${Ze(p-f)})/${Ze(f)},0,1)`;i.push(`(${Ze(u-c)})*${m}*${m}*(3-2*${m})`)}return _t(i)}function El(t,e,r=Jt){let{width:n,height:o,fps:i}=e,s=n<=1920?2:1,a=vl(t,"z",r),c=vl(t,"cx",r),u=vl(t,"cy",r);return`fps=${Ze(i)},scale=${n*s}:${o*s},zoompan=z='${a}':x='clip((${c})*${s}-iw/zoom/2,0,iw-iw/zoom)':y='clip((${u})*${s}-ih/zoom/2,0,ih-ih/zoom)':d=1:s=${n}x${o}:fps=${Ze(i)}`}function vw(t,e,r,n,o=Jt,i="standard",s){let{width:a,height:c,fps:u}=n,d=El(r,n,o);if(!s||s.clicks.length===0)return["-y","-i",t,"-vf",d,..._e(i),"-c:a","copy",e];let p=["[0:v]null[in]",...tA(s.clicks,a,c,u,s.color),`[out]${d}[v]`].join(";");return["-y","-i",t,"-filter_complex",p,"-map","[v]","-map","0:a?",..._e(i),"-c:a","copy",e]}function $w(t,e,r,n,o={}){let i=o.step??.25,s=o.holdSec??2,a=o.maxZoom??Qa,c=o.globalFraction??.3,u=o.transition??Jt,d=r/t,p=r/a,f=n/a,m=[],h=null,b=()=>{h&&m.push(h),h=null},w=null,g=0;return{push:S=>{let C=w;if(w=S,!C){g=1;return}let M=g++*i,R=kt(C,S,t,e,{scale:d});if(R.regions.length===0){h&&M-h.last>s&&b();return}if(R.changedFraction>c){b();return}let P=kl(R.regions);h&&M-h.last<=s&&ZT(h.box,P,r,n)?(h.box=kl([h.box,P]),h.last=M):(b(),h={start:M,last:M,box:P})},finish:()=>{b();let S=[],C=0;for(let M of m){let R=kw(M.box,r,n,p,f),P=Math.max(M.start,C+u),j=Math.max(M.last+s,P+u);S.push({t:ci(P),...R},{t:ci(j),full:!0}),C=j}return S}}}var ci=t=>Math.round(t*100)/100;function kl(t){let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,width:n-e,height:o-r}}function ZT(t,e,r,n){let o=kl([t,e]);return o.width<=r/2&&o.height<=n/2}function kw(t,e,r,n,o){let i=Math.max(t.width*1.4,n),s=Math.max(t.height*1.4,o),a=e/r;i/s>a?s=i/a:i=s*a,i=Math.min(i,e),s=Math.min(s,r);let c=t.x+t.width/2,u=t.y+t.height/2,d=Math.max(0,Math.min(e-i,c-i/2)),p=Math.max(0,Math.min(r-s,u-s/2));return{x:Math.round(d),y:Math.round(p),width:Math.round(i),height:Math.round(s)}}function Ew(t,e,r){return["-v","error","-i",t,"-an","-vf",`fps=${Ze(1/r)},scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function ec(t,e,r,n={}){let o=n.holdSec??2,i=n.maxZoom??Qa,s=n.transition??Jt,a=e/i,c=r/i,u=Math.min(e,r)*.05,d=[...t].sort((h,b)=>h.t-b.t),p=[],f=0,m=-1/0;for(let h of d){let b=kw({x:h.x-u,y:h.y-u,width:2*u,height:2*u},e,r,a,c),w=p[p.length-1];if(w&&!w.full&&h.t-m<=o&&eA(w,h)){m=h.t;continue}if(h.t-m>o&&p.length>0){let y=Math.max(m+o,f+s);p.push({t:ci(y),full:!0}),f=y}let g=Math.max(h.t,f+s);p.push({t:ci(g),...b}),f=g,m=h.t}return p.length>0&&p.push({t:ci(Math.max(m+o,f+s)),full:!0}),p}function eA(t,e){let r=t.width*.15,n=t.height*.15;return e.x>=t.x+r&&e.x<=t.x+t.width-r&&e.y>=t.y+n&&e.y<=t.y+t.height-n}var $l=.6,tc="#FF4545";function _l(t,e){return Math.max(40,2*Math.round(Math.min(t,e)*.045))}function tA(t,e,r,n,o){let i=_l(e,r),s=i/2,a=Math.max(3,Math.round(i/10)),c=s*.3,u=s-a/2-c,d=[],p="[in]";return t.forEach((f,m)=>{let h=`if(lt(abs(hypot(X-${s},Y-${s})-(${Ze(c)}+${Ze(u)}*T/${$l})),${a/2}),255*min(1,2-2*T/${$l}),0)`;d.push(`color=c=${o}:s=${i}x${i}:r=${Ze(n)}:d=${$l},format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${h}',setpts=PTS+${Ze(f.t)}/TB[ring${m}]`);let b=m===t.length-1?"[out]":`[r${m}]`;d.push(`${p}[ring${m}]overlay=x=${Ze(f.x-s)}:y=${Ze(f.y-s)}:eof_action=pass${b}`),p=`[r${m}]`}),d}function li(t){return VT(t)?je(QT(t,"utf8")).filter(e=>e.type==="down"&&e.inFrame).map(e=>({t:e.t,x:e.x,y:e.y})):null}var rc=en.object({t:en.number().nonnegative(),x:en.number().optional(),y:en.number().optional(),width:en.number().positive().optional(),height:en.number().positive().optional(),full:en.boolean().optional()});var _w=200,rA={input:Xe.string().min(1).describe("Path to the source video."),keyframes:Xe.array(rc).max(100).optional().describe("Views reached by time t: a source rectangle (x, y, width, height), or { t, full: true } to zoom out. Omit to plan them (see follow)."),follow:Xe.enum(["auto","clicks","changes"]).optional().describe("Without keyframes: clicks (from the events log of start_recording events: true) or changes (where the screen changed). auto (default): clicks if logged, else changes."),events:Xe.string().optional().describe("Events log (default: the input's .events.jsonl); must match the input's timing and size, so use the original recording."),highlightClicks:Xe.boolean().optional().describe("Ring each logged click (default false)."),highlightColor:Xe.string().optional().describe("Ring color (default #FF4545)."),transitionSec:Xe.number().positive().max(5).optional().describe(`How long each zoom/pan eases (default ${Jt}).`),maxZoom:Xe.number().min(1).max(ui).optional().describe(`Auto mode: the furthest it zooms in (default ${Qa}).`),holdSec:Xe.number().positive().max(30).optional().describe("Auto mode: stay zoomed this long after activity (default 2)."),dryRun:Xe.boolean().optional().describe("Return the planned keyframes only (editable, pass back)."),output:Xe.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Xe.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Tw(t){t.registerTool("zoom",{title:"Zoom and Pan",description:"Smooth animated zoom-and-pan into the action and back out, from keyframes or planned from logged clicks or screen changes.",inputSchema:rA,outputSchema:N({keyframes:Xe.array(Xe.unknown())}),annotations:I},async(e,r)=>{try{k(),F(e.input);let n=await L(e.input),{width:o,height:i,durationSec:s}=n;if(!o||!i)throw new l(`Could not read the size of ${e.input}.`);let a=n.fps??30,c=e.transitionSec??Jt,u=e.events??$e(e.input).jsonl,d=li(u);if(e.events&&!d)throw new l(`No event log at ${e.events}.`);if((e.follow==="clicks"||e.highlightClicks)&&!d)throw new l(`No event log for ${e.input} (looked for ${u}). Record with start_recording events: true, or pass events: <path to .events.jsonl>.`);let p=De(e.highlightColor??tc,"highlightColor"),f=e.keyframes,m=!f,h=e.follow==="clicks"||e.follow!=="changes"&&d&&d.length>0?"clicks":"changes";if(!f&&h==="clicks"&&(f=ec(d??[],o,i,{holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c}),f.length===0))return v({keyframes:[],follow:h,note:"The event log has no clicks inside the frame; nothing written."});if(!f){let $=Zh(o,i),S=.25,C=$w($.width,$.height,o,i,{step:S,holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c});if(await Wi(Ew(e.input,$,S),$.width*$.height,M=>C.push(M),le(s),{signal:r.signal}),f=C.finish(),f.length===0)return v({keyframes:[],note:"No localised changes found to zoom into; nothing written."})}if(e.dryRun)return v({planned:m,...m?{follow:h}:{},keyframes:f,transitionSec:c});if(e.highlightClicks&&d&&d.length>_w)throw new l(`${d.length} clicks is more than ${_w} rings; trim the video or the event log first.`);let b=Za(f,o,i),w=V(e.input),g=B(e.output,"zoom",w,{overwrite:e.overwrite}),y=e.highlightClicks?{clicks:d??[],color:p}:void 0;return await W(vw(e.input,g,b,{width:o,height:i,fps:a},c,"standard",y),{output:g,durationSec:s,extra:r}),v({outputPath:g,planned:m,...m?{follow:h}:{},keyframes:f,...y?{ringedClicks:y.clicks.length}:{}})}catch(n){return E(n)}})}import{z as O}from"zod";import{dirname as mA,join as tn}from"node:path";import{existsSync as ic,mkdtempSync as fA,readFileSync as Dw,rmSync as hA,writeFileSync as pi}from"node:fs";import{tmpdir as gA}from"node:os";var Zn=30,At=t=>Math.round(t*1e3)/1e3;function Tl(t,e){let r=[...t],n=r.indexOf("-af");return n!==-1&&e.audio.length>0&&(r[n+1]=`${e.audio.join(",")},${r[n+1]}`),r.splice(r.indexOf("-i"),0,...e.seek),r}function Aw(t,e,r){let n=e.slice(r);return n.length>0?as(t,n):[...t]}function nc(t,e,r,n,o={},i="standard",s={}){if(r.length===0)throw new l("Give at least one step.");if(r.length>Zn)throw new l(`At most ${Zn} steps.`);r.forEach((x,q)=>{if((x.op==="export_preset"||x.op==="export_gif")&&q!==r.length-1)throw new l(`${x.op} must be the last step (it is step ${q+1} of ${r.length}).`)});let a=r.findIndex(x=>x.op==="zoom"),c=a===-1?-1:r.findIndex((x,q)=>q>a&&x.op==="redact");if(c!==-1)throw new l(`step ${c+1}: redact comes after zoom (step ${a+1}), which moves the content under a fixed box. Put redact before zoom, in the source's coordinates.`);let u=r.some(x=>x.op==="redact");if(r.filter(x=>x.op==="cut_idle").length>1)throw new l("Use at most one cut_idle step.");let d=n.width,p=n.height,f=n.fps,m=n.durationSec,h=[],b=[],w=1,g=[],y=[],$=!1,S="[0:v]",C=null,M,R=[],P=[],j=[],X=[],D={sx:1,sy:1,ox:0,oy:0},ae=(x,q)=>{if(!Number.isFinite(x.start)||x.start<0)throw new l(`step ${q}: trim start must be a non-negative number.`);if(x.end===void 0==(x.duration===void 0))throw new l(`step ${q}: trim takes end OR duration.`);let H=x.end??x.start+x.duration;if(!(H>x.start))throw new l(`step ${q}: trim end must be after start.`);if(m!==null&&x.start>=m)throw new l(`step ${q}: trim starts at ${x.start}s, but the video is ${At(m)}s long at that point.`);return{start:x.start,end:m!==null?Math.min(H,m):H}};r.forEach((x,q)=>{let H=q+1,de=`p${q}`,G=`[${de}]`,Q=T=>{g.push(`${S}${T}${G}`),S=G},te=T=>j.push({step:q,kind:T,seek:[...h],audio:[...y],ops:[...P]});switch(x.op){case"trim":{let{start:T,end:_}=ae(x,H);q===0?(h.push("-ss",String(T),"-t",String(At(_-T))),R.push(`trim ${T}-${At(_)}s: input seek`)):(Q(`trim=start=${T}:end=${At(_)},setpts=PTS-STARTPTS`),y.push(`atrim=start=${T}:end=${At(_)},asetpts=PTS-STARTPTS`),R.push(`trim ${T}-${At(_)}s: trim filter`)),$=!0,m=_-T,P.push({op:"trim",start:T,end:_});break}case"crop":Q(Ec(x,{width:d,height:p})),D&&(D={...D,ox:D.ox-x.x,oy:D.oy-x.y}),d=x.width,p=x.height,R.push(`crop to ${d}x${p}`);break;case"scale":{let T=_c(x),[_,A]=[d,p];({width:d,height:p}=Cp(d,p,x)),D&&(D={sx:D.sx*d/_,sy:D.sy*p/A,ox:D.ox*d/_,oy:D.oy*p/A}),Q(T),R.push(`scale to ${d}x${p}`);break}case"speed":{if(x.factor===void 0==(x.segments===void 0))throw new l(`step ${H}: speed takes factor or segments.`);if(x.segments){let _=$a(x.segments,m),A=ka(_,f);Q(A.video),y.push(A.audio),$=!0;let z=Kr(_);m!==null&&(m-=z),P.push({op:"cut",spans:_}),R.push(`speed up ${_.length} range(s), ${At(z)}s saved`);break}let T=x.factor;if(!Number.isFinite(T)||T<=0)throw new l(`step ${H}: speed factor must be positive.`);Q(`setpts=PTS/${T}`),y.push(Tc(T)),$=!0,m!==null&&(m/=T),P.push({op:"speed",factor:T}),R.push(`speed x${T}`);break}case"redact":{let{steps:T,out:_}=Ac(x.regions,x,{width:d,height:p},S,de);g.push(...T),S=_,R.push(`redact ${x.regions.length} region(s), ${x.style??"box"}`);break}case"callout":{let T=o[q];if(!T)throw new l(`Internal: missing callout assets for step ${H}.`);let{steps:_,out:A,extraInputs:z}=ol(x.items,T,S,w,de);g.push(..._),b.push(...z),w+=z.length/4,S=A,R.push(`callout ${x.items.length} item(s)`);break}case"reframe":{let T=jn[x.aspect];if(!T)throw new l(`step ${H}: unknown aspect "${x.aspect}".`);Q(`${pa(T.w,T.h,x.fit??"pad")},format=yuv420p`),D=null,d=T.w,p=T.h,R.push(`reframe to ${x.aspect} (${x.fit??"pad"})`);break}case"zoom":{let T=x.transitionSec??Jt,_=x.keyframes,A="";if(x.follow==="clicks"){if(_)throw new l(`step ${H}: zoom takes keyframes or follow, not both.`);if(!D)throw new l(`step ${H}: zoom follow "clicks" must come before reframe, backdrop or another zoom; the logged click positions no longer match the frame.`);let z=D,K=s.clicks?.[q];if(!K)throw new l(`Internal: missing clicks for step ${H}.`);let ue=K.flatMap(me=>{let Ne=ss(me.t,P),Rt=me.x*z.sx+z.ox,uo=me.y*z.sy+z.oy;return Ne!==null&&Rt>=0&&Rt<d&&uo>=0&&uo<p?[{t:Ne,x:Rt,y:uo}]:[]});_=ec(ue,d,p,{holdSec:x.holdSec,maxZoom:x.maxZoom,transition:T}),A=` from ${ue.length} click(s)`}else if(!_||_.length===0)throw new l(`step ${H}: zoom needs keyframes, or follow: "clicks".`);if(_.length===0){R.push("zoom: no clicks in this part of the video; skipped");break}Q(El(Za(_,d,p),{width:d,height:p,fps:f},T)),D=null,R.push(`zoom ${_.length} keyframe(s)${A}`);break}case"cut_idle":{if(!s.idle)throw new l(`Internal: missing idle scan for step ${H}.`);let T=Sa(km(s.idle,P),x.minIdleSec??Yr,x.keepSec??Ko);if(T.length===0){R.push("cut_idle: no idle stretches here; nothing cut");break}if(x.action==="speed"){let z=x.factor??Vo,K=T.map(Ne=>({...Ne,factor:z})),ue=ka(K,f);Q(ue.video),y.push(ue.audio),$=!0;let me=Kr(K);m!==null&&(m-=me),P.push({op:"cut",spans:K}),R.push(`cut_idle ${T.length} stretch(es) sped up x${z}, ${At(me)}s saved`);break}let _=Qu(T);Q(_.video),y.push(_.audio),$=!0;let A=T.reduce((z,K)=>z+(K.end-K.start),0);m!==null&&(m-=A),P.push({op:"cut",spans:T}),R.push(`cut_idle ${T.length} stretch(es), ${At(A)}s removed`);break}case"audio":{if(x.normalize===void 0&&x.denoise===void 0)throw new l(`step ${H}: audio needs normalize and/or denoise.`);if(!n.hasAudio){R.push("audio: the input has no audio; skipped");break}let T=s.audio?.[q],_=[];if(x.denoise!==void 0&&(T?.floorDb===void 0&&te("noisefloor"),y.push(bl(x.denoise,T?.floorDb??null)),_.push(`denoise ${x.denoise}`)),x.normalize!==void 0&&T?.silent)_.push("silent, not normalized");else if(x.normalize!==void 0){let A=Vn(x.normalize);T?.loudness||te("loudness"),y.push(gl(A,T?.loudness),"aresample=48000"),_.push(`normalize to ${A.i} LUFS${T?.loudness?` (measured ${T.loudness.input_i})`:""}`)}$=!0,R.push(`audio: ${_.join(", ")}`);break}case"burn_subtitles":{if(!x.subtitles==!x.transcribe)throw new l(`step ${H}: burn_subtitles takes subtitles (a path) or transcribe: true.`);if(x.transcribe&&!n.hasAudio)throw new l(`step ${H}: transcribe needs audio, and the input has none.`);let T=s.subtitles?.[q];if(T===""){R.push("burn_subtitles: no cues in this part of the video; skipped");break}T===void 0&&te(x.transcribe?"transcribe":"subtitles");let _=!!x.subtitles&&/\.(ass|ssa)$/i.test(x.subtitles),A=x.style??(_?null:"clean");Q(Wu(T??"<subtitles.srt>",s.fontsDir??"<fonts>",A)),R.push(`burn_subtitles ${x.transcribe?"from a transcript":"from a file"}, ${A??"file"} style`);break}case"backdrop":{let{op:T,..._}=x,{steps:A,out:z,extraInputs:K,layout:ue}=ml(_,{width:d,height:p},S,w,de);D=null,g.push(...A),b.push(...K),w+=K.length/2,S=z,d=ue.canvasW,p=ue.canvasH,R.push(`backdrop to ${d}x${p}`);break}case"keystroke_overlay":{let T=s.keystrokes?.[q];if(!T)throw new l(`Internal: missing keystroke badges for step ${H}.`);let _=db(T.badges,P);if(_.length===0){R.push("keystroke_overlay: no badges in this part of the video");break}let{steps:A,out:z}=al(Ia(_),T,x,{height:p},S,de);g.push(...A),S=z,R.push(`keystroke_overlay ${_.length} badge(s)`);break}case"cursor":{if(!D)throw new l(`step ${H}: cursor must come before zoom, reframe or backdrop; the logged positions no longer match the frame after them.`);let T=s.cursor?.[q];if(!T)throw new l(`Internal: missing cursor plan for step ${H}.`);let _=Da(T.plan,P,D);if(_.path.length===0||_.visible.length===0){R.push("cursor: no cursor movement in this part of the video");break}let{steps:A,out:z,extraInputs:K,commands:ue}=ll(_,x,{width:d,height:p},S,w,de,T.sprite,T.commandsFile);g.push(...A),b.push(...K),w+=K.length/2,S=z,X.push({path:T.commandsFile,content:ue}),R.push(`cursor ${_.path.length} segment(s), ${_.clicks.length} click(s)${x.spotlight?", spotlight":""}`);break}case"export_preset":{let T=Vu(x.platform,x.fit??"pad",de);D=null,Q(T.vf),T.af&&y.push(T.af),C=T.encode,d=T.width,p=T.height,f=30,$=!0,R.push(`export_preset ${x.platform}`);break}case"export_gif":{let{op:T,..._}=x;M=_,R.push(`export_gif (${_.format??"gif"}): second stage, size-budget ladder`);break}}});let ee=["-y",...h,"-i",t,...b],J=s.chaptersFile?ee.filter(x=>x==="-i").length:-1;s.chaptersFile&&ee.push("-f","ffmetadata","-i",s.chaptersFile);let ie=n.hasAudio&&y.length>0;ie&&g.push(`[0:a]${y.join(",")}[aout]`),g.length>0&&ee.push("-filter_complex",g.join(";")),ee.push("-map",S==="[0:v]"?"0:v":S),n.hasAudio&&ee.push("-map",ie?"[aout]":"0:a");let ce=C;return ce?ee.push(...ce):(ee.push(..._e(M||u?"high":i)),n.hasAudio&&ee.push(...$?["-c:a","aac","-b:a","160k"]:["-c:a","copy"]),ee.push("-movflags","+faststart")),J!==-1&&ee.push("-map_chapters",String(J)),ee.push(e),{args:ee,width:d,height:p,fps:f,durationSec:m===null?null:At(m),gif:M,summary:R,timeOps:P,pending:j,files:X}}var Mw=["pr_demo","tutorial","social_reel"],nA=1e7,Rw=new Set(["export_preset","export_gif"]);function Cw(t,e){let r=[],n=[{op:"cut_idle"}];e.hasClicks?n.push({op:"zoom",follow:"clicks"}):r.push("zoom left out: no event log with clicks (record with start_recording events: true).");let o=i=>{e.hasAudio&&(e.transcribeBlocker?r.push(`captions left out: ${e.transcribeBlocker}`):n.push({op:"burn_subtitles",transcribe:!0,style:i}))};switch(!e.hasAudio&&t!=="pr_demo"&&r.push("audio and captions left out: the input has no audio."),t){case"pr_demo":n.push({op:"export_gif",maxBytes:nA});break;case"tutorial":e.hasAudio&&n.push({op:"audio",denoise:"light",normalize:"youtube"}),o("clean"),n.push({op:"export_preset",platform:"youtube"});break;case"social_reel":e.hasAudio&&n.push({op:"audio",normalize:"youtube"}),n.push({op:"reframe",aspect:"9:16"}),o("social"),n.push({op:"export_preset",platform:"instagram_reel"});break;default:throw new l(`Unknown recipe "${String(t)}".`)}return{steps:n,notes:r}}var oA=new Set(["redact","crop","cursor"]);function Al(t,e){let r=[...t],o=r.at(-1)&&Rw.has(r.at(-1).op)?r.pop():null,i=r.length,s=new Set,a=[],c=[];for(let u of e){if(Rw.has(u.op)){o=u;continue}let d=r.findIndex((p,f)=>f<i&&!s.has(f)&&p.op===u.op);d===-1&&u.op==="trim"?a.push(u):d===-1&&oA.has(u.op)?c.push(u):d===-1?r.push(u):(r[d]=u,s.add(d))}return[...a,...c,...r,...o?[o]:[]]}import{readFileSync as iA,statSync as sA,writeFileSync as aA}from"node:fs";var Pw=1;function cA(t){return`${t}.edit.json`}function uA(t,e="the edit spec"){let r;try{r=JSON.parse(t)}catch{throw new l(`${e} is not valid JSON.`)}let n=r;if(n?.tool!=="pipeline"||typeof n.version!="number"||!Array.isArray(n.steps)||typeof n.source?.path!="string")throw new l(`${e} is not a pipeline edit spec.`);if(n.version>Pw)throw new l(`${e} was written by a newer version (spec ${n.version}).`,"Update screencast-mcp to re-render it.");return n}function Iw(t){let e;try{e=iA(t,"utf8")}catch{throw new l(`Edit spec not found: ${t}`)}return uA(e,t)}function Rl(t){let e=sA(t);return{path:t,size:e.size,mtimeMs:Math.round(e.mtimeMs)}}function Fw(t){let e;try{e=Rl(t.source.path)}catch{return`its source ${t.source.path} is gone`}return e.size!==t.source.size||e.mtimeMs!==t.source.mtimeMs?`its source ${t.source.path} changed since`:null}function Ow(t,e){let r=cA(t),n={version:Pw,tool:"pipeline",createdAt:new Date().toISOString(),output:t,...e};return aA(r,JSON.stringify(n,null,2)+`
375
- `),r}var lA=new Set(["input","inputs","inputA","inputB","clips","a","b","image","overlay","music","video","subtitles","srt","transcript","events","path","file","perf","fromEdit"]),pA=new Set(["output","outputDir","model","fontFile"]),dA=new Set(["whisper"]);function Nw(t){return typeof t=="string"?[t]:Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function oc(t){let e=r=>{if(Array.isArray(r)){r.forEach(e);return}if(!(!r||typeof r!="object"))for(let[n,o]of Object.entries(r)){if(lA.has(n))for(let i of Nw(o))i.trim().length>0&&!dA.has(i)&&mp(i,`Input "${n}"`);else if(pA.has(n))for(let i of Nw(o))Qt(i,`"${n}"`);o&&typeof o=="object"&&e(o)}};e(t)}function bA(){if(!Ye("whisper"))return"this ffmpeg has no whisper filter (FFmpeg 8 with whisper.cpp).";try{return br(void 0),null}catch{return"no whisper model (set SCREENCAST_WHISPER_MODEL)."}}var wA=O.enum(Wn),Lw=O.enum(la).optional(),yA=O.discriminatedUnion("op",[O.object({op:O.literal("trim"),start:O.number().nonnegative(),end:O.number().positive().optional(),duration:O.number().positive().optional()}),O.object({op:O.literal("crop"),x:O.number().int().nonnegative(),y:O.number().int().nonnegative(),width:O.number().int().positive(),height:O.number().int().positive()}),O.object({op:O.literal("scale"),width:O.number().int().positive().optional(),height:O.number().int().positive().optional()}),O.object({op:O.literal("speed"),factor:O.number().positive().optional(),segments:O.array(va).min(1).optional()}),O.object({op:O.literal("redact"),regions:O.array(gn).min(1),style:O.enum(Fi).optional(),pad:O.number().int().nonnegative().optional(),color:O.string().optional()}),O.object({op:O.literal("callout"),items:O.array(Ra).min(1).max(50),fontFile:vr}),O.object({op:O.literal("reframe"),aspect:wA,fit:Lw}),O.object({op:O.literal("zoom"),keyframes:O.array(rc).min(1).max(100).optional(),follow:O.literal("clicks").optional(),maxZoom:O.number().min(1).max(ui).optional(),holdSec:O.number().positive().max(30).optional(),transitionSec:O.number().positive().max(5).optional()}),O.object({op:O.literal("cut_idle"),minIdleSec:O.number().positive().optional(),keepSec:O.number().min(0).optional(),action:O.enum(["cut","speed"]).optional(),factor:O.number().gt(1).max(Jr).optional()}),O.object({op:O.literal("audio"),normalize:za.optional(),denoise:O.enum(Ga).optional()}),O.object({op:O.literal("burn_subtitles"),subtitles:O.string().min(1).optional(),transcribe:O.boolean().optional(),style:O.enum(Vs).optional()}),O.object({op:O.literal("backdrop"),...ja}),O.object({op:O.literal("keystroke_overlay"),...Fa}),O.object({op:O.literal("cursor"),...La}),O.object({op:O.literal("export_preset"),platform:O.enum(da),fit:Lw}),O.object({op:O.literal("export_gif"),format:O.enum(["gif","webp"]).optional(),maxBytes:O.number().int().min(1e4).optional(),fps:O.number().positive().max(30).optional(),width:O.number().int().min(64).max(1920).optional()})]),xA={input:O.string().min(1).optional().describe("Path to the source video."),fromEdit:O.string().min(1).optional().describe("Re-render an .edit.json; steps replace same-op steps."),steps:O.array(yA).max(Zn).optional().describe(`Edits in order, each { op, ...its tool's options }; export_preset/export_gif only last. Times and pixels are relative to the video as it is at that step (after earlier trims, speed, crops). zoom follow:"clicks" plans from the event log; burn_subtitles takes subtitles or transcribe:true.`),recipe:O.enum(Mw).optional().describe("Polish preset expanded to steps (see dryRun): pr_demo = cut_idle, click zoom, GIF <=10 MB; tutorial = + audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step; trim, redact, crop and cursor go first (source pixels and time)."),quality:O.enum(["draft","standard","high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),dryRun:O.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),output:O.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:O.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),chapters:O.boolean().optional().describe("Keep the input's markers as chapters, re-timed through trims and speed.")};function Bw(t){t.registerTool("pipeline",{title:"Edit Pipeline",description:"Run several edits (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, cursor, reframe, zoom, backdrop, audio, burn_subtitles, then optionally export_preset or export_gif) in one ffmpeg pass: one re-encode, no intermediate files. Prefer it over chaining edit tools; a recipe does the usual polish in one call.",inputSchema:xA,outputSchema:N({processes:O.number().int(),steps:O.array(O.string())}),annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k(),o=e.fromEdit?Iw(e.fromEdit):null;if(o){if(oc({input:o.source.path,steps:o.steps}),e.recipe)throw new l("fromEdit already has its steps; leave recipe out.");if(e.input&&!Bo(e.input,o.source.path))throw new l(`The spec is for ${o.source.path}, not ${e.input}.`);let P=Fw(o);if(P)throw new l(`Cannot re-render ${e.fromEdit}: ${P}.`,"Run pipeline on the source again with steps instead.")}let i=e.input??o?.source.path;if(!i)throw new l("Pass input (or fromEdit).");let s=e.quality??o?.quality??"standard",a=e.chapters??o?.chapters??!1;F(i);let c=await L(i),u=c.audioCodec!==null,d=[],p=e.steps??[];if(o&&(p=Al(o.steps,p)),e.recipe){let P=li($e(i).jsonl),j=Cw(e.recipe,{hasAudio:u,hasClicks:!!P&&P.length>0,transcribeBlocker:u?bA():null});p=Al(j.steps,p),d.push(...j.notes)}if(p.length===0)throw new l("Give steps, a recipe, or both.");if(p.length>Zn)throw new l(`At most ${Zn} steps.`);if(!c.width||!c.height)throw new l(`Could not read the size of ${i}.`);let f={width:c.width,height:c.height,fps:c.fps??30,durationSec:c.durationSec,hasAudio:u},m=le(c.durationSec),h=p.at(-1);if(!h)throw new l("Provide at least one step.");let b=h.op==="export_gif"?`.${h.format??"gif"}`:".mp4",w=B(e.output,"pipeline",b,{overwrite:e.overwrite,anyContainer:h.op==="export_gif"}),g=h.op!=="export_gif"&&p.some(P=>P.op==="burn_subtitles"&&P.transcribe),y=w.replace(/\.[^./\\]+$/,"")+".srt";if(g&&!e.overwrite&&ic(y))throw new l(`Output already exists: ${y}. Pass overwrite: true to replace it.`);for(let[P,j]of p.entries())if(j.op==="burn_subtitles"){if(!Ye("subtitles"))throw new l("This ffmpeg has no subtitles filter (it needs libass).","Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");if(j.subtitles&&!ic(j.subtitles))throw new l(`step ${P+1}: subtitles file not found: ${j.subtitles}`);if(j.transcribe){if(!Ye("whisper"))throw new l(`step ${P+1}: transcribe needs FFmpeg 8 built with whisper.cpp (no whisper filter here).`);br(void 0)}}let $={};for(let[P,j]of p.entries()){if(j.op!=="zoom"||j.follow!=="clicks")continue;let X=$e(i).jsonl,D=li(X);if(!D)throw new l(`step ${P+1}: no event log at ${X}; record with start_recording events: true.`);$[P]=D}let S,C=p.findIndex(P=>P.op==="cut_idle"),M=p[C];if(M?.op==="cut_idle"){let P=c.durationSec;if(P===null)throw new l(`Could not read the duration of ${i}.`);let j=p.slice(0,C).reduce((ee,J)=>J.op==="speed"&&J.factor?ee*J.factor:ee,1),X=u,D=await ne(n,ba(i,(M.minIdleSec??Yr)*j,X),m,{signal:r.signal});if(D.code!==0)throw new l(`Idle scan failed (exit ${D.code}): ${D.stderr.trim().slice(-400)}`);let ae=wa(D.stderr,P);S=X?xa(ae,ya(D.stderr,P)):ae}let R=fA(tn(gA(),"screencast-pipeline-"));try{let P={},j=[];for(let[_,A]of p.entries()){if(A.op!=="callout")continue;let z=e.dryRun?{fontFile:"<font>",textFiles:A.items.map(K=>K.type==="text"?"<text>":null),arrowFiles:A.items.map(K=>K.type==="arrow"?"<arrow.png>":null),...il(A.items,A.fontFile)}:await Ma(A.items,R,`s${_}_`,A.fontFile);P[_]=z,j.push(...z.fallbackFonts.map(K=>({step:_,...K}))),d.push(...z.warnings.map(K=>`Step ${_}, ${K.charAt(0).toLowerCase()}${K.slice(1)}`))}let X={};for(let[_,A]of p.entries()){if(A.op==="backdrop"&&A.image&&!ic(A.image))throw new l(`step ${_+1}: background image not found: ${A.image}`);if(A.op!=="keystroke_overlay")continue;let{badges:z}=Oa(i,A.events,A),K=[...new Set(z.map(me=>me.label))],ue=Zo(K,e.dryRun?null:R,`s${_}_`,A.fontFile);X[_]={badges:z,fontFile:ue.fontFile,textFiles:ue.textFiles},d.push(...ue.warnings.map(me=>`Step ${_}, ${me.charAt(0).toLowerCase()}${me.slice(1)}`))}let D={};for(let[_,A]of p.entries())A.op==="cursor"&&(D[_]={plan:Ba(i,A.events,A,c.durationSec),sprite:Na(),commandsFile:e.dryRun?`<cursor ${_}.cmd>`:tn(R,`s${_}_cursor.cmd`)});let ae=h.op==="export_gif"?e.dryRun?"<temporary stage1.mp4>":tn(R,"stage1.mp4"):w,ee={},J={},ie=mA(Bt("regular")),ce=_=>nc(i,ae,p,f,P,s,{keystrokes:X,cursor:D,idle:S,clicks:$,audio:ee,subtitles:J,fontsDir:ie,chaptersFile:_}),x=ce(),q;for(let _=0;!e.dryRun&&x.pending.length>0;_++){let A=x.pending[0];if(_>p.length*3)throw new l(`Internal: step ${A.step+1} ${A.kind} did not resolve.`);let z=p[A.step],K=async ue=>{let me=Bi(Tl(ue,A));try{let Ne=await ne(n,me.args,m,{signal:r.signal});if(Ne.code!==0)throw new l(`step ${A.step+1} ${A.kind} scan failed (exit ${Ne.code}): ${Ne.stderr.trim().slice(-400)}`);return Ne}finally{me.cleanup()}};if(A.kind==="noisefloor")ee[A.step]={...ee[A.step],floorDb:Xa((await K(qa(i))).stdout)};else if(A.kind==="loudness"&&z.op==="audio"){let ue=await K(oi(i,Vn(z.normalize)));try{ee[A.step]={...ee[A.step],loudness:ii(ue.stderr)}}catch{d.push(`Step ${A.step+1}: the audio is silent; not normalized.`),ee[A.step]={...ee[A.step],silent:!0}}}else if(A.kind==="transcribe"&&z.op==="burn_subtitles"){let ue=tn(R,`s${A.step}_raw.srt`);await Z(Tl(On(i,br(void 0),ue),A),m,{signal:r.signal});let me=ic(ue)?ut(We(Dw(ue,"utf8"))):[];J[A.step]=me.length>0?tn(R,`s${A.step}.srt`):"",me.length>0?(q={cues:me,opsBefore:A.ops.length},pi(J[A.step],nt(me))):d.push(`Step ${A.step+1}: no speech was recognised; no captions.`)}else if(A.kind==="subtitles"&&z.op==="burn_subtitles"&&z.subtitles)if(A.ops.length===0)J[A.step]=z.subtitles;else{let ue=Dw(z.subtitles,"utf8"),me=/\.(ass|ssa)$/i.test(z.subtitles),Ne=me?Em(ue,A.ops):nt(as(ut(We(ue)),A.ops)),Rt=tn(R,`s${A.step}${me?".ass":".srt"}`);pi(Rt,Ne),J[A.step]=me||Ne.trim()?Rt:""}else throw new l(`Internal: step ${A.step+1} cannot resolve ${A.kind}.`);x=ce()}let H=[],de=[];if(a){let _=x.gif?null:await mr(i,r.signal);if(!_)d.push("chapters: a GIF/WebP cannot hold chapters; none written.");else if(_.markers.length===0)d.push("chapters: the input has no markers (add_marker) or chapters; none written.");else if(de=Rm(_.markers,x.timeOps),H=x.durationSec?ls(ds(de),x.durationSec):[],H.length===0)d.push("chapters: no marker falls inside the result; none written.");else{let A=e.dryRun?"<chapters.txt>":tn(R,"chapters.txt");e.dryRun||pi(A,ps(H)),x=ce(A)}}let G={...e.recipe&&{recipe:e.recipe,expandedSteps:p},steps:x.summary,...e.dryRun&&x.pending.length>0&&{measuredOnRun:x.pending.map(_=>`step ${_.step+1}: ${_.kind}`)},processes:x.gif?2:1,width:x.width,height:x.height,durationSec:x.durationSec,...j.length>0&&{fallbackFonts:j},...d.length>0&&{warnings:d},...H.length>0&&{chapters:H}};if(e.dryRun)return v({dryRun:!0,...G,ffmpegArgs:x.args});let Q=()=>{try{let _=e.recipe??o?.recipe;return{editSpecPath:Ow(w,{serverVersion:wt(),source:Rl(i),steps:p,..._?{recipe:_}:{},quality:s,chapters:a})}}catch{return{}}};for(let _ of x.files)pi(_.path,_.content);if(await W(x.args,{output:ae,durationSec:x.durationSec,inputDurationSec:c.durationSec,extra:r}),x.gif){let _=await zn(ae,w,x.gif,r);return v({outputPath:w,...G,animation:_,...Q()})}let te;if(q)try{let _=Aw(q.cues,x.timeOps,q.opsBefore);_.length>0&&(pi(y,nt(_)),te=y)}catch{te=void 0}let T;if(H.length>0)try{T=dr(w,de.filter(_=>_.t<(x.durationSec??1/0)))}catch{}return v({outputPath:w,...G,...T&&{markersPath:T},...te&&{subtitlesPath:te},...Q()})}finally{hA(R,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as di}from"zod";var SA={input:di.string().min(1).describe("Path to the source video."),platform:di.enum(da).describe("Sets aspect, size, fps, bitrate. steam_trailer: 1080p 5.5 Mbps CBR, -14 LUFS. vertical_reel: 1080x1920 over a blurred copy of itself, -14 LUFS (ignores fit)."),fit:di.enum(["pad","crop"]).optional().describe("Fit to the platform aspect: pad (default) or crop."),output:di.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:di.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ww(t){t.registerTool("export_preset",{title:"Export for Platform",description:"Encode a platform-ready H.264 file (aspect, fps, bitrate, faststart) for a named platform.",inputSchema:SA,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.platform,o=B(e.output,n,".mp4",{overwrite:e.overwrite}),i=Cg(e.input,o,n,e.fit??"pad");await W(i,{output:o,durationSec:await se(e.input),extra:r});let s=Ku[n];return v({outputPath:o,platform:n,aspect:s.aspect,fps:s.fps})}catch(n){return E(n)}})}import{z as ke}from"zod";import{existsSync as sc,mkdirSync as vA,mkdtempSync as $A,readFileSync as Ml,rmSync as Cl,writeFileSync as jw}from"node:fs";import{tmpdir as kA,release as EA,version as _A}from"node:os";import{join as rn}from"node:path";var TA=wt(),AA={input:ke.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),sessionId:ke.string().min(1).optional().describe("Or a stopped session's id."),title:ke.string().max(200).optional().describe("Issue title."),actual:ke.string().max(4e3).optional().describe("What happened."),expected:ke.string().max(4e3).optional().describe("What should happen."),start:ke.number().nonnegative().optional().describe("Clip start s (default: end - clipSec)."),end:ke.number().positive().optional().describe("Clip end s (default: recording end)."),clipSec:ke.number().positive().max(Is).optional().describe(`Clip length without start (default ${Cu}).`),redact:ke.boolean().optional().describe("Box out OCR-found secrets in every output (default true; needs Windows OCR)."),secretPattern:ke.string().optional().describe("Secret regex (default: API keys, tokens, password: values)."),regions:ke.array(gn).optional().describe("Extra boxes (video px; start/end on the clip clock)."),errorPattern:ke.string().optional().describe("Error-line regex."),scanEverySec:ke.number().positive().optional().describe(`OCR every N s (default ${Pu}).`),maxFrames:ke.number().int().min(1).max(vs).optional().describe(`Scan frame cap (default ${En}).`),gif:ke.boolean().optional().describe("Also export a GIF (default true)."),maxBytes:ke.number().int().min(1e4).optional().describe(`GIF size budget (default ${Sr}).`),outputDir:ke.string().optional().describe("Package folder (default: a new one in SCREENCAST_HOME/edits)."),overwrite:ke.boolean().optional().describe("Replace a report already in outputDir.")},mi=t=>Math.round(t*1e3)/1e3;async function RA(){if(process.platform!=="win32")return null;try{return(await ar()).map(e=>`${e.width}x${e.height}${e.dpi?` @${Math.round(e.dpi/96*100)}%`:""}${e.primary?" (primary)":""}`).join(", ")}catch{return null}}function Uw(t){t.registerTool("bug_report",{title:"Bug Report Package",description:"Package a recording as a paste-ready repro folder: secret-scanned, redacted clip and GIF, contact sheet, steps from the event log, OCR'd errors, environment, report.md for gh issue create --body-file.",inputSchema:AA,outputSchema:N({outputDir:ke.string(),reportPath:ke.string(),jsonPath:ke.string(),clipPath:ke.string()}),annotations:I},async(e,r)=>{let n=null,o=[];try{if(e.input===void 0==(e.sessionId===void 0))throw new l("Provide exactly one of: input (a recording path) or sessionId.");let{ffmpeg:i}=k(),s=await Ns(e),a=await L(s.path);if(!a.width||!a.height)throw new l(`Could not read the size of ${s.path}.`);let c=a.videoDurationSec??a.durationSec;if(c===null)throw new l(`Could not read the duration of ${s.path}.`);let u=If(c,e),d=mi(u.end-u.start),p=e.redact!==!1,f=e.secretPattern??Ge;Oe(["x"],f),e.errorPattern!==void 0&&Oe(["x"],e.errorPattern);let m="gif",h=ln(e.outputDir,we("edits"))??rn(we("edits"),`bug-report-${ge()}-${be()}`),b={markdown:rn(h,Wt.markdown),json:rn(h,Wt.json),clip:rn(h,Wt.clip),gif:rn(h,Wt.gif(m)),sheet:rn(h,Wt.contactSheet)},w=Object.values(b).filter($=>sc($));if(w.length>0&&!e.overwrite)throw new l(`The folder already holds a report: ${w.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);sc(h)||(vA(h,{recursive:!0}),n=h);let g=[],y=$A(rn(kA(),"screencast-bug-"));try{let $="unavailable",S=null,C=await wr();if(C.available)S=await Ss(s.path,{everySec:e.scanEverySec??Pu,maxFrames:e.maxFrames??En,range:{start:u.start,duration:d}},y,r.signal),$="read";else{if(p)throw new l(`The secret scan needs Windows OCR, which is unavailable here${C.error?` (${C.error})`:""}.`,"Pass redact: false to package without it (then check the clip yourself before sharing), or run doctor.");g.push("Windows OCR is unavailable, so no error text was read.")}let M=S&&p?Ff(kn(S,f,!0,"line").redactRegions):[],R=[...M,...e.regions??[]],P=S?Of(S.frames,e.errorPattern??Os,p?f:null):[];r.signal.throwIfAborted();let j=[{op:"trim",start:u.start,end:u.end},...R.length>0?[{op:"redact",regions:R,style:"box"}]:[]],X=nc(s.path,b.clip,j,{width:a.width,height:a.height,fps:a.fps??30,durationSec:a.durationSec,hasAudio:a.audioCodec!==null});await W(X.args,{output:b.clip,durationSec:X.durationSec,inputDurationSec:d,extra:r}),o.push(b.clip);let D=null;e.gif!==!1&&(D=await zn(b.clip,b.gif,{format:m,maxBytes:e.maxBytes??Sr},r),o.push(b.gif),D.note&&g.push(D.note)),await Cs(b.clip,Ms(d,Oo),b.sheet,{tileWidth:No},r.signal),o.push(b.sheet);let ae=(s.eventsPath?Mu(je(Ml(s.eventsPath,"utf8"))):[]).map(_=>p?{..._,text:Oe([_.text],f)[0]??_.text}:_),ee=s.eventsPath?ae.length===0?"The event log has no clicks, shortcuts, typing, or scrolls.":void 0:"The recording has no input event log (record with start_recording events: true).",J=Lt(s.path),ie=sc(J)?Df(Es(Ml(J,"utf8")),u,p?f:null):void 0,ce=xt(s.path),x=sc(ce)?Lf(An(Ml(ce,"utf8")),u,s.record?.perf?.summary?.process):[],q=ca(ua(i)??""),H=await RA(),de=s.record,G=_=>p?Oe([_],f)[0]??_:_,Q=[["OS",`${_A()} (${EA()}), ${process.arch}`],...H?[["Displays",H]]:[],...de?[["Recorded target",G(de.target)]]:[],...de?.matchedWindow?[["Window",G(de.matchedWindow)]]:[],...de?.backend?[["Capture backend",de.backend]]:[],["Recording",`${a.width}x${a.height}${a.fps?` @ ${Math.round(a.fps*100)/100} fps`:""}, ${mi(c)} s${a.videoCodec?`, ${a.videoCodec}`:""}`],["ffmpeg",q.version??"unknown"],["screencast-mcp",`${TA} (Node ${process.version})`]],te={title:e.title?.trim()||"Bug report",...e.expected?{expected:e.expected}:{},...e.actual?{actual:e.actual}:{},createdAt:new Date().toISOString(),clip:{start:u.start,end:u.end,recordingDurationSec:mi(c),width:a.width,height:a.height},files:{clip:Wt.clip,...D?{gif:Wt.gif(m)}:{},contactSheet:Wt.contactSheet},...D?{gif:{format:m,sizeBytes:D.sizeBytes,withinBudget:D.withinBudget}}:{},steps:ae.slice(0,Fs),...ae.length>Fs?{stepsOmitted:ae.length-Fs}:{},...ee?{stepsNote:ee}:{},errors:P,...ie?{logs:ie}:{},...x.length?{perf:x}:{},ocr:$,redaction:{scanned:S!==null&&p,...S&&p?{everySec:mi(S.step),framesScanned:S.frames.length}:{},found:M.length,manual:e.regions?.length??0},environment:Q};jw(b.markdown,Nf(te)),o.push(b.markdown),jw(b.json,JSON.stringify({...te,steps:ae,redaction:{...te.redaction,regions:R}},null,2)+`
376
- `),o.push(b.json),S?.clamped&&g.push(`The scan interval was widened to ${mi(S.step)} s to fit maxFrames.`);let{images:T}=await Re([b.sheet],Ae,1);return v({outputDir:h,reportPath:b.markdown,jsonPath:b.json,clipPath:b.clip,...D?{gifPath:b.gif,gifSizeBytes:D.sizeBytes,gifWithinBudget:D.withinBudget}:{},contactSheetPath:b.sheet,clip:{start:u.start,end:u.end},steps:ae.length,errors:P.map(_=>_.text),ocr:$,redaction:te.redaction,...g.length>0?{warnings:g}:{},next:`Review the clip and report.md, then: gh issue create --title ${JSON.stringify(te.title)} --body-file ${JSON.stringify(b.markdown)} and drag the GIF into the issue.`,note:"Redaction is OCR-based and best-effort: look at the clip before posting it anywhere public."},T)}finally{Cl(y,{recursive:!0,force:!0})}}catch(i){if(n)Cl(n,{recursive:!0,force:!0});else for(let s of o)Cl(s,{force:!0});return E(i)}})}import{z as Tr}from"zod";import{existsSync as ac,mkdirSync as Dl,mkdtempSync as DA,readFileSync as ty,readdirSync as ry,rmSync as nn,rmdirSync as LA,statSync as BA,writeFileSync as ny}from"node:fs";import{tmpdir as WA}from"node:os";import{join as Je}from"node:path";var fi=100,MA=.1,CA=1280,zw=40,PA=24,to={markdown:"guide.md",html:"guide.html",images:"images",image:t=>`step-${String(t).padStart(2,"0")}.png`};function Il(t){return t.label?`${t.text} ${t.label}`:t.text}var IA=t=>Math.round(t*1e3)/1e3;function FA(t,e,r){let n=Math.max(0,e-1/(r>0?r:30));return IA(Math.min(Math.max(0,t-MA),n))}function Pl(t,e,r){let n=Math.max(t.x-e,0,e-(t.x+t.width)),o=Math.max(t.y-r,0,r-(t.y+t.height));return Math.hypot(n,o)}function Hw(t,e,r){let o=t.map(s=>({line:s,d:Pl(s,e,r)})).filter(s=>s.d<=PA&&s.line.text.trim().length>0).sort((s,a)=>s.d-a.d||s.line.width*s.line.height-a.line.width*a.line.height)[0]?.line;if(!o)return null;let i=o.text.replace(/\s+/g," ").trim();if(i.length>zw){let s=[...o.words].sort((a,c)=>Pl(a,e,r)-Pl(c,e,r))[0];i=s?s.text.trim():`${i.slice(0,zw-1).trimEnd()}\u2026`}return i.length>0?i:null}function OA(t){let e=t.action==="double_click"?"double-click":"click",r=t.button&&t.button!=="left"?`${t.button.charAt(0).toUpperCase()}${t.button.slice(1)}-${e}`:e;return r.charAt(0).toUpperCase()+r.slice(1)}function Fl(t,e){let r=e.secretPattern??Ge,n=i=>Oe([i],r)[0]??i,o=0;return t.map((i,s)=>{if(i.action==="gap")return{n:0,t:i.t,action:i.action,text:i.text};o++;let a={n:o,t:i.t,action:i.action,text:i.text,shotT:FA(i.t,e.durationSec,e.fps)},c=i.element?.name??e.labels?.[s];if(i.action==="click"||i.action==="double_click"){let u=OA(i);return i.inFrame===!1?{...a,text:i.element?.name?n(`${u} ${Au(i.element)}`):`${u} outside the recorded area`}:{...a,x:i.x,y:i.y,...c?{text:u,label:n(c)}:{text:`${u} the marked spot`}}}return i.action==="scroll"?{...a,...i.inFrame===!1?{}:{x:i.x,y:i.y},...c?{text:`${i.text} over`,label:n(c)}:{}}:i.action==="shortcut"?i.keys?{...a,text:"Press",label:i.keys}:a:i.action==="switch"?{...a,text:n(i.text)}:{...a,text:"Type text"}})}function Gw(t,e){let r=[...e].sort((n,o)=>n.t-o.t);return t.map(n=>{let o=r.filter(i=>i.t<=n.t+1e-6).at(-1);return o?{...n,section:o.label}:n})}function qw(t,e){let r=p=>String(Math.round(p)),n=[];for(let p of e.boxes??[])n.push(`drawbox=x=${r(p.x)}:y=${r(p.y)}:w=${r(p.width)}:h=${r(p.height)}:color=black:t=fill`);let o=`scale=w='min(iw,${CA})':h=-2:flags=lanczos`,i=`[0:v]${n.length?n.join(",")+",":""}format=rgba`;if(!e.click)return`${i},${o},format=rgb24[out]`;let s=_l(t.width,t.height),a=s/2,c=Math.max(3,Math.round(s/10)),u=a-c/2-1,d=e.color??tc;return`${i}[bg];color=c=${d}:s=${s}x${s}:d=1,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='if(lt(abs(hypot(X-${a},Y-${a})-${u}),${c/2}),255,0)'[ring];[bg][ring]overlay=x=${r(e.click.x-a)}:y=${r(e.click.y-a)},${o},format=rgb24[out]`}function Xw(t,e,r){return["-y","-v","error","-ss",String(e),"-i",t,"-frames:v","1",r]}var ro=1e7,Yt=[{width:1280,q:4},{width:960,q:6},{width:800,q:8},{width:640,q:10},{width:480,q:14},{width:360,q:20}],Ol=t=>t.replace(/\.png$/i,".jpg");function Jw(t,e,r){return["-y","-v","error","-i",t,"-vf",`scale=w='min(iw,${e.width})':h=-2:flags=lanczos,format=yuvj420p`,"-frames:v","1","-q:v",String(e.q),r]}var Yw=t=>4*Math.ceil(t/3);function Kw(t,e,r=ro){let n=Yt[t].width;for(let o=t+1;o<Yt.length;o++)if(e*(Yt[o].width/n)**2<=r)return o;return t+1<Yt.length?Yt.length-1:null}function Vw(t,e,r){return["-y","-v","error","-i",t,"-filter_complex",e,"-map","[out]","-frames:v","1",r]}var eo=t=>t.replace(/\s*\n\s*/g," ").replace(/([\\`*_[\]<>#|])/g,"\\$1");function Qw(t){return`${t.ocr==="read"?`Screenshots scanned for secrets with OCR (best-effort); ${t.redactions} region${t.redactions===1?"":"s"} boxed out.`:"Screenshots were not scanned for secrets: review them before sharing."} Typed text is never logged, so it never appears here.`}function Zw(t){let e=t.steps.filter(r=>r.n>0).length;return`${e} step${e===1?"":"s"} from a ${Fe(t.recording.durationSec)} recording.`}function ey(t){let e=[`# ${eo(t.title)}`,"",Zw(t),""];t.steps.length===0&&e.push(`_${t.stepsNote??"No steps in the recording."}_`,"");let r;for(let n of t.steps){if(n.section!==void 0&&n.section!==r&&(r=n.section,e.push(`## ${eo(r)}`,"")),n.n===0){e.push(`> _${eo(n.text)}_`,"");continue}let o=n.label?`${eo(n.text)} **${eo(n.label)}**`:eo(n.text);e.push(`${n.n}. ${o} <sub>${Fe(n.t)}</sub>`,""),n.image&&e.push(` ![Step ${n.n}](${to.images}/${n.image})`,"")}return t.stepsOmitted&&e.push(`_${t.stepsOmitted} more steps not shown._`,""),e.push("<sub>",Qw(t),`Generated by screencast-mcp step_guide, ${t.createdAt}.`,"</sub>",""),e.join(`
377
- `)}var et=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),NA=`:root{--bg:#f6f5f2;--card:#fff;--ink:#16161a;--dim:#6b6b74;--line:#e2e0da;--rec:#e5383b}
375
+ `;var YT=xt(),xw=de.looseObject({found:de.boolean(),path:de.string().nullable(),version:de.string().nullable(),major:de.number().nullable()}),KT=B({ok:de.boolean(),problems:de.array(de.string()),server:de.looseObject({version:de.string(),node:de.string(),platform:de.string(),arch:de.string()}),ffmpeg:xw.extend({meetsFfmpeg8:de.boolean().nullable()}),ffprobe:xw,filters:de.record(de.string(),de.boolean()),devices:de.looseObject({gdigrab:de.boolean(),dshow:de.boolean()}),wgc:de.looseObject({available:de.boolean()}),ocr:de.looseObject({available:de.boolean(),language:de.string().nullable(),languages:de.array(de.string())}),storage:de.looseObject({home:de.string(),homeExists:de.boolean()}),env:de.record(de.string(),de.string().nullable())});function VT(t){let e=E(t).content[0];return e?.type==="text"?e.text.replace(/\s*\n+\s*/g," "):String(t)}function Sw(t){let e=ua(t),r=ca(e??"");return{found:e!==null,path:e!==null?gg(t):null,version:r.version,major:r.major,...r.inferred?{majorInferred:!0}:{}}}function vw(t){t.registerTool("doctor",{title:"Check Setup",description:`Check the setup: ffmpeg/ffprobe (FFmpeg ${Yr}+?), optional filters, capture devices, Windows OCR, settings, and enabled toolsets; \`problems\` says what is missing and how to fix it. Call on first use or when a tool reports a missing feature.`,inputSchema:{},outputSchema:KT,annotations:fe},async()=>{try{let e=[],r=null;try{r=Mc()}catch(w){e.push(VT(w))}let n=Sw(r?.ffmpeg??(process.env.FFMPEG_PATH?.trim()||"ffmpeg")),o=Sw(r?.ffprobe??(process.env.FFPROBE_PATH?.trim()||"ffprobe")),i=n.major===null?null:n.major>=Yr;r&&i===!1&&e.push(`FFmpeg ${n.version} is older than ${Yr}: transcribe and backend "wgc" need FFmpeg ${Yr}+. Windows: \`winget install Gyan.FFmpeg\`.`);let s={},a={gdigrab:!1,dshow:!1};if(r){for(let g of yg)s[g.filter]=g.filter==="gfxcapture"?cr():Ve(g.filter),!s[g.filter]&&!(g.filter==="gfxcapture"&&process.platform!=="win32")&&e.push(`No ${g.filter} filter: ${g.tools} unavailable (needs ${g.why}).`);let w=fg(hg(r.ffmpeg)??"");a={gdigrab:w.includes("gdigrab"),dshow:w.includes("dshow")},process.platform==="win32"&&!a.gdigrab&&e.push("This ffmpeg has no gdigrab device: screenshot and start_recording cannot capture the screen.")}process.platform!=="win32"&&e.push("Not Windows: capture (screenshot, start_recording, list_targets) and OCR are unavailable; the watch and edit tools work.");let c=r?{ddagrab:process.platform==="win32"&&Ve("ddagrab"),encoders:await zc(r.ffmpeg)}:null,[u,d]=await Promise.all([vr(),ww()]);process.platform==="win32"&&!u.available&&e.push(`Windows OCR unavailable: find_text cannot read the screen. ${u.error??"Install an OCR language (Settings > Time & language > Language)."}`),process.platform==="win32"&&!d.available&&e.push(`Windows speech unavailable: narrate cannot speak. ${d.error??""} Install a voice (Settings > Time & language > Speech).`.replace(/\s+/g," "));let p=wg(),f=p.SCREENCAST_WHISPER_MODEL;f&&!Qa(f)&&e.push(`SCREENCAST_WHISPER_MODEL points at a missing file: ${f}`);let m=Pe();for(let w of go())Qa(w)||e.push(`SCREENCAST_ALLOWED_DIRS names a missing folder: ${w}`);let h=bi(p.SCREENCAST_TOOLSETS??void 0);h.unknown.length>0&&e.push(`SCREENCAST_TOOLSETS names unknown toolsets (ignored): ${h.unknown.join(", ")}.`),e.push(...bg());let b=Qa(m)?await iw(m):{freeBytes:await Sl(JT(m)),bytes:null};return b.freeBytes!==null&&b.freeBytes<nw&&e.push(`Only ${sw(b.freeBytes)} free on the drive holding SCREENCAST_HOME: a long recording can fail partway. Delete old recordings (delete_recording) or set SCREENCAST_HOME on a bigger drive.`),S({ok:e.length===0,problems:e,server:{version:YT,node:process.version,platform:process.platform,arch:process.arch},ffmpeg:{...n,meetsFfmpeg8:i},ffprobe:o,filters:s,devices:a,wgc:{available:s.gfxcapture===!0},...c?{gpu:c}:{},ocr:u,tts:d,storage:{home:m,homeExists:Qa(m),freeBytes:b.freeBytes,...b.bytes?{bytes:b.bytes}:{},recordings:vl(m,"recordings"),screenshots:vl(m,"screenshots"),edits:vl(m,"edits"),allowedOutputDirs:Or()},env:p,toolsets:{enabled:h.enabled,available:["all",...gi]}})}catch(e){return E(e)}})}import{z as eo}from"zod";var QT={inputA:eo.string().min(1).describe("Outgoing video."),inputB:eo.string().min(1).describe("Incoming video."),transition:eo.string().optional().describe("xfade name (default fade): fade, wipeleft, slideup, circleopen, dissolve, ..."),duration:eo.number().positive().optional().describe(`Transition length in seconds (default ${jn}).`),output:eo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:eo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function $w(t){t.registerTool("xfade_transition",{title:"Crossfade Transition",description:"Join two videos with an xfade transition (audio crossfaded); they need not match in size, fps, or audio. For more clips use assemble_highlights.",inputSchema:QT,outputSchema:K,annotations:I},async(e,r)=>{try{k();for(let p of[e.inputA,e.inputB])O(p);let[n,o]=await Promise.all([W(e.inputA),W(e.inputB)]),i=Vr(n),s=Vr(o);if(i===null||s===null)throw new l(`Could not read duration of ${i===null?e.inputA:e.inputB}.`);let a=[n.audioCodec!==null,o.audioCodec!==null],c=a[0]||a[1],u=j(e.output,"xfade",".mp4",{overwrite:e.overwrite}),d=Ag(e.inputA,e.inputB,[i,s],u,{transition:e.transition,duration:e.duration},a);return await U(d,{output:u,durationSec:i+s,extra:r}),S({outputPath:u,audio:c})}catch(n){return E(n)}})}import{z as Kt}from"zod";var ZT={clips:Kt.array(Kt.string().min(1)).min(2).describe("Clip paths, in order."),transition:Kt.string().optional().describe("cut (default) or an xfade name (fade, wipeleft, slideup, ...)."),duration:Kt.number().positive().optional().describe(`Transition seconds (default ${jn}).`),width:Kt.number().int().positive().optional().describe("Common output width (default 1920)."),height:Kt.number().int().positive().optional().describe("Common output height (default 1080)."),fps:Kt.number().int().positive().optional().describe("Common output fps (default 30)."),output:Kt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Kt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function kw(t){t.registerTool("assemble_highlights",{title:"Assemble Highlights",description:"Stitch clips (including title cards) into one video with cuts or xfade transitions; they need not match in size, fps, or audio.",inputSchema:ZT,outputSchema:K,annotations:I},async(e,r)=>{try{k();for(let c of e.clips)O(c);let n=await Promise.all(e.clips.map(c=>W(c))),o=n.map(c=>Vr(c)??0),i=n.map(c=>c.audioCodec!==null),s=j(e.output,"highlights",".mp4",{overwrite:e.overwrite}),a=Yo(e.clips,o,s,{transition:e.transition,duration:e.duration,width:e.width,height:e.height,fps:e.fps},i);return await U(a,{output:s,durationSec:o.reduce((c,u)=>c+u,0)||null,extra:r}),S({outputPath:s,clips:e.clips.length,transition:e.transition??"cut",audio:i.some(Boolean)})}catch(n){return E(n)}})}import{z as ht}from"zod";import{writeFileSync as eR,rmSync as tR}from"node:fs";var rR={text:ht.string().min(1).describe("Title text. Multiple lines are allowed (use \\n)."),duration:ht.number().positive().optional().describe("Card length in seconds (default 3)."),width:ht.number().int().positive().optional().describe("Card width (default 1920)."),height:ht.number().int().positive().optional().describe("Card height (default 1080)."),fps:ht.number().int().positive().optional().describe("Card fps (default 30)."),bg:ht.string().optional().describe("Background color (default black)."),fontColor:ht.string().optional().describe("Text color (default white)."),fontSize:ht.number().int().positive().optional().describe("Text size in px (default 96)."),bold:ht.boolean().optional().describe("Use the bold weight (default true)."),fontFile:_r,output:ht.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ht.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ew(t){t.registerTool("title_card",{title:"Title Card",description:"Generate a title card clip (centered text on a solid background, silent audio track) to stitch in with assemble_highlights. Uncoverable characters are reported in warnings.",inputSchema:rR,outputSchema:K,annotations:I},async(e,r)=>{try{k();let n=j(e.output,"title",".mp4",{overwrite:e.overwrite}),o=kt(e.text,{weight:e.bold===!1?"regular":"bold",fontFile:e.fontFile}),i=He(".txt");eR(i,e.text);try{let s=Mg(i,o.fontFile,n,{duration:e.duration,width:e.width,height:e.height,fps:e.fps,bg:e.bg,fontColor:e.fontColor,fontSize:e.fontSize});await U(s,{output:n,durationSec:e.duration??Ku,extra:r})}finally{tR(i,{force:!0})}return S({outputPath:n,...(o.fallback||e.fontFile)&&{fontFile:o.fontFile},...o.warning&&{warnings:[o.warning]}})}catch(n){return E(n)}})}import{z as Mr}from"zod";var nR={video:Mr.string().min(1).describe("Path to the video."),music:Mr.string().min(1).describe("Music audio file."),musicVolume:Mr.number().nonnegative().optional().describe("0..1 (default 0.25 over existing audio, 0.8 alone)."),fadeIn:Mr.number().nonnegative().optional().describe("Fade-in seconds (default 1)."),fadeOut:Mr.number().nonnegative().optional().describe("Fade-out seconds (default 2)."),duck:Mr.boolean().optional().describe("Duck the music under the original audio (default false)."),output:Mr.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Mr.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function _w(t){t.registerTool("music_bed",{title:"Add Music Bed",description:"Lay music under a video: looped or trimmed to length, faded, leveled, and mixed with any existing audio. Video is stream-copied.",inputSchema:nR,outputSchema:K,annotations:I},async(e,r)=>{try{k();for(let a of[e.video,e.music])O(a);let n=await W(e.video);if(n.durationSec===null)throw new l(`Could not read duration of ${e.video}.`);let o=Z(e.video),i=j(e.output,"music",o,{overwrite:e.overwrite}),s=Cg(e.video,e.music,i,n.durationSec,n.audioCodec!==null,{musicVolume:e.musicVolume,fadeIn:e.fadeIn,fadeOut:e.fadeOut,duck:e.duck});return await U(s,{output:i,durationSec:n.durationSec,extra:r}),S({outputPath:i,mixedWithOriginal:n.audioCodec!==null})}catch(n){return E(n)}})}import{z as gt}from"zod";import{existsSync as oR,mkdtempSync as iR,readFileSync as sR,rmSync as aR,writeFileSync as cR}from"node:fs";import{tmpdir as uR}from"node:os";import{join as Tw}from"node:path";var lR={video:gt.string().min(1).describe("Path to the video."),lines:gt.array(gt.object({t:gt.number().nonnegative().optional().describe("Seconds."),marker:gt.string().optional().describe("Or a marker label."),text:gt.string().min(1)})).min(1),voice:gt.string().optional().describe("Voice name or part (doctor lists them)."),rate:gt.number().min(Ka).max(Va).optional().describe("Default 1."),duck:gt.boolean().optional().describe("Duck the original audio (default true)."),output:gt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:gt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Rw(t){t.registerTool("narrate",{title:"Narrate",description:"Offline voiceover with the built-in Windows voices: speaks each line at its time or marker over the audio, plus an SRT.",inputSchema:lR,outputSchema:K,annotations:I},async(e,r)=>{let n=null;try{k(),O(e.video);let o=await W(e.video);if(o.durationSec===null)throw new l(`Could not read duration of ${e.video}.`);let s=e.lines.some(w=>w.marker!==void 0)?(await gr(e.video,r.signal)).markers:[],a=lw(e.lines,s),c=j(e.output,"narrated",Z(e.video),{overwrite:e.overwrite}),u=c.replace(/\.[^./\\]+$/,"")+".srt";if(!e.overwrite&&oR(u))throw new l(`Output already exists: ${u}. Pass overwrite: true to replace it.`);n=iR(Tw(uR(),"screencast-tts-"));let d=a.map((w,g)=>Tw(n,`line-${g}.wav`)),p=await yw(a.map((w,g)=>({text:w.text,path:d[g]})),{voice:e.voice,rate:e.rate,signal:r.signal}),f=a.map((w,g)=>({...w,durationSec:mw(sR(d[g]))})),m=pw(f,o.durationSec),h=fw(e.video,d,c,f,o.durationSec,{hasAudio:o.audioCodec!==null,channels:o.channels,duck:e.duck});await U(h,{output:c,durationSec:o.durationSec,extra:r}),cR(u,it(dw(f,o.durationSec)));let b=We(e.video);return b.length>0&&hr(c,b),S({outputPath:c,srtPath:u,voice:p,lines:f.map(w=>({t:w.t,durationSec:Math.round(w.durationSec*100)/100})),mixedWithOriginal:o.audioCodec!==null,...m.length?{warnings:m}:{}})}catch(o){return E(o)}finally{n&&aR(n,{recursive:!0,force:!0})}})}import{z as ci}from"zod";var pR={input:ci.string().min(1).describe("Path to the source video."),aspect:ci.enum(Un).describe("Target aspect ratio."),fit:ci.enum(la).optional().describe("pad (default): letterbox, nothing lost. crop: fill and center-crop."),output:ci.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ci.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Aw(t){t.registerTool("reframe",{title:"Reframe Aspect Ratio",description:"Re-aspect a video to 16:9, 9:16, 1:1, or 4:5 by padding or cropping.",inputSchema:pR,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=Z(e.input),o=j(e.output,"reframe",n,{overwrite:e.overwrite}),i=Pg(e.input,o,e.aspect,e.fit??"pad");return await U(i,{output:o,durationSec:await ue(e.input),extra:r}),S({outputPath:o,aspect:e.aspect,fit:e.fit??"pad"})}catch(n){return E(n)}})}import{z as Je}from"zod";import{z as sn}from"zod";import{existsSync as dR,readFileSync as mR}from"node:fs";var Vt=.6,li=6,Za=2.5;function ec(t,e,r,n=li){if(t.length===0)throw new l("Give at least one keyframe.");let i=[...t].sort((s,a)=>s.t-a.t).map(s=>{if(!Number.isFinite(s.t)||s.t<0)throw new l("Keyframe t must be a non-negative number.");if(s.full||s.width===void 0||s.height===void 0)return{t:s.t,z:1,cx:e/2,cy:r/2};if(!(s.width>0)||!(s.height>0))throw new l("Keyframe width and height must be positive.");let a=Math.max(1,Math.min(n,e/s.width,r/s.height));return{t:s.t,z:a,cx:(s.x??0)+s.width/2,cy:(s.y??0)+s.height/2}});return i[0]&&i[0].t>0&&i.unshift({t:0,z:1,cx:e/2,cy:r/2}),i}var tt=t=>Number(t.toFixed(4)).toString();function $l(t,e,r){let[n,...o]=t;if(!n)throw new l("Give at least one keyframe.");let i=[tt(n[e])],s=n;for(let a of o){let c=s[e],u=a[e],d=s.t;if(s=a,c===u)continue;let p=a.t,f=Math.max(.001,Math.min(r,p-d)),m=`clip((it-${tt(p-f)})/${tt(f)},0,1)`;i.push(`(${tt(u-c)})*${m}*${m}*(3-2*${m})`)}return At(i)}function _l(t,e,r=Vt){let{width:n,height:o,fps:i}=e,s=n<=1920?2:1,a=$l(t,"z",r),c=$l(t,"cx",r),u=$l(t,"cy",r);return`fps=${tt(i)},scale=${n*s}:${o*s},zoompan=z='${a}':x='clip((${c})*${s}-iw/zoom/2,0,iw-iw/zoom)':y='clip((${u})*${s}-ih/zoom/2,0,ih-ih/zoom)':d=1:s=${n}x${o}:fps=${tt(i)}`}function Mw(t,e,r,n,o=Vt,i="standard",s){let{width:a,height:c,fps:u}=n,d=_l(r,n,o);if(!s||s.clicks.length===0)return["-y","-i",t,"-vf",d,...Re(i),"-c:a","copy",e];let p=["[0:v]null[in]",...gR(s.clicks,a,c,u,s.color),`[out]${d}[v]`].join(";");return["-y","-i",t,"-filter_complex",p,"-map","[v]","-map","0:a?",...Re(i),"-c:a","copy",e]}function Cw(t,e,r,n,o={}){let i=o.step??.25,s=o.holdSec??2,a=o.maxZoom??Za,c=o.globalFraction??.3,u=o.transition??Vt,d=r/t,p=r/a,f=n/a,m=[],h=null,b=()=>{h&&m.push(h),h=null},w=null,g=0;return{push:x=>{let R=w;if(w=x,!R){g=1;return}let T=g++*i,M=Tt(R,x,t,e,{scale:d});if(M.regions.length===0){h&&T-h.last>s&&b();return}if(M.changedFraction>c){b();return}let H=El(M.regions);h&&T-h.last<=s&&fR(h.box,H,r,n)?(h.box=El([h.box,H]),h.last=T):(b(),h={start:T,last:T,box:H})},finish:()=>{b();let x=[],R=0;for(let T of m){let M=Pw(T.box,r,n,p,f),H=Math.max(T.start,R+u),G=Math.max(T.last+s,H+u);x.push({t:ui(H),...M},{t:ui(G),full:!0}),R=G}return x}}}var ui=t=>Math.round(t*100)/100;function El(t){let e=Math.min(...t.map(i=>i.x)),r=Math.min(...t.map(i=>i.y)),n=Math.max(...t.map(i=>i.x+i.width)),o=Math.max(...t.map(i=>i.y+i.height));return{x:e,y:r,width:n-e,height:o-r}}function fR(t,e,r,n){let o=El([t,e]);return o.width<=r/2&&o.height<=n/2}function Pw(t,e,r,n,o){let i=Math.max(t.width*1.4,n),s=Math.max(t.height*1.4,o),a=e/r;i/s>a?s=i/a:i=s*a,i=Math.min(i,e),s=Math.min(s,r);let c=t.x+t.width/2,u=t.y+t.height/2,d=Math.max(0,Math.min(e-i,c-i/2)),p=Math.max(0,Math.min(r-s,u-s/2));return{x:Math.round(d),y:Math.round(p),width:Math.round(i),height:Math.round(s)}}function Iw(t,e,r){return["-v","error","-i",t,"-an","-vf",`fps=${tt(1/r)},scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function tc(t,e,r,n={}){let o=n.holdSec??2,i=n.maxZoom??Za,s=n.transition??Vt,a=e/i,c=r/i,u=Math.min(e,r)*.05,d=[...t].sort((h,b)=>h.t-b.t),p=[],f=0,m=-1/0;for(let h of d){let b=Pw({x:h.x-u,y:h.y-u,width:2*u,height:2*u},e,r,a,c),w=p[p.length-1];if(w&&!w.full&&h.t-m<=o&&hR(w,h)){m=h.t;continue}if(h.t-m>o&&p.length>0){let y=Math.max(m+o,f+s);p.push({t:ui(y),full:!0}),f=y}let g=Math.max(h.t,f+s);p.push({t:ui(g),...b}),f=g,m=h.t}return p.length>0&&p.push({t:ui(Math.max(m+o,f+s)),full:!0}),p}function hR(t,e){let r=t.width*.15,n=t.height*.15;return e.x>=t.x+r&&e.x<=t.x+t.width-r&&e.y>=t.y+n&&e.y<=t.y+t.height-n}var kl=.6,rc="#FF4545";function Tl(t,e){return Math.max(40,2*Math.round(Math.min(t,e)*.045))}function gR(t,e,r,n,o){let i=Tl(e,r),s=i/2,a=Math.max(3,Math.round(i/10)),c=s*.3,u=s-a/2-c,d=[],p="[in]";return t.forEach((f,m)=>{let h=`if(lt(abs(hypot(X-${s},Y-${s})-(${tt(c)}+${tt(u)}*T/${kl})),${a/2}),255*min(1,2-2*T/${kl}),0)`;d.push(`color=c=${o}:s=${i}x${i}:r=${tt(n)}:d=${kl},format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='${h}',setpts=PTS+${tt(f.t)}/TB[ring${m}]`);let b=m===t.length-1?"[out]":`[r${m}]`;d.push(`${p}[ring${m}]overlay=x=${tt(f.x-s)}:y=${tt(f.y-s)}:eof_action=pass${b}`),p=`[r${m}]`}),d}function pi(t){return dR(t)?ze(mR(t,"utf8")).filter(e=>e.type==="down"&&e.inFrame).map(e=>({t:e.t,x:e.x,y:e.y})):null}var nc=sn.object({t:sn.number().nonnegative(),x:sn.number().optional(),y:sn.number().optional(),width:sn.number().positive().optional(),height:sn.number().positive().optional(),full:sn.boolean().optional()});var Fw=200,bR={input:Je.string().min(1).describe("Path to the source video."),keyframes:Je.array(nc).max(100).optional().describe("Views reached by time t: a source rectangle (x, y, width, height), or { t, full: true } to zoom out. Omit to plan them (see follow)."),follow:Je.enum(["auto","clicks","changes"]).optional().describe("Without keyframes: clicks (from the events log of start_recording events: true) or changes (where the screen changed). auto (default): clicks if logged, else changes."),events:Je.string().optional().describe("Events log (default: the input's .events.jsonl); must match the input's timing and size, so use the original recording."),highlightClicks:Je.boolean().optional().describe("Ring each logged click (default false)."),highlightColor:Je.string().optional().describe("Ring color (default #FF4545)."),transitionSec:Je.number().positive().max(5).optional().describe(`How long each zoom/pan eases (default ${Vt}).`),maxZoom:Je.number().min(1).max(li).optional().describe(`Auto mode: the furthest it zooms in (default ${Za}).`),holdSec:Je.number().positive().max(30).optional().describe("Auto mode: stay zoomed this long after activity (default 2)."),dryRun:Je.boolean().optional().describe("Return the planned keyframes only (editable, pass back)."),output:Je.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Je.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ow(t){t.registerTool("zoom",{title:"Zoom and Pan",description:"Smooth animated zoom-and-pan into the action and back out, from keyframes or planned from logged clicks or screen changes.",inputSchema:bR,outputSchema:B({keyframes:Je.array(Je.unknown())}),annotations:I},async(e,r)=>{try{k(),O(e.input);let n=await W(e.input),{width:o,height:i,durationSec:s}=n;if(!o||!i)throw new l(`Could not read the size of ${e.input}.`);let a=n.fps??30,c=e.transitionSec??Vt,u=e.events??ke(e.input).jsonl,d=pi(u);if(e.events&&!d)throw new l(`No event log at ${e.events}.`);if((e.follow==="clicks"||e.highlightClicks)&&!d)throw new l(`No event log for ${e.input} (looked for ${u}). Record with start_recording events: true, or pass events: <path to .events.jsonl>.`);let p=Be(e.highlightColor??rc,"highlightColor"),f=e.keyframes,m=!f,h=e.follow==="clicks"||e.follow!=="changes"&&d&&d.length>0?"clicks":"changes";if(!f&&h==="clicks"&&(f=tc(d??[],o,i,{holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c}),f.length===0))return S({keyframes:[],follow:h,note:"The event log has no clicks inside the frame; nothing written."});if(!f){let v=tg(o,i),x=.25,R=Cw(v.width,v.height,o,i,{step:x,holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c});if(await ji(Iw(e.input,v,x),v.width*v.height,T=>R.push(T),pe(s),{signal:r.signal}),f=R.finish(),f.length===0)return S({keyframes:[],note:"No localised changes found to zoom into; nothing written."})}if(e.dryRun)return S({planned:m,...m?{follow:h}:{},keyframes:f,transitionSec:c});if(e.highlightClicks&&d&&d.length>Fw)throw new l(`${d.length} clicks is more than ${Fw} rings; trim the video or the event log first.`);let b=ec(f,o,i),w=Z(e.input),g=j(e.output,"zoom",w,{overwrite:e.overwrite}),y=e.highlightClicks?{clicks:d??[],color:p}:void 0;return await U(Mw(e.input,g,b,{width:o,height:i,fps:a},c,"standard",y),{output:g,durationSec:s,extra:r}),S({outputPath:g,planned:m,...m?{follow:h}:{},keyframes:f,...y?{ringedClicks:y.clicks.length}:{}})}catch(n){return E(n)}})}import{z as F}from"zod";import{dirname as RR,join as Cr}from"node:path";import{existsSync as sc,mkdtempSync as Gw,readFileSync as qw,rmSync as Xw,writeFileSync as di}from"node:fs";import{tmpdir as Jw}from"node:os";var to=30,Ct=t=>Math.round(t*1e3)/1e3;function Rl(t,e){let r=[...t],n=r.indexOf("-af");return n!==-1&&e.audio.length>0&&(r[n+1]=`${e.audio.join(",")},${r[n+1]}`),r.splice(r.indexOf("-i"),0,...e.seek),r}function Nw(t,e,r){let n=e.slice(r);return n.length>0?cs(t,n):[...t]}function oc(t,e,r,n,o={},i="standard",s={}){if(r.length===0)throw new l("Give at least one step.");if(r.length>to)throw new l(`At most ${to} steps.`);r.forEach(($,J)=>{if(($.op==="export_preset"||$.op==="export_gif")&&J!==r.length-1)throw new l(`${$.op} must be the last step (it is step ${J+1} of ${r.length}).`)});let a=r.findIndex($=>$.op==="zoom"),c=a===-1?-1:r.findIndex(($,J)=>J>a&&$.op==="redact");if(c!==-1)throw new l(`step ${c+1}: redact comes after zoom (step ${a+1}), which moves the content under a fixed box. Put redact before zoom, in the source's coordinates.`);let u=r.some($=>$.op==="redact");if(r.filter($=>$.op==="cut_idle").length>1)throw new l("Use at most one cut_idle step.");let d=n.width,p=n.height,f=n.fps,m=n.durationSec,h=[],b=[],w=1,g=[],y=[],v=!1,x="[0:v]",R=null,T,M=[],H=[],G=[],L=[],C={sx:1,sy:1,ox:0,oy:0},ne=($,J)=>{if(!Number.isFinite($.start)||$.start<0)throw new l(`step ${J}: trim start must be a non-negative number.`);if($.end===void 0==($.duration===void 0))throw new l(`step ${J}: trim takes end OR duration.`);let N=$.end??$.start+$.duration;if(!(N>$.start))throw new l(`step ${J}: trim end must be after start.`);if(m!==null&&$.start>=m)throw new l(`step ${J}: trim starts at ${$.start}s, but the video is ${Ct(m)}s long at that point.`);return{start:$.start,end:m!==null?Math.min(N,m):N}};r.forEach(($,J)=>{let N=J+1,le=`p${J}`,X=`[${le}]`,ee=_=>{g.push(`${x}${_}${X}`),x=X},ie=_=>G.push({step:J,kind:_,seek:[...h],audio:[...y],ops:[...H]});switch($.op){case"trim":{let{start:_,end:P}=ne($,N);J===0?(h.push("-ss",String(_),"-t",String(Ct(P-_))),M.push(`trim ${_}-${Ct(P)}s: input seek`)):(ee(`trim=start=${_}:end=${Ct(P)},setpts=PTS-STARTPTS`),y.push(`atrim=start=${_}:end=${Ct(P)},asetpts=PTS-STARTPTS`),M.push(`trim ${_}-${Ct(P)}s: trim filter`)),v=!0,m=P-_,H.push({op:"trim",start:_,end:P});break}case"crop":ee(_c($,{width:d,height:p})),C&&(C={...C,ox:C.ox-$.x,oy:C.oy-$.y}),d=$.width,p=$.height,M.push(`crop to ${d}x${p}`);break;case"scale":{let _=Tc($),[P,re]=[d,p];({width:d,height:p}=Ip(d,p,$)),C&&(C={sx:C.sx*d/P,sy:C.sy*p/re,ox:C.ox*d/P,oy:C.oy*p/re}),ee(_),M.push(`scale to ${d}x${p}`);break}case"speed":{if($.factor===void 0==($.segments===void 0))throw new l(`step ${N}: speed takes factor or segments.`);if($.segments){let P=$a($.segments,m),re=ka(P,f);ee(re.video),y.push(re.audio),v=!0;let D=tn(P);m!==null&&(m-=D),H.push({op:"cut",spans:P}),M.push(`speed up ${P.length} range(s), ${Ct(D)}s saved`);break}let _=$.factor;if(!Number.isFinite(_)||_<=0)throw new l(`step ${N}: speed factor must be positive.`);ee(`setpts=PTS/${_}`),y.push(Rc(_)),v=!0,m!==null&&(m/=_),H.push({op:"speed",factor:_}),M.push(`speed x${_}`);break}case"redact":{let{steps:_,out:P}=Ac($.regions,$,{width:d,height:p},x,le);g.push(..._),x=P,M.push(`redact ${$.regions.length} region(s), ${$.style??"box"}`);break}case"callout":{let _=o[J];if(!_)throw new l(`Internal: missing callout assets for step ${N}.`);let{steps:P,out:re,extraInputs:D}=il($.items,_,x,w,le);g.push(...P),b.push(...D),w+=D.length/4,x=re,M.push(`callout ${$.items.length} item(s)`);break}case"reframe":{let _=zn[$.aspect];if(!_)throw new l(`step ${N}: unknown aspect "${$.aspect}".`);ee(`${pa(_.w,_.h,$.fit??"pad")},format=yuv420p`),C=null,d=_.w,p=_.h,M.push(`reframe to ${$.aspect} (${$.fit??"pad"})`);break}case"zoom":{let _=$.transitionSec??Vt,P=$.keyframes,re="";if($.follow==="clicks"){if(P)throw new l(`step ${N}: zoom takes keyframes or follow, not both.`);if(!C)throw new l(`step ${N}: zoom follow "clicks" must come before reframe, backdrop or another zoom; the logged click positions no longer match the frame.`);let D=C,A=s.clicks?.[J];if(!A)throw new l(`Internal: missing clicks for step ${N}.`);let ce=A.flatMap(be=>{let Ee=as(be.t,H),$e=be.x*D.sx+D.ox,Ke=be.y*D.sy+D.oy;return Ee!==null&&$e>=0&&$e<d&&Ke>=0&&Ke<p?[{t:Ee,x:$e,y:Ke}]:[]});P=tc(ce,d,p,{holdSec:$.holdSec,maxZoom:$.maxZoom,transition:_}),re=` from ${ce.length} click(s)`}else if(!P||P.length===0)throw new l(`step ${N}: zoom needs keyframes, or follow: "clicks".`);if(P.length===0){M.push("zoom: no clicks in this part of the video; skipped");break}ee(_l(ec(P,d,p),{width:d,height:p,fps:f},_)),C=null,M.push(`zoom ${P.length} keyframe(s)${re}`);break}case"cut_idle":{if(!s.idle)throw new l(`Internal: missing idle scan for step ${N}.`);let _=Sa(_m(s.idle,H),$.minIdleSec??en,$.keepSec??Vo);if(_.length===0){M.push("cut_idle: no idle stretches here; nothing cut");break}if($.action==="speed"){let D=$.factor??Qo,A=_.map(Ee=>({...Ee,factor:D})),ce=ka(A,f);ee(ce.video),y.push(ce.audio),v=!0;let be=tn(A);m!==null&&(m-=be),H.push({op:"cut",spans:A}),M.push(`cut_idle ${_.length} stretch(es) sped up x${D}, ${Ct(be)}s saved`);break}let P=Zu(_);ee(P.video),y.push(P.audio),v=!0;let re=_.reduce((D,A)=>D+(A.end-A.start),0);m!==null&&(m-=re),H.push({op:"cut",spans:_}),M.push(`cut_idle ${_.length} stretch(es), ${Ct(re)}s removed`);break}case"audio":{if($.normalize===void 0&&$.denoise===void 0)throw new l(`step ${N}: audio needs normalize and/or denoise.`);if(!n.hasAudio){M.push("audio: the input has no audio; skipped");break}let _=s.audio?.[J],P=[];if($.denoise!==void 0&&(_?.floorDb===void 0&&ie("noisefloor"),y.push(wl($.denoise,_?.floorDb??null)),P.push(`denoise ${$.denoise}`)),$.normalize!==void 0&&_?.silent)P.push("silent, not normalized");else if($.normalize!==void 0){let re=Zn($.normalize);_?.loudness||ie("loudness"),y.push(bl(re,_?.loudness),"aresample=48000"),P.push(`normalize to ${re.i} LUFS${_?.loudness?` (measured ${_.loudness.input_i})`:""}`)}v=!0,M.push(`audio: ${P.join(", ")}`);break}case"burn_subtitles":{if(!$.subtitles==!$.transcribe)throw new l(`step ${N}: burn_subtitles takes subtitles (a path) or transcribe: true.`);if($.transcribe&&!n.hasAudio)throw new l(`step ${N}: transcribe needs audio, and the input has none.`);let _=s.subtitles?.[J];if(_===""){M.push("burn_subtitles: no cues in this part of the video; skipped");break}_===void 0&&ie($.transcribe?"transcribe":"subtitles");let P=!!$.subtitles&&/\.(ass|ssa)$/i.test($.subtitles),re=$.style??(P?null:"clean");ee(ju(_??"<subtitles.srt>",s.fontsDir??"<fonts>",re)),M.push(`burn_subtitles ${$.transcribe?"from a transcript":"from a file"}, ${re??"file"} style`);break}case"backdrop":{let{op:_,...P}=$,{steps:re,out:D,extraInputs:A,layout:ce}=fl(P,{width:d,height:p},x,w,le);C=null,g.push(...re),b.push(...A),w+=A.length/2,x=D,d=ce.canvasW,p=ce.canvasH,M.push(`backdrop to ${d}x${p}`);break}case"keystroke_overlay":{let _=s.keystrokes?.[J];if(!_)throw new l(`Internal: missing keystroke badges for step ${N}.`);let P=fb(_.badges,H);if(P.length===0){M.push("keystroke_overlay: no badges in this part of the video");break}let{steps:re,out:D}=cl(Ia(P),_,$,{height:p},x,le);g.push(...re),x=D,M.push(`keystroke_overlay ${P.length} badge(s)`);break}case"cursor":{if(!C)throw new l(`step ${N}: cursor must come before zoom, reframe or backdrop; the logged positions no longer match the frame after them.`);let _=s.cursor?.[J];if(!_)throw new l(`Internal: missing cursor plan for step ${N}.`);let P=Da(_.plan,H,C);if(P.path.length===0||P.visible.length===0){M.push("cursor: no cursor movement in this part of the video");break}let{steps:re,out:D,extraInputs:A,commands:ce}=pl(P,$,{width:d,height:p},x,w,le,_.sprite,_.commandsFile);g.push(...re),b.push(...A),w+=A.length/2,x=D,L.push({path:_.commandsFile,content:ce}),M.push(`cursor ${P.path.length} segment(s), ${P.clicks.length} click(s)${$.spotlight?", spotlight":""}`);break}case"export_preset":{let _=Qu($.platform,$.fit??"pad",le);C=null,ee(_.vf),_.af&&y.push(_.af),R=_.encode,d=_.width,p=_.height,f=30,v=!0,M.push(`export_preset ${$.platform}`);break}case"export_gif":{let{op:_,...P}=$;T=P,M.push(`export_gif (${P.format??"gif"}): second stage, size-budget ladder`);break}}});let V=["-y",...h,"-i",t,...b],Y=s.chaptersFile?V.filter($=>$==="-i").length:-1;s.chaptersFile&&V.push("-f","ffmetadata","-i",s.chaptersFile);let q=n.hasAudio&&y.length>0;q&&g.push(`[0:a]${y.join(",")}[aout]`),g.length>0&&V.push("-filter_complex",g.join(";")),V.push("-map",x==="[0:v]"?"0:v":x),n.hasAudio&&V.push("-map",q?"[aout]":"0:a");let Q=R;return Q?V.push(...Q):(V.push(...Re(T||u?"high":i)),n.hasAudio&&V.push(...v?["-c:a","aac","-b:a","160k"]:["-c:a","copy"]),V.push("-movflags","+faststart")),Y!==-1&&V.push("-map_chapters",String(Y)),V.push(e),{args:V,width:d,height:p,fps:f,durationSec:m===null?null:Ct(m),gif:T,summary:M,timeOps:H,pending:G,files:L}}var Lw=["pr_demo","tutorial","social_reel"],wR=1e7,Dw=new Set(["export_preset","export_gif"]);function Bw(t,e){let r=[],n=[{op:"cut_idle"}];e.hasClicks?n.push({op:"zoom",follow:"clicks"}):r.push("zoom left out: no event log with clicks (record with start_recording events: true).");let o=i=>{e.hasAudio&&(e.transcribeBlocker?r.push(`captions left out: ${e.transcribeBlocker}`):n.push({op:"burn_subtitles",transcribe:!0,style:i}))};switch(!e.hasAudio&&t!=="pr_demo"&&r.push("audio and captions left out: the input has no audio."),t){case"pr_demo":n.push({op:"export_gif",maxBytes:wR});break;case"tutorial":e.hasAudio&&n.push({op:"audio",denoise:"light",normalize:"youtube"}),o("clean"),n.push({op:"export_preset",platform:"youtube"});break;case"social_reel":e.hasAudio&&n.push({op:"audio",normalize:"youtube"}),n.push({op:"reframe",aspect:"9:16"}),o("social"),n.push({op:"export_preset",platform:"instagram_reel"});break;default:throw new l(`Unknown recipe "${String(t)}".`)}return{steps:n,notes:r}}var yR=new Set(["redact","crop","cursor"]);function Al(t,e){let r=[...t],o=r.at(-1)&&Dw.has(r.at(-1).op)?r.pop():null,i=r.length,s=new Set,a=[],c=[];for(let u of e){if(Dw.has(u.op)){o=u;continue}let d=r.findIndex((p,f)=>f<i&&!s.has(f)&&p.op===u.op);d===-1&&u.op==="trim"?a.push(u):d===-1&&yR.has(u.op)?c.push(u):d===-1?r.push(u):(r[d]=u,s.add(d))}return[...a,...c,...r,...o?[o]:[]]}import{readFileSync as xR,statSync as SR,writeFileSync as vR}from"node:fs";var Ww=1;function $R(t){return`${t}.edit.json`}function kR(t,e="the edit spec"){let r;try{r=JSON.parse(t)}catch{throw new l(`${e} is not valid JSON.`)}let n=r;if(n?.tool!=="pipeline"||typeof n.version!="number"||!Array.isArray(n.steps)||typeof n.source?.path!="string")throw new l(`${e} is not a pipeline edit spec.`);if(n.version>Ww)throw new l(`${e} was written by a newer version (spec ${n.version}).`,"Update screencast-mcp to re-render it.");return n}function jw(t){let e;try{e=xR(t,"utf8")}catch{throw new l(`Edit spec not found: ${t}`)}return kR(e,t)}function Ml(t){let e=SR(t);return{path:t,size:e.size,mtimeMs:Math.round(e.mtimeMs)}}function Uw(t){let e;try{e=Ml(t.source.path)}catch{return`its source ${t.source.path} is gone`}return e.size!==t.source.size||e.mtimeMs!==t.source.mtimeMs?`its source ${t.source.path} changed since`:null}function zw(t,e){let r=$R(t),n={version:Ww,tool:"pipeline",createdAt:new Date().toISOString(),output:t,...e};return vR(r,JSON.stringify(n,null,2)+`
376
+ `),r}var ER=new Set(["input","inputs","inputA","inputB","clips","a","b","image","overlay","music","video","subtitles","srt","transcript","events","path","file","perf","fromEdit"]),_R=new Set(["output","outputDir","model","fontFile"]),TR=new Set(["whisper"]);function Hw(t){return typeof t=="string"?[t]:Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function ic(t){let e=r=>{if(Array.isArray(r)){r.forEach(e);return}if(!(!r||typeof r!="object"))for(let[n,o]of Object.entries(r)){if(ER.has(n))for(let i of Hw(o))i.trim().length>0&&!TR.has(i)&&hp(i,`Input "${n}"`);else if(_R.has(n))for(let i of Hw(o))tr(i,`"${n}"`);o&&typeof o=="object"&&e(o)}};e(t)}function AR(){if(!Ve("whisper"))return"this ffmpeg has no whisper filter (FFmpeg 8 with whisper.cpp).";try{return Sr(void 0),null}catch{return"no whisper model (set SCREENCAST_WHISPER_MODEL)."}}var MR=F.enum(Un),Yw=F.enum(la).optional(),CR=F.discriminatedUnion("op",[F.object({op:F.literal("trim"),start:F.number().nonnegative(),end:F.number().positive().optional(),duration:F.number().positive().optional()}),F.object({op:F.literal("crop"),x:F.number().int().nonnegative(),y:F.number().int().nonnegative(),width:F.number().int().positive(),height:F.number().int().positive()}),F.object({op:F.literal("scale"),width:F.number().int().positive().optional(),height:F.number().int().positive().optional()}),F.object({op:F.literal("speed"),factor:F.number().positive().optional(),segments:F.array(va).min(1).optional()}),F.object({op:F.literal("redact"),regions:F.array(xn).min(1).optional(),secrets:F.union([F.boolean(),F.string().min(1).max(500)]).optional().describe("OCR for on-screen secrets: true or a regex."),style:F.enum(Oi).optional(),pad:F.number().int().nonnegative().optional(),color:F.string().optional()}),F.object({op:F.literal("callout"),items:F.array(Aa).min(1).max(50),fontFile:_r}),F.object({op:F.literal("reframe"),aspect:MR,fit:Yw}),F.object({op:F.literal("zoom"),keyframes:F.array(nc).min(1).max(100).optional(),follow:F.literal("clicks").optional(),maxZoom:F.number().min(1).max(li).optional(),holdSec:F.number().positive().max(30).optional(),transitionSec:F.number().positive().max(5).optional()}),F.object({op:F.literal("cut_idle"),minIdleSec:F.number().positive().optional(),keepSec:F.number().min(0).optional(),action:F.enum(["cut","speed"]).optional(),factor:F.number().gt(1).max(Zr).optional()}),F.object({op:F.literal("audio"),normalize:za.optional(),denoise:F.enum(Ga).optional()}),F.object({op:F.literal("burn_subtitles"),subtitles:F.string().min(1).optional(),transcribe:F.boolean().optional(),style:F.enum(Vs).optional()}),F.object({op:F.literal("backdrop"),...ja}),F.object({op:F.literal("keystroke_overlay"),...Fa}),F.object({op:F.literal("cursor"),...La}),F.object({op:F.literal("export_preset"),platform:F.enum(da),fit:Yw}),F.object({op:F.literal("export_gif"),format:F.enum(["gif","webp"]).optional(),maxBytes:F.number().int().min(1e4).optional(),fps:F.number().positive().max(30).optional(),width:F.number().int().min(64).max(1920).optional()})]),PR={input:F.string().min(1).optional().describe("Path to the source video."),fromEdit:F.string().min(1).optional().describe("Re-render an .edit.json; steps replace same-op steps."),steps:F.array(CR).max(to).optional().describe(`Edits in order, each { op, ...its tool's options }; export_preset/export_gif only last. Times and pixels are relative to the video as it is at that step (after earlier trims, speed, crops). zoom follow:"clicks" plans from the event log; burn_subtitles takes subtitles or transcribe:true.`),recipe:F.enum(Lw).optional().describe("Polish preset expanded to steps (see dryRun): pr_demo = cut_idle, click zoom, GIF <=10 MB; tutorial = + audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step; trim, redact, crop and cursor go first (source pixels and time)."),quality:F.enum(["draft","standard","high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),dryRun:F.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),output:F.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:F.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),chapters:F.boolean().optional().describe("Keep the input's markers as chapters, re-timed through trims and speed.")};function Kw(t){t.registerTool("pipeline",{title:"Edit Pipeline",description:"Run several edits (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, cursor, reframe, zoom, backdrop, audio, burn_subtitles, then optionally export_preset or export_gif) in one ffmpeg pass: one re-encode, no intermediate files. Prefer it over chaining edit tools; a recipe does the usual polish in one call.",inputSchema:PR,outputSchema:B({processes:F.number().int(),steps:F.array(F.string())}),annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k(),o=e.fromEdit?jw(e.fromEdit):null;if(o){if(ic({input:o.source.path,steps:o.steps}),e.recipe)throw new l("fromEdit already has its steps; leave recipe out.");if(e.input&&!Wo(e.input,o.source.path))throw new l(`The spec is for ${o.source.path}, not ${e.input}.`);let L=Uw(o);if(L)throw new l(`Cannot re-render ${e.fromEdit}: ${L}.`,"Run pipeline on the source again with steps instead.")}let i=e.input??o?.source.path;if(!i)throw new l("Pass input (or fromEdit).");let s=e.quality??o?.quality??"standard",a=e.chapters??o?.chapters??!1;O(i);let c=await W(i),u=c.audioCodec!==null,d=[],p=e.steps??[];if(o&&(p=Al(o.steps,p)),e.recipe){let L=pi(ke(i).jsonl),C=Bw(e.recipe,{hasAudio:u,hasClicks:!!L&&L.length>0,transcribeBlocker:u?AR():null});p=Al(C.steps,p),d.push(...C.notes)}if(p.length===0)throw new l("Give steps, a recipe, or both.");if(p.length>to)throw new l(`At most ${to} steps.`);if(!c.width||!c.height)throw new l(`Could not read the size of ${i}.`);let f={width:c.width,height:c.height,fps:c.fps??30,durationSec:c.durationSec,hasAudio:u},m=pe(c.durationSec),h=p.at(-1);if(!h)throw new l("Provide at least one step.");let b=h.op==="export_gif"?`.${h.format??"gif"}`:".mp4",w=j(e.output,"pipeline",b,{overwrite:e.overwrite,anyContainer:h.op==="export_gif"}),g=h.op!=="export_gif"&&p.some(L=>L.op==="burn_subtitles"&&L.transcribe),y=w.replace(/\.[^./\\]+$/,"")+".srt";if(g&&!e.overwrite&&sc(y))throw new l(`Output already exists: ${y}. Pass overwrite: true to replace it.`);for(let[L,C]of p.entries())if(C.op==="burn_subtitles"){if(!Ve("subtitles"))throw new l("This ffmpeg has no subtitles filter (it needs libass).","Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");if(C.subtitles&&!sc(C.subtitles))throw new l(`step ${L+1}: subtitles file not found: ${C.subtitles}`);if(C.transcribe){if(!Ve("whisper"))throw new l(`step ${L+1}: transcribe needs FFmpeg 8 built with whisper.cpp (no whisper filter here).`);Sr(void 0)}}let v={};for(let[L,C]of p.entries()){if(C.op!=="zoom"||C.follow!=="clicks")continue;let ne=ke(i).jsonl,V=pi(ne);if(!V)throw new l(`step ${L+1}: no event log at ${ne}; record with start_recording events: true.`);v[L]=V}let x,R=p.findIndex(L=>L.op==="cut_idle"),T=p[R];if(T?.op==="cut_idle"){let L=c.durationSec;if(L===null)throw new l(`Could not read the duration of ${i}.`);let C=p.slice(0,R).reduce((q,Q)=>Q.op==="speed"&&Q.factor?q*Q.factor:q,1),ne=u,V=await se(n,ba(i,(T.minIdleSec??en)*C,ne),m,{signal:r.signal});if(V.code!==0)throw new l(`Idle scan failed (exit ${V.code}): ${V.stderr.trim().slice(-400)}`);let Y=wa(V.stderr,L);x=ne?xa(Y,ya(V.stderr,L)):Y}let M=0,H=p;p=[...p];for(let[L,C]of p.entries()){if(C.op!=="redact")continue;let ne=[...C.regions??[]];if(C.secrets){let V=p.slice(0,L);if(V.some(q=>q.op==="speed"||q.op==="cut_idle"))throw new l(`step ${L+1}: put a redact with secrets before speed and cut_idle; it scans the source's clock.`);let Y=V.reduce((q,Q)=>Q.op==="trim"?q+Q.start:q,0);if(e.dryRun)d.push(`Step ${L+1}: the secret scan runs when rendering, not in a dry run.`);else{let q=Gw(Cr(Jw(),"screencast-secrets-"));try{let Q=c.durationSec??0,$=await Rn(i,{everySec:Math.max(1,Math.ceil(Q/Wt)),maxFrames:Wt},q,r.signal),J=typeof C.secrets=="string"?C.secrets:De;for(let N of br($,J,!0).redactRegions){if(N.end-Y<=0)continue;let le={x:Math.round(N.x),y:Math.round(N.y),width:Math.round(N.width),height:Math.round(N.height)};ne.push({...le,start:Math.max(0,N.start-Y),end:N.end-Y}),M++}}finally{Xw(q,{recursive:!0,force:!0})}}}else if(ne.length===0)throw new l(`step ${L+1}: redact needs regions, or secrets: true to find them.`);p[L]={...C,regions:ne}}if(p.some(L=>L.op==="redact"&&L.secrets)&&!e.dryRun&&d.push(M>0?`Blurred ${M} on-screen secret region(s).`:"No on-screen secrets found."),p=p.filter(L=>L.op!=="redact"||L.regions.length>0),p.length===0)throw new l("Nothing to render: the only step was a redact that found no secrets.");let G=Gw(Cr(Jw(),"screencast-pipeline-"));try{let L={},C=[];for(let[D,A]of p.entries()){if(A.op!=="callout")continue;let ce=e.dryRun?{fontFile:"<font>",textFiles:A.items.map(be=>be.type==="text"?"<text>":null),arrowFiles:A.items.map(be=>be.type==="arrow"?"<arrow.png>":null),...sl(A.items,A.fontFile)}:await Ma(A.items,G,`s${D}_`,A.fontFile);L[D]=ce,C.push(...ce.fallbackFonts.map(be=>({step:D,...be}))),d.push(...ce.warnings.map(be=>`Step ${D}, ${be.charAt(0).toLowerCase()}${be.slice(1)}`))}let ne={};for(let[D,A]of p.entries()){if(A.op==="backdrop"&&A.image&&!sc(A.image))throw new l(`step ${D+1}: background image not found: ${A.image}`);if(A.op!=="keystroke_overlay")continue;let{badges:ce}=Oa(i,A.events,A),be=[...new Set(ce.map($e=>$e.label))],Ee=ei(be,e.dryRun?null:G,`s${D}_`,A.fontFile);ne[D]={badges:ce,fontFile:Ee.fontFile,textFiles:Ee.textFiles},d.push(...Ee.warnings.map($e=>`Step ${D}, ${$e.charAt(0).toLowerCase()}${$e.slice(1)}`))}let V={};for(let[D,A]of p.entries())A.op==="cursor"&&(V[D]={plan:Ba(i,A.events,A,c.durationSec),sprite:Na(),commandsFile:e.dryRun?`<cursor ${D}.cmd>`:Cr(G,`s${D}_cursor.cmd`)});let Y=h.op==="export_gif"?e.dryRun?"<temporary stage1.mp4>":Cr(G,"stage1.mp4"):w,q={},Q={},$=RR(Ut("regular")),J=D=>oc(i,Y,p,f,L,s,{keystrokes:ne,cursor:V,idle:x,clicks:v,audio:q,subtitles:Q,fontsDir:$,chaptersFile:D}),N=J(),le;for(let D=0;!e.dryRun&&N.pending.length>0;D++){let A=N.pending[0];if(D>p.length*3)throw new l(`Internal: step ${A.step+1} ${A.kind} did not resolve.`);let ce=p[A.step],be=async Ee=>{let $e=Wi(Rl(Ee,A));try{let Ke=await se(n,$e.args,m,{signal:r.signal});if(Ke.code!==0)throw new l(`step ${A.step+1} ${A.kind} scan failed (exit ${Ke.code}): ${Ke.stderr.trim().slice(-400)}`);return Ke}finally{$e.cleanup()}};if(A.kind==="noisefloor")q[A.step]={...q[A.step],floorDb:Xa((await be(qa(i))).stdout)};else if(A.kind==="loudness"&&ce.op==="audio"){let Ee=await be(ii(i,Zn(ce.normalize)));try{q[A.step]={...q[A.step],loudness:si(Ee.stderr)}}catch{d.push(`Step ${A.step+1}: the audio is silent; not normalized.`),q[A.step]={...q[A.step],silent:!0}}}else if(A.kind==="transcribe"&&ce.op==="burn_subtitles"){let Ee=Cr(G,`s${A.step}_raw.srt`);await te(Rl(Dn(i,Sr(void 0),Ee),A),m,{signal:r.signal});let $e=sc(Ee)?pt(Ue(qw(Ee,"utf8"))):[];Q[A.step]=$e.length>0?Cr(G,`s${A.step}.srt`):"",$e.length>0?(le={cues:$e,opsBefore:A.ops.length},di(Q[A.step],it($e))):d.push(`Step ${A.step+1}: no speech was recognised; no captions.`)}else if(A.kind==="subtitles"&&ce.op==="burn_subtitles"&&ce.subtitles)if(A.ops.length===0)Q[A.step]=ce.subtitles;else{let Ee=qw(ce.subtitles,"utf8"),$e=/\.(ass|ssa)$/i.test(ce.subtitles),Ke=$e?Tm(Ee,A.ops):it(cs(pt(Ue(Ee)),A.ops)),Xl=Cr(G,`s${A.step}${$e?".ass":".srt"}`);di(Xl,Ke),Q[A.step]=$e||Ke.trim()?Xl:""}else throw new l(`Internal: step ${A.step+1} cannot resolve ${A.kind}.`);N=J()}let X=[],ee=[];if(a){let D=N.gif?null:await gr(i,r.signal);if(!D)d.push("chapters: a GIF/WebP cannot hold chapters; none written.");else if(D.markers.length===0)d.push("chapters: the input has no markers (add_marker) or chapters; none written.");else if(ee=Cm(D.markers,N.timeOps),X=N.durationSec?ps(ms(ee),N.durationSec):[],X.length===0)d.push("chapters: no marker falls inside the result; none written.");else{let A=e.dryRun?"<chapters.txt>":Cr(G,"chapters.txt");e.dryRun||di(A,ds(X)),N=J(A)}}let ie={...e.recipe&&{recipe:e.recipe,expandedSteps:p},steps:N.summary,...e.dryRun&&N.pending.length>0&&{measuredOnRun:N.pending.map(D=>`step ${D.step+1}: ${D.kind}`)},processes:N.gif?2:1,width:N.width,height:N.height,durationSec:N.durationSec,...C.length>0&&{fallbackFonts:C},...d.length>0&&{warnings:d},...X.length>0&&{chapters:X}};if(e.dryRun)return S({dryRun:!0,...ie,ffmpegArgs:N.args});let _=()=>{try{let D=e.recipe??o?.recipe;return{editSpecPath:zw(w,{serverVersion:xt(),source:Ml(i),steps:H,...D?{recipe:D}:{},quality:s,chapters:a})}}catch{return{}}};for(let D of N.files)di(D.path,D.content);if(await U(N.args,{output:Y,durationSec:N.durationSec,inputDurationSec:c.durationSec,extra:r}),N.gif){let D=await Gn(Y,w,N.gif,r);return S({outputPath:w,...ie,animation:D,..._()})}let P;if(le)try{let D=Nw(le.cues,N.timeOps,le.opsBefore);D.length>0&&(di(y,it(D)),P=y)}catch{P=void 0}let re;if(X.length>0)try{re=hr(w,ee.filter(D=>D.t<(N.durationSec??1/0)))}catch{}return S({outputPath:w,...ie,...re&&{markersPath:re},...P&&{subtitlesPath:P},..._()})}finally{Xw(G,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as mi}from"zod";var IR={input:mi.string().min(1).describe("Path to the source video."),platform:mi.enum(da).describe("Sets aspect, size, fps, bitrate. steam_trailer: 1080p 5.5 Mbps CBR, -14 LUFS. vertical_reel: 1080x1920 over a blurred copy of itself, -14 LUFS (ignores fit)."),fit:mi.enum(["pad","crop"]).optional().describe("Fit to the platform aspect: pad (default) or crop."),output:mi.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:mi.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Vw(t){t.registerTool("export_preset",{title:"Export for Platform",description:"Encode a platform-ready H.264 file (aspect, fps, bitrate, faststart) for a named platform.",inputSchema:IR,outputSchema:K,annotations:I},async(e,r)=>{try{k(),O(e.input);let n=e.platform,o=j(e.output,n,".mp4",{overwrite:e.overwrite}),i=Ig(e.input,o,n,e.fit??"pad");await U(i,{output:o,durationSec:await ue(e.input),extra:r});let s=Vu[n];return S({outputPath:o,platform:n,aspect:s.aspect,fps:s.fps})}catch(n){return E(n)}})}import{z as _e}from"zod";import{existsSync as ac,mkdirSync as FR,mkdtempSync as OR,readFileSync as Cl,rmSync as Pl,writeFileSync as Qw}from"node:fs";import{tmpdir as NR,release as DR,version as LR}from"node:os";import{join as an}from"node:path";var BR=xt(),WR={input:_e.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),sessionId:_e.string().min(1).optional().describe("Or a stopped session's id."),title:_e.string().max(200).optional().describe("Issue title."),actual:_e.string().max(4e3).optional().describe("What happened."),expected:_e.string().max(4e3).optional().describe("What should happen."),start:_e.number().nonnegative().optional().describe("Clip start s (default: end - clipSec)."),end:_e.number().positive().optional().describe("Clip end s (default: recording end)."),clipSec:_e.number().positive().max(Is).optional().describe(`Clip length without start (default ${Pu}).`),redact:_e.boolean().optional().describe("Box out OCR-found secrets in every output (default true; needs Windows OCR)."),secretPattern:_e.string().optional().describe("Secret regex (default: API keys, tokens, password: values)."),regions:_e.array(xn).optional().describe("Extra boxes (video px; start/end on the clip clock)."),errorPattern:_e.string().optional().describe("Error-line regex."),scanEverySec:_e.number().positive().optional().describe(`OCR every N s (default ${Iu}).`),maxFrames:_e.number().int().min(1).max(vs).optional().describe(`Scan frame cap (default ${Wt}).`),gif:_e.boolean().optional().describe("Also export a GIF (default true)."),maxBytes:_e.number().int().min(1e4).optional().describe(`GIF size budget (default ${Er}).`),outputDir:_e.string().optional().describe("Package folder (default: a new one in SCREENCAST_HOME/edits)."),overwrite:_e.boolean().optional().describe("Replace a report already in outputDir.")},fi=t=>Math.round(t*1e3)/1e3;async function jR(){if(process.platform!=="win32")return null;try{return(await lr()).map(e=>`${e.width}x${e.height}${e.dpi?` @${Math.round(e.dpi/96*100)}%`:""}${e.primary?" (primary)":""}`).join(", ")}catch{return null}}function Zw(t){t.registerTool("bug_report",{title:"Bug Report Package",description:"Package a recording as a paste-ready repro folder: secret-scanned, redacted clip and GIF, contact sheet, steps from the event log, OCR'd errors, environment, report.md for gh issue create --body-file.",inputSchema:WR,outputSchema:B({outputDir:_e.string(),reportPath:_e.string(),jsonPath:_e.string(),clipPath:_e.string()}),annotations:I},async(e,r)=>{let n=null,o=[];try{if(e.input===void 0==(e.sessionId===void 0))throw new l("Provide exactly one of: input (a recording path) or sessionId.");let{ffmpeg:i}=k(),s=await Ns(e),a=await W(s.path);if(!a.width||!a.height)throw new l(`Could not read the size of ${s.path}.`);let c=a.videoDurationSec??a.durationSec;if(c===null)throw new l(`Could not read the duration of ${s.path}.`);let u=Of(c,e),d=fi(u.end-u.start),p=e.redact!==!1,f=e.secretPattern??De;Le(["x"],f),e.errorPattern!==void 0&&Le(["x"],e.errorPattern);let m="gif",h=fn(e.outputDir,we("edits"))??an(we("edits"),`bug-report-${he()}-${ge()}`),b={markdown:an(h,zt.markdown),json:an(h,zt.json),clip:an(h,zt.clip),gif:an(h,zt.gif(m)),sheet:an(h,zt.contactSheet)},w=Object.values(b).filter(v=>ac(v));if(w.length>0&&!e.overwrite)throw new l(`The folder already holds a report: ${w.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);ac(h)||(FR(h,{recursive:!0}),n=h);let g=[],y=OR(an(NR(),"screencast-bug-"));try{let v="unavailable",x=null,R=await vr();if(R.available)x=await Rn(s.path,{everySec:e.scanEverySec??Iu,maxFrames:e.maxFrames??Wt,range:{start:u.start,duration:d}},y,r.signal),v="read";else{if(p)throw new l(`The secret scan needs Windows OCR, which is unavailable here${R.error?` (${R.error})`:""}.`,"Pass redact: false to package without it (then check the clip yourself before sharing), or run doctor.");g.push("Windows OCR is unavailable, so no error text was read.")}let T=x&&p?Nf(br(x,f,!0,"line").redactRegions):[],M=[...T,...e.regions??[]],H=x?Df(x.frames,e.errorPattern??Os,p?f:null):[];r.signal.throwIfAborted();let G=[{op:"trim",start:u.start,end:u.end},...M.length>0?[{op:"redact",regions:M,style:"box"}]:[]],L=oc(s.path,b.clip,G,{width:a.width,height:a.height,fps:a.fps??30,durationSec:a.durationSec,hasAudio:a.audioCodec!==null});await U(L.args,{output:b.clip,durationSec:L.durationSec,inputDurationSec:d,extra:r}),o.push(b.clip);let C=null;e.gif!==!1&&(C=await Gn(b.clip,b.gif,{format:m,maxBytes:e.maxBytes??Er},r),o.push(b.gif),C.note&&g.push(C.note)),await Cs(b.clip,Ms(d,No),b.sheet,{tileWidth:Do},r.signal),o.push(b.sheet);let ne=(s.eventsPath?Cu(ze(Cl(s.eventsPath,"utf8"))):[]).map(P=>p?{...P,text:Le([P.text],f)[0]??P.text}:P),V=s.eventsPath?ne.length===0?"The event log has no clicks, shortcuts, typing, or scrolls.":void 0:"The recording has no input event log (record with start_recording events: true).",Y=jt(s.path),q=ac(Y)?Bf(Es(Cl(Y,"utf8")),u,p?f:null):void 0,Q=vt(s.path),$=ac(Q)?Wf(Cn(Cl(Q,"utf8")),u,s.record?.perf?.summary?.process):[],J=ca(ua(i)??""),N=await jR(),le=s.record,X=P=>p?Le([P],f)[0]??P:P,ee=[["OS",`${LR()} (${DR()}), ${process.arch}`],...N?[["Displays",N]]:[],...le?[["Recorded target",X(le.target)]]:[],...le?.matchedWindow?[["Window",X(le.matchedWindow)]]:[],...le?.backend?[["Capture backend",le.backend]]:[],["Recording",`${a.width}x${a.height}${a.fps?` @ ${Math.round(a.fps*100)/100} fps`:""}, ${fi(c)} s${a.videoCodec?`, ${a.videoCodec}`:""}`],["ffmpeg",J.version??"unknown"],["screencast-mcp",`${BR} (Node ${process.version})`]],ie={title:e.title?.trim()||"Bug report",...e.expected?{expected:e.expected}:{},...e.actual?{actual:e.actual}:{},createdAt:new Date().toISOString(),clip:{start:u.start,end:u.end,recordingDurationSec:fi(c),width:a.width,height:a.height},files:{clip:zt.clip,...C?{gif:zt.gif(m)}:{},contactSheet:zt.contactSheet},...C?{gif:{format:m,sizeBytes:C.sizeBytes,withinBudget:C.withinBudget}}:{},steps:ne.slice(0,Fs),...ne.length>Fs?{stepsOmitted:ne.length-Fs}:{},...V?{stepsNote:V}:{},errors:H,...q?{logs:q}:{},...$.length?{perf:$}:{},ocr:v,redaction:{scanned:x!==null&&p,...x&&p?{everySec:fi(x.step),framesScanned:x.frames.length}:{},found:T.length,manual:e.regions?.length??0},environment:ee};Qw(b.markdown,Lf(ie)),o.push(b.markdown),Qw(b.json,JSON.stringify({...ie,steps:ne,redaction:{...ie.redaction,regions:M}},null,2)+`
377
+ `),o.push(b.json),x?.clamped&&g.push(`The scan interval was widened to ${fi(x.step)} s to fit maxFrames.`);let{images:_}=await Ce([b.sheet],Me,1);return S({outputDir:h,reportPath:b.markdown,jsonPath:b.json,clipPath:b.clip,...C?{gifPath:b.gif,gifSizeBytes:C.sizeBytes,gifWithinBudget:C.withinBudget}:{},contactSheetPath:b.sheet,clip:{start:u.start,end:u.end},steps:ne.length,errors:H.map(P=>P.text),ocr:v,redaction:ie.redaction,...g.length>0?{warnings:g}:{},next:`Review the clip and report.md, then: gh issue create --title ${JSON.stringify(ie.title)} --body-file ${JSON.stringify(b.markdown)} and drag the GIF into the issue.`,note:"Redaction is OCR-based and best-effort: look at the clip before posting it anywhere public."},_)}finally{Pl(y,{recursive:!0,force:!0})}}catch(i){if(n)Pl(n,{recursive:!0,force:!0});else for(let s of o)Pl(s,{force:!0});return E(i)}})}import{z as Pr}from"zod";import{existsSync as cc,mkdirSync as Ll,mkdtempSync as YR,readFileSync as dy,readdirSync as my,rmSync as cn,rmdirSync as KR,statSync as VR,writeFileSync as fy}from"node:fs";import{tmpdir as QR}from"node:os";import{join as Ye}from"node:path";var hi=100,UR=.1,zR=1280,ey=40,HR=24,no={markdown:"guide.md",html:"guide.html",images:"images",image:t=>`step-${String(t).padStart(2,"0")}.png`};function Fl(t){return t.label?`${t.text} ${t.label}`:t.text}var GR=t=>Math.round(t*1e3)/1e3;function qR(t,e,r){let n=Math.max(0,e-1/(r>0?r:30));return GR(Math.min(Math.max(0,t-UR),n))}function Il(t,e,r){let n=Math.max(t.x-e,0,e-(t.x+t.width)),o=Math.max(t.y-r,0,r-(t.y+t.height));return Math.hypot(n,o)}function ty(t,e,r){let o=t.map(s=>({line:s,d:Il(s,e,r)})).filter(s=>s.d<=HR&&s.line.text.trim().length>0).sort((s,a)=>s.d-a.d||s.line.width*s.line.height-a.line.width*a.line.height)[0]?.line;if(!o)return null;let i=o.text.replace(/\s+/g," ").trim();if(i.length>ey){let s=[...o.words].sort((a,c)=>Il(a,e,r)-Il(c,e,r))[0];i=s?s.text.trim():`${i.slice(0,ey-1).trimEnd()}\u2026`}return i.length>0?i:null}function XR(t){let e=t.action==="double_click"?"double-click":"click",r=t.button&&t.button!=="left"?`${t.button.charAt(0).toUpperCase()}${t.button.slice(1)}-${e}`:e;return r.charAt(0).toUpperCase()+r.slice(1)}function Ol(t,e){let r=e.secretPattern??De,n=i=>Le([i],r)[0]??i,o=0;return t.map((i,s)=>{if(i.action==="gap")return{n:0,t:i.t,action:i.action,text:i.text};o++;let a={n:o,t:i.t,action:i.action,text:i.text,shotT:qR(i.t,e.durationSec,e.fps)},c=i.element?.name??e.labels?.[s];if(i.action==="click"||i.action==="double_click"){let u=XR(i);return i.inFrame===!1?{...a,text:i.element?.name?n(`${u} ${Au(i.element)}`):`${u} outside the recorded area`}:{...a,x:i.x,y:i.y,...c?{text:u,label:n(c)}:{text:`${u} the marked spot`}}}return i.action==="scroll"?{...a,...i.inFrame===!1?{}:{x:i.x,y:i.y},...c?{text:`${i.text} over`,label:n(c)}:{}}:i.action==="shortcut"?i.keys?{...a,text:"Press",label:i.keys}:a:i.action==="switch"?{...a,text:n(i.text)}:{...a,text:"Type text"}})}function ry(t,e){let r=[...e].sort((n,o)=>n.t-o.t);return t.map(n=>{let o=r.filter(i=>i.t<=n.t+1e-6).at(-1);return o?{...n,section:o.label}:n})}function ny(t,e){let r=p=>String(Math.round(p)),n=[];for(let p of e.boxes??[])n.push(`drawbox=x=${r(p.x)}:y=${r(p.y)}:w=${r(p.width)}:h=${r(p.height)}:color=black:t=fill`);let o=`scale=w='min(iw,${zR})':h=-2:flags=lanczos`,i=`[0:v]${n.length?n.join(",")+",":""}format=rgba`;if(!e.click)return`${i},${o},format=rgb24[out]`;let s=Tl(t.width,t.height),a=s/2,c=Math.max(3,Math.round(s/10)),u=a-c/2-1,d=e.color??rc;return`${i}[bg];color=c=${d}:s=${s}x${s}:d=1,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='if(lt(abs(hypot(X-${a},Y-${a})-${u}),${c/2}),255,0)'[ring];[bg][ring]overlay=x=${r(e.click.x-a)}:y=${r(e.click.y-a)},${o},format=rgb24[out]`}function oy(t,e,r){return["-y","-v","error","-ss",String(e),"-i",t,"-frames:v","1",r]}var oo=1e7,Qt=[{width:1280,q:4},{width:960,q:6},{width:800,q:8},{width:640,q:10},{width:480,q:14},{width:360,q:20}],Nl=t=>t.replace(/\.png$/i,".jpg");function iy(t,e,r){return["-y","-v","error","-i",t,"-vf",`scale=w='min(iw,${e.width})':h=-2:flags=lanczos,format=yuvj420p`,"-frames:v","1","-q:v",String(e.q),r]}var sy=t=>4*Math.ceil(t/3);function ay(t,e,r=oo){let n=Qt[t].width;for(let o=t+1;o<Qt.length;o++)if(e*(Qt[o].width/n)**2<=r)return o;return t+1<Qt.length?Qt.length-1:null}function cy(t,e,r){return["-y","-v","error","-i",t,"-filter_complex",e,"-map","[out]","-frames:v","1",r]}var ro=t=>t.replace(/\s*\n\s*/g," ").replace(/([\\`*_[\]<>#|])/g,"\\$1");function uy(t){return`${t.ocr==="read"?`Screenshots scanned for secrets with OCR (best-effort); ${t.redactions} region${t.redactions===1?"":"s"} boxed out.`:"Screenshots were not scanned for secrets: review them before sharing."} Typed text is never logged, so it never appears here.`}function ly(t){let e=t.steps.filter(r=>r.n>0).length;return`${e} step${e===1?"":"s"} from a ${Ne(t.recording.durationSec)} recording.`}function py(t){let e=[`# ${ro(t.title)}`,"",ly(t),""];t.steps.length===0&&e.push(`_${t.stepsNote??"No steps in the recording."}_`,"");let r;for(let n of t.steps){if(n.section!==void 0&&n.section!==r&&(r=n.section,e.push(`## ${ro(r)}`,"")),n.n===0){e.push(`> _${ro(n.text)}_`,"");continue}let o=n.label?`${ro(n.text)} **${ro(n.label)}**`:ro(n.text);e.push(`${n.n}. ${o} <sub>${Ne(n.t)}</sub>`,""),n.image&&e.push(` ![Step ${n.n}](${no.images}/${n.image})`,"")}return t.stepsOmitted&&e.push(`_${t.stepsOmitted} more steps not shown._`,""),e.push("<sub>",uy(t),`Generated by screencast-mcp step_guide, ${t.createdAt}.`,"</sub>",""),e.join(`
378
+ `)}var rt=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),JR=`:root{--bg:#f6f5f2;--card:#fff;--ink:#16161a;--dim:#6b6b74;--line:#e2e0da;--rec:#e5383b}
378
379
  @media (prefers-color-scheme:dark){:root{--bg:#121214;--card:#1b1b1f;--ink:#ececf1;--dim:#9a9aa6;--line:#2c2c33}}
379
380
  *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}
380
381
  main{max-width:920px;margin:0 auto;padding:40px 16px 64px}
@@ -389,8 +390,8 @@ li{background:var(--card);border:1px solid var(--line);border-radius:10px;margin
389
390
  .t{margin-left:auto;font:12px/1 ui-monospace,Consolas,monospace;color:var(--dim)}
390
391
  li img{display:block;width:100%;height:auto;border-top:1px solid var(--line)}
391
392
  .note{color:var(--dim);font-style:italic;margin:0 0 18px;padding-left:18px;border-left:3px solid var(--line)}
392
- footer{color:var(--dim);font-size:13px;margin-top:40px;border-top:1px solid var(--line);padding-top:16px}`;function Nl(t,e){let r=[],n,o=!1,i=()=>{o&&r.push("</ol>"),o=!1};for(let s of t.steps){if(s.section!==void 0&&s.section!==n&&(i(),n=s.section,r.push(`<h2>${et(n)}</h2>`)),s.n===0){i(),r.push(`<p class="note">${et(s.text)}</p>`);continue}o||r.push("<ol>"),o=!0;let a=s.label?`${et(s.text)} <strong>${et(s.label)}</strong>`:et(s.text);r.push(`<li><div class="cap"><span class="n">${String(s.n).padStart(2,"0")}</span><span>${a}</span><span class="t">${Fe(s.t)}</span></div>`+(s.image?`<img src="${et(e(s.image))}" alt="Step ${s.n}: ${et(Il(s))}" loading="lazy">`:"")+"</li>")}return i(),t.steps.length===0&&r.push(`<p class="note">${et(t.stepsNote??"No steps in the recording.")}</p>`),t.stepsOmitted&&r.push(`<p class="note">${t.stepsOmitted} more steps not shown.</p>`),["<!doctype html>",'<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">',`<title>${et(t.title)}</title><style>${NA}</style></head><body><main>`,`<header><div class="rec">Step guide</div><h1>${et(t.title)}</h1><p class="meta">${et(Zw(t))}</p></header>`,...r,`<footer>${et(Qw(t))}<br>Generated by screencast-mcp step_guide, ${et(t.createdAt)}.</footer>`,"</main></body></html>",""].join(`
393
- `)}var oy=10,iy=5,jA={input:Tr.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),sessionId:Tr.string().min(1).optional().describe("Or a stopped session's id."),title:Tr.string().max(200).optional().describe("Guide title."),format:Tr.enum(["md","html","both"]).optional().describe("md + images/, self-contained html, or both (default)."),ocr:Tr.boolean().optional().describe("OCR shots for captions and secret boxes (default true; needs Windows OCR)."),outputDir:Tr.string().optional().describe("Guide folder (default: new in SCREENCAST_HOME/edits)."),overwrite:Tr.boolean().optional().describe("Replace a guide already in outputDir.")};function sy(t){t.registerTool("step_guide",{title:"Step-by-Step Guide",description:"Turn a recording's event log into a numbered how-to: a ringed screenshot and caption per step, marker headings; Markdown and/or one HTML file. Never includes typed text.",inputSchema:jA,outputSchema:N({outputDir:Tr.string()}),annotations:I},async(e,r)=>{let n=null,o=[];try{if(e.input===void 0==(e.sessionId===void 0))throw new l("Provide exactly one of: input (a recording path) or sessionId.");k();let i=await Ns(e);if(!i.eventsPath)throw new l("The recording has no input event log, so there are no steps to write.","Record with start_recording events: true, or pass a recording that has a .events.jsonl beside it.");let s=await L(i.path);if(!s.width||!s.height)throw new l(`Could not read the size of ${i.path}.`);let a=s.videoDurationSec??s.durationSec;if(a===null)throw new l(`Could not read the duration of ${i.path}.`);let c=s.fps??30,u=e.format??"both",d=u!=="html",p=u!=="md",f=e.ocr!==!1;if(f){let M=await wr();if(!M.available)throw new l(`Captions and the secret scan need Windows OCR, which is unavailable here${M.error?` (${M.error})`:""}.`,"Pass ocr: false for a guide without them (then check the screenshots yourself before sharing), or run doctor.")}let m=ln(e.outputDir,we("edits"))??Je(we("edits"),`step-guide-${ge()}-${be()}`),h={markdown:Je(m,to.markdown),html:Je(m,to.html),images:Je(m,to.images)},b=[h.markdown,h.html].filter(M=>ac(M));if(b.length>0&&!e.overwrite)throw new l(`The folder already holds a guide: ${b.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);let w=Ru(je(ty(i.eventsPath,"utf8"))),g=w.slice(0,fi),$=Fl(g,{durationSec:a,fps:c}).map((M,R)=>({i:R,s:M})).filter(({s:M})=>M.shotT!==void 0),S=[];ac(m)||(Dl(m,{recursive:!0}),n=m);let C=DA(Je(WA(),"screencast-guide-"));try{let M=vo(r),R=$.length*(f?3:2)||1,P=0,j=()=>M?.(++P/R),X=await He($,async({s:G})=>{let Q=Je(C,`frame-${String(G.n).padStart(3,"0")}.png`);return await Z(Xw(i.path,G.shotT,Q),6e4,{signal:r.signal}),j(),Q}),D=X.map(()=>null);if(f)for(let G=0;G<X.length;G+=oy)r.signal.throwIfAborted(),(await ct(X.slice(G,G+oy),C,r.signal,{sameSize:!0})).forEach((te,T)=>{D[G+T]=te,j()});let ae=g.map(()=>null),ee=$.map(({i:G,s:Q},te)=>{let T=D[te];return T?(Q.x!==void 0&&Q.y!==void 0&&(ae[G]=Hw(T.lines,Q.x,Q.y)),kn({frames:[{...T,t:0,path:""}],step:1,end:1},Ge,!0,"line").redactRegions):[]}),J=Gw(Fl(g,{durationSec:a,fps:c,labels:ae}),Le(i.path)),ie=d?h.images:Je(C,"images");if(d&&ac(ie)&&e.overwrite)for(let G of ry(ie))/^step-\d+\.png$/.test(G)&&nn(Je(ie,G),{force:!0});Dl(ie,{recursive:!0});let ce=0,x={width:s.width,height:s.height},q=await He($,async({i:G},Q)=>{let te=J[G],T=to.image(te.n),_=te.x!==void 0&&te.y!==void 0?{x:te.x,y:te.y}:void 0,A=qw(x,{click:_,boxes:ee[Q]}),z=Je(ie,T);return await Z(Vw(X[Q],A,z),6e4,{signal:r.signal}),j(),{step:te,file:T,out:z}});for(let[G,{step:Q,file:te,out:T}]of q.entries())d&&o.push(T),Q.image=te,ce+=ee[G].length;let H=w.length===0?"The event log has no clicks, shortcuts, typing, or scrolls.":void 0,de={title:e.title?.trim()||"Step-by-step guide",createdAt:new Date().toISOString(),recording:{durationSec:Math.round(a*1e3)/1e3,width:s.width,height:s.height},steps:J,...w.length>fi?{stepsOmitted:w.length-fi}:{},...H?{stepsNote:H}:{},ocr:f?"read":"off",redactions:ce};if(d&&(ny(h.markdown,ey(de)),o.push(h.markdown)),p){let G=Je(C,"html");Dl(G,{recursive:!0});let Q=J.flatMap(K=>K.image?[K.image]:[]),te=K=>`data:image/jpeg;base64,${ty(Je(G,Ol(K))).toString("base64")}`,T=async(K,ue)=>{let me=Je(G,Ol(K));return await Z(Jw(Je(ie,K),ue,me),6e4,{signal:r.signal}),Yw(BA(me).size)},_=Q.length>iy?Q.filter((K,ue)=>ue%Math.ceil(Q.length/iy)===0):[],A=0;for(;_.length>0&&A<Yt.length-1;A++){let K=0;for(let ue of _)K+=await T(ue,Yt[A]);if(K/_.length*Q.length<=ro*.9)break}let z="";for(let K=A;K!==null;){let ue=Yt[K],me=0;for(let uo of Q)me+=await T(uo,ue);z=me<=ro?Nl(de,te):"";let Ne=z?Buffer.byteLength(z):me;if(Ne<=ro)break;let Rt=Kw(K,Ne);Rt===null&&(z||=Nl(de,te),S.push(`guide.html is ${(Buffer.byteLength(z)/1e6).toFixed(1)} MB, over the ${ro/1e6} MB budget even with ${ue.width} px JPEGs; use format: md for a guide this long.`)),K=Rt}ny(h.html,z),o.push(h.html)}if(e.overwrite&&(p||nn(h.html,{force:!0}),!d&&(nn(h.markdown,{force:!0}),ac(h.images)))){for(let G of ry(h.images))/^step-\d+\.png$/.test(G)&&nn(Je(h.images,G),{force:!0});try{LA(h.images)}catch{}}return de.stepsOmitted&&S.push(`Only the first ${fi} steps were written; ${de.stepsOmitted} more were left out.`),H&&S.push(H),v({outputDir:m,...d?{markdownPath:h.markdown,imagesDir:h.images}:{},...p?{htmlPath:h.html}:{},steps:J.map(G=>({...G.n>0?{n:G.n}:{},t:G.t,action:G.action,caption:Il(G),...G.section?{section:G.section}:{},...G.image?{image:G.image}:{}})),ocr:de.ocr,redactions:ce,...S.length>0?{warnings:S}:{},note:f?"Captions are OCR-based templates: rewrite them in guide.md as needed. The secret scan is best-effort: look at the screenshots before sharing.":"Not scanned for secrets: look at the screenshots before sharing."})}finally{nn(C,{recursive:!0,force:!0})}}catch(i){if(n)nn(n,{recursive:!0,force:!0});else for(let s of o)nn(s,{force:!0});return E(i)}})}import{existsSync as ay,rmSync as UA}from"node:fs";import{ResourceTemplate as cy}from"@modelcontextprotocol/sdk/server/mcp.js";import{SubscribeRequestSchema as zA,UnsubscribeRequestSchema as HA}from"@modelcontextprotocol/sdk/types.js";var uy=(t,e)=>({contents:[{uri:t,mimeType:"application/json",text:JSON.stringify(e,null,2)}]});function ly(t){let e=re().get(t);if(!e)throw new l(`No session with id ${t}.`);return e}function dy(t){t.registerResource("sessions","screencast://sessions",{title:"Recording sessions",description:"Every recording session (active and finished), newest first.",mimeType:"application/json"},r=>uy(r.href,re().list())),t.registerResource("session",new cy("screencast://sessions/{id}",{list:()=>({resources:re().list().map(r=>({uri:`screencast://sessions/${r.id}`,name:r.id,title:`${r.status}: ${r.target}`,description:`${r.target} -> ${r.outputPath}`,mimeType:"application/json"}))})}),{title:"Recording session",description:"One session's record.",mimeType:"application/json"},(r,{id:n})=>{let o=ly(String(n));return uy(r.href,{...o,fileExists:ay(o.outputPath)})}),t.registerResource("session-poster",new cy("screencast://sessions/{id}/poster",{list:void 0}),{title:"Recording preview",description:"A JPEG frame from the middle of a session's recording.",mimeType:"image/jpeg"},async(r,{id:n})=>{let o=ly(String(n));if(!ay(o.outputPath))throw new l(`Recording file not found: ${o.outputPath}`);let{durationSec:i}=await L(o.outputPath),s=Ue(".png");try{await Z(["-y","-v","error","-ss",String((i??0)/2),"-i",o.outputPath,"-frames:v","1",s],3e4);let[a]=(await Re([s],960,1)).images;if(!a)throw new l(`Could not extract a thumbnail frame from ${o.outputPath}`);return{contents:[{uri:r.href,mimeType:a.mimeType,blob:a.data}]}}finally{UA(s,{force:!0})}});let e=new Map;t.server.registerCapabilities({resources:{subscribe:!0}}),t.server.setRequestHandler(zA,r=>(e.set(r.params.uri,py(r.params.uri)),{})),t.server.setRequestHandler(HA,r=>(e.delete(r.params.uri),{})),re().onChange(()=>{if(!(ys()||!t.isConnected())){try{t.sendResourceListChanged()}catch{}for(let[r,n]of e){let o=py(r);o!==n&&(e.set(r,o),t.server.sendResourceUpdated({uri:r}).catch(()=>{}))}}})}function py(t){if(t==="screencast://sessions")return JSON.stringify(re().list());let e=/^screencast:\/\/sessions\/([^/]+)$/.exec(t),r=e?re().get(decodeURIComponent(e[1])):void 0;return r?JSON.stringify(r):null}import{z as it}from"zod";var no=t=>({messages:[{role:"user",content:{type:"text",text:t}}]}),oo={bugReproClip:(t,e)=>`Record a short bug-reproduction clip of ${t}.${e?` The bug: ${e}.`:""}
393
+ footer{color:var(--dim);font-size:13px;margin-top:40px;border-top:1px solid var(--line);padding-top:16px}`;function Dl(t,e){let r=[],n,o=!1,i=()=>{o&&r.push("</ol>"),o=!1};for(let s of t.steps){if(s.section!==void 0&&s.section!==n&&(i(),n=s.section,r.push(`<h2>${rt(n)}</h2>`)),s.n===0){i(),r.push(`<p class="note">${rt(s.text)}</p>`);continue}o||r.push("<ol>"),o=!0;let a=s.label?`${rt(s.text)} <strong>${rt(s.label)}</strong>`:rt(s.text);r.push(`<li><div class="cap"><span class="n">${String(s.n).padStart(2,"0")}</span><span>${a}</span><span class="t">${Ne(s.t)}</span></div>`+(s.image?`<img src="${rt(e(s.image))}" alt="Step ${s.n}: ${rt(Fl(s))}" loading="lazy">`:"")+"</li>")}return i(),t.steps.length===0&&r.push(`<p class="note">${rt(t.stepsNote??"No steps in the recording.")}</p>`),t.stepsOmitted&&r.push(`<p class="note">${t.stepsOmitted} more steps not shown.</p>`),["<!doctype html>",'<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">',`<title>${rt(t.title)}</title><style>${JR}</style></head><body><main>`,`<header><div class="rec">Step guide</div><h1>${rt(t.title)}</h1><p class="meta">${rt(ly(t))}</p></header>`,...r,`<footer>${rt(uy(t))}<br>Generated by screencast-mcp step_guide, ${rt(t.createdAt)}.</footer>`,"</main></body></html>",""].join(`
394
+ `)}var hy=10,gy=5,ZR={input:Pr.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),sessionId:Pr.string().min(1).optional().describe("Or a stopped session's id."),title:Pr.string().max(200).optional().describe("Guide title."),format:Pr.enum(["md","html","both"]).optional().describe("md + images/, self-contained html, or both (default)."),ocr:Pr.boolean().optional().describe("OCR shots for captions and secret boxes (default true; needs Windows OCR)."),outputDir:Pr.string().optional().describe("Guide folder (default: new in SCREENCAST_HOME/edits)."),overwrite:Pr.boolean().optional().describe("Replace a guide already in outputDir.")};function by(t){t.registerTool("step_guide",{title:"Step-by-Step Guide",description:"Turn a recording's event log into a numbered how-to: a ringed screenshot and caption per step, marker headings; Markdown and/or one HTML file. Never includes typed text.",inputSchema:ZR,outputSchema:B({outputDir:Pr.string()}),annotations:I},async(e,r)=>{let n=null,o=[];try{if(e.input===void 0==(e.sessionId===void 0))throw new l("Provide exactly one of: input (a recording path) or sessionId.");k();let i=await Ns(e);if(!i.eventsPath)throw new l("The recording has no input event log, so there are no steps to write.","Record with start_recording events: true, or pass a recording that has a .events.jsonl beside it.");let s=await W(i.path);if(!s.width||!s.height)throw new l(`Could not read the size of ${i.path}.`);let a=s.videoDurationSec??s.durationSec;if(a===null)throw new l(`Could not read the duration of ${i.path}.`);let c=s.fps??30,u=e.format??"both",d=u!=="html",p=u!=="md",f=e.ocr!==!1;if(f){let T=await vr();if(!T.available)throw new l(`Captions and the secret scan need Windows OCR, which is unavailable here${T.error?` (${T.error})`:""}.`,"Pass ocr: false for a guide without them (then check the screenshots yourself before sharing), or run doctor.")}let m=fn(e.outputDir,we("edits"))??Ye(we("edits"),`step-guide-${he()}-${ge()}`),h={markdown:Ye(m,no.markdown),html:Ye(m,no.html),images:Ye(m,no.images)},b=[h.markdown,h.html].filter(T=>cc(T));if(b.length>0&&!e.overwrite)throw new l(`The folder already holds a guide: ${b.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);let w=Mu(ze(dy(i.eventsPath,"utf8"))),g=w.slice(0,hi),v=Ol(g,{durationSec:a,fps:c}).map((T,M)=>({i:M,s:T})).filter(({s:T})=>T.shotT!==void 0),x=[];cc(m)||(Ll(m,{recursive:!0}),n=m);let R=YR(Ye(QR(),"screencast-guide-"));try{let T=$o(r),M=v.length*(f?3:2)||1,H=0,G=()=>T?.(++H/M),L=await qe(v,async({s:X})=>{let ee=Ye(R,`frame-${String(X.n).padStart(3,"0")}.png`);return await te(oy(i.path,X.shotT,ee),6e4,{signal:r.signal}),G(),ee}),C=L.map(()=>null);if(f)for(let X=0;X<L.length;X+=hy)r.signal.throwIfAborted(),(await lt(L.slice(X,X+hy),R,r.signal,{sameSize:!0})).forEach((ie,_)=>{C[X+_]=ie,G()});let ne=g.map(()=>null),V=v.map(({i:X,s:ee},ie)=>{let _=C[ie];return _?(ee.x!==void 0&&ee.y!==void 0&&(ne[X]=ty(_.lines,ee.x,ee.y)),br({frames:[{..._,t:0,path:""}],step:1,end:1},De,!0,"line").redactRegions):[]}),Y=ry(Ol(g,{durationSec:a,fps:c,labels:ne}),We(i.path)),q=d?h.images:Ye(R,"images");if(d&&cc(q)&&e.overwrite)for(let X of my(q))/^step-\d+\.png$/.test(X)&&cn(Ye(q,X),{force:!0});Ll(q,{recursive:!0});let Q=0,$={width:s.width,height:s.height},J=await qe(v,async({i:X},ee)=>{let ie=Y[X],_=no.image(ie.n),P=ie.x!==void 0&&ie.y!==void 0?{x:ie.x,y:ie.y}:void 0,re=ny($,{click:P,boxes:V[ee]}),D=Ye(q,_);return await te(cy(L[ee],re,D),6e4,{signal:r.signal}),G(),{step:ie,file:_,out:D}});for(let[X,{step:ee,file:ie,out:_}]of J.entries())d&&o.push(_),ee.image=ie,Q+=V[X].length;let N=w.length===0?"The event log has no clicks, shortcuts, typing, or scrolls.":void 0,le={title:e.title?.trim()||"Step-by-step guide",createdAt:new Date().toISOString(),recording:{durationSec:Math.round(a*1e3)/1e3,width:s.width,height:s.height},steps:Y,...w.length>hi?{stepsOmitted:w.length-hi}:{},...N?{stepsNote:N}:{},ocr:f?"read":"off",redactions:Q};if(d&&(fy(h.markdown,py(le)),o.push(h.markdown)),p){let X=Ye(R,"html");Ll(X,{recursive:!0});let ee=Y.flatMap(A=>A.image?[A.image]:[]),ie=A=>`data:image/jpeg;base64,${dy(Ye(X,Nl(A))).toString("base64")}`,_=async(A,ce)=>{let be=Ye(X,Nl(A));return await te(iy(Ye(q,A),ce,be),6e4,{signal:r.signal}),sy(VR(be).size)},P=ee.length>gy?ee.filter((A,ce)=>ce%Math.ceil(ee.length/gy)===0):[],re=0;for(;P.length>0&&re<Qt.length-1;re++){let A=0;for(let ce of P)A+=await _(ce,Qt[re]);if(A/P.length*ee.length<=oo*.9)break}let D="";for(let A=re;A!==null;){let ce=Qt[A],be=0;for(let Ke of ee)be+=await _(Ke,ce);D=be<=oo?Dl(le,ie):"";let Ee=D?Buffer.byteLength(D):be;if(Ee<=oo)break;let $e=ay(A,Ee);$e===null&&(D||=Dl(le,ie),x.push(`guide.html is ${(Buffer.byteLength(D)/1e6).toFixed(1)} MB, over the ${oo/1e6} MB budget even with ${ce.width} px JPEGs; use format: md for a guide this long.`)),A=$e}fy(h.html,D),o.push(h.html)}if(e.overwrite&&(p||cn(h.html,{force:!0}),!d&&(cn(h.markdown,{force:!0}),cc(h.images)))){for(let X of my(h.images))/^step-\d+\.png$/.test(X)&&cn(Ye(h.images,X),{force:!0});try{KR(h.images)}catch{}}return le.stepsOmitted&&x.push(`Only the first ${hi} steps were written; ${le.stepsOmitted} more were left out.`),N&&x.push(N),S({outputDir:m,...d?{markdownPath:h.markdown,imagesDir:h.images}:{},...p?{htmlPath:h.html}:{},steps:Y.map(X=>({...X.n>0?{n:X.n}:{},t:X.t,action:X.action,caption:Fl(X),...X.section?{section:X.section}:{},...X.image?{image:X.image}:{}})),ocr:le.ocr,redactions:Q,...x.length>0?{warnings:x}:{},note:f?"Captions are OCR-based templates: rewrite them in guide.md as needed. The secret scan is best-effort: look at the screenshots before sharing.":"Not scanned for secrets: look at the screenshots before sharing."})}finally{cn(R,{recursive:!0,force:!0})}}catch(i){if(n)cn(n,{recursive:!0,force:!0});else for(let s of o)cn(s,{force:!0});return E(i)}})}import{existsSync as wy,rmSync as eA}from"node:fs";import{ResourceTemplate as yy}from"@modelcontextprotocol/sdk/server/mcp.js";import{SubscribeRequestSchema as tA,UnsubscribeRequestSchema as rA}from"@modelcontextprotocol/sdk/types.js";var xy=(t,e)=>({contents:[{uri:t,mimeType:"application/json",text:JSON.stringify(e,null,2)}]});function Sy(t){let e=oe().get(t);if(!e)throw new l(`No session with id ${t}.`);return e}function $y(t){t.registerResource("sessions","screencast://sessions",{title:"Recording sessions",description:"Every recording session (active and finished), newest first.",mimeType:"application/json"},r=>xy(r.href,oe().list())),t.registerResource("session",new yy("screencast://sessions/{id}",{list:()=>({resources:oe().list().map(r=>({uri:`screencast://sessions/${r.id}`,name:r.id,title:`${r.status}: ${r.target}`,description:`${r.target} -> ${r.outputPath}`,mimeType:"application/json"}))})}),{title:"Recording session",description:"One session's record.",mimeType:"application/json"},(r,{id:n})=>{let o=Sy(String(n));return xy(r.href,{...o,fileExists:wy(o.outputPath)})}),t.registerResource("session-poster",new yy("screencast://sessions/{id}/poster",{list:void 0}),{title:"Recording preview",description:"A JPEG frame from the middle of a session's recording.",mimeType:"image/jpeg"},async(r,{id:n})=>{let o=Sy(String(n));if(!wy(o.outputPath))throw new l(`Recording file not found: ${o.outputPath}`);let{durationSec:i}=await W(o.outputPath),s=He(".png");try{await te(["-y","-v","error","-ss",String((i??0)/2),"-i",o.outputPath,"-frames:v","1",s],3e4);let[a]=(await Ce([s],960,1)).images;if(!a)throw new l(`Could not extract a thumbnail frame from ${o.outputPath}`);return{contents:[{uri:r.href,mimeType:a.mimeType,blob:a.data}]}}finally{eA(s,{force:!0})}});let e=new Map;t.server.registerCapabilities({resources:{subscribe:!0}}),t.server.setRequestHandler(tA,r=>(e.set(r.params.uri,vy(r.params.uri)),{})),t.server.setRequestHandler(rA,r=>(e.delete(r.params.uri),{})),oe().onChange(()=>{if(!(xs()||!t.isConnected())){try{t.sendResourceListChanged()}catch{}for(let[r,n]of e){let o=vy(r);o!==n&&(e.set(r,o),t.server.sendResourceUpdated({uri:r}).catch(()=>{}))}}})}function vy(t){if(t==="screencast://sessions")return JSON.stringify(oe().list());let e=/^screencast:\/\/sessions\/([^/]+)$/.exec(t),r=e?oe().get(decodeURIComponent(e[1])):void 0;return r?JSON.stringify(r):null}import{z as at}from"zod";var io=t=>({messages:[{role:"user",content:{type:"text",text:t}}]}),so={bugReproClip:(t,e)=>`Record a short bug-reproduction clip of ${t}.${e?` The bug: ${e}.`:""}
394
395
 
395
396
  1. start_recording { target: "${t}", quality: "standard" }, then tell me to reproduce the bug (or reproduce it yourself if you can drive the app), and stop_recording when done.
396
397
  2. sample_frames { input: <recording>, mode: "scenes" } to see what happened, and describe the moment the bug appears.
@@ -427,63 +428,63 @@ Give a timestamped summary of the main steps and anything that looks wrong.`,doc
427
428
  1. start_recording { target: "${t}", events: true } so every click and shortcut is logged, then do the task (or ask me to). Between phases, add_marker { sessionId: <id>, label: <phase name> } so the guide gets section headings. Then stop_recording.
428
429
  2. step_guide { sessionId: <session id>, title: <what the guide teaches> }. It writes guide.md (with an images folder) and a self-contained guide.html: one screenshot per step, the click ringed, captioned from the text under it, secrets boxed out. Typed text is never logged; say what to type in the captions yourself.
429
430
  3. Read the returned steps and rewrite any vague caption ("Click the marked spot") in guide.md, using the screenshot to name the control.
430
- Report the guide paths, the steps, and anything you would check before sharing it.`};function my(t){t.registerPrompt("bug-repro-clip",{title:"Record a bug reproduction",description:"Record a target, find the bug moment, redact secrets, trim, annotate, and export a GIF for an issue.",argsSchema:{target:it.string().optional().describe("What to record, e.g. window:My App (default: full)."),notes:it.string().optional().describe("What the bug is.")}},({target:e,notes:r})=>no(oo.bugReproClip(e||"full",r??""))),t.registerPrompt("file-bug-report",{title:"File a bug report",description:"Record a repro with input events, then package it with bug_report: redacted clip, GIF, steps, error text, and report.md.",argsSchema:{target:it.string().optional().describe("What to record, e.g. window:My App (default: full)."),notes:it.string().optional().describe("What the bug is."),expected:it.string().optional().describe("What should happen instead.")}},({target:e,notes:r,expected:n})=>no(oo.fileBugReport(e||"full",r??"",n??""))),t.registerPrompt("demo-gif",{title:"Make a demo GIF",description:"Record a feature walkthrough and export a GIF small enough for a README or PR.",argsSchema:{target:it.string().optional().describe("What to record (default: full)."),maxMB:it.string().optional().describe("Size budget in MB (default 10).")}},({target:e,maxMB:r})=>no(oo.demoGif(e||"full",r||"10"))),t.registerPrompt("verify-ui-change",{title:"Verify a UI change",description:"Screenshot before, make the change, wait for the screen to settle, diff, and check the text.",argsSchema:{target:it.string().optional().describe("What to watch (default: full)."),expectation:it.string().optional().describe("What should change.")}},({target:e,expectation:r})=>no(oo.verifyUiChange(e||"full",r??""))),t.registerPrompt("review-recording",{title:"Review a recording",description:"Summarize what happens in a recording, with timestamps, using a contact sheet and scene frames.",argsSchema:{path:it.string().describe("Path to the recording.")}},({path:e})=>no(oo.reviewRecording(e))),t.registerPrompt("document-steps",{title:"Document what I just did",description:"Record a task with input events and markers, then turn it into a step-by-step guide with step_guide.",argsSchema:{target:it.string().optional().describe("What to record (default: full)."),task:it.string().optional().describe("The task the guide teaches.")}},({target:e,task:r})=>no(oo.documentSteps(e||"full",r??"")))}import{fileURLToPath as GA}from"node:url";import{RootsListChangedNotificationSchema as qA}from"@modelcontextprotocol/sdk/types.js";function XA(t){let e=[];for(let{uri:r}of t)if(r.startsWith("file:"))try{e.push(GA(r))}catch{}return e}function fy(t){let e=t.server,r=async o=>{if(!e.getClientCapabilities()?.roots){go(null);return}o&&go("pending");try{let{roots:i}=await e.listRoots();go(XA(i))}catch(i){o&&go([]),process.stderr.write(`roots/list failed: ${U(i)}
431
- `)}},n=e.oninitialized;e.oninitialized=()=>{n?.(),r(!0)},e.setNotificationHandler(qA,()=>r(!1))}var YA=wt();function cc(t={}){let e=gi(t.toolsets??process.env.SCREENCAST_TOOLSETS);e.unknown.length>0&&console.error(`screencast-mcp: ignoring unknown SCREENCAST_TOOLSETS entries: ${e.unknown.join(", ")} (known: all, ${hi.join(", ")})`);let r=new JA({name:"screencast-mcp",version:YA},{capabilities:{logging:{}},instructions:Xl(e)});jp(r);let n=KA(r);return vf(r),kf(r),mh(r),gh(r),wh(r),fh(r),Sh(r),vh(r),kh(r),Eh(r),Xh(r),Jh(r),Kh(r),Vh(r),og(r),cg(r),pg(r),wg(r),Sg(r),vg(r),$g(r),Pg(r),Ig(r),Lg(r),Bg(r),Wg(r),Ug(r),zg(r),Yg(r),rb(r),nb(r),cb(r),fb(r),xb(r),_b(r),Tb(r),Ab(r),Ib(r),Fb(r),Ob(r),Nb(r),Oh(r),Db(r),Lb(r),qb(r),Xb(r),Jb(r),xh(r),Qb(r),fw(r),hw(r),gw(r),bw(r),ww(r),xw(r),Sw(r),Tw(r),Bw(r),Ww(r),Uw(r),sy(r),VA(n,e),dy(r),my(r),fy(r),r}function KA(t){let e=new Map,r=t.registerTool.bind(t);return t.registerTool=((...n)=>{let o=n.length-1,i=n[o];n[o]=(a,c)=>{try{oc(a)}catch(u){return E(u)}return i(a,c)};let s=r(...n);return e.set(n[0],s),s}),e}function VA(t,e){for(let[r,n]of t){let o=ql(r);if(!o)throw new Error(`Tool "${r}" belongs to no toolset; add it to TOOLSETS in src/utils/toolsets.ts.`);e.enabled.includes(o)||n.remove()}}import{spawn as gy}from"node:child_process";import{copyFileSync as QA,existsSync as ZA,mkdirSync as eR,readFileSync as tR,writeFileSync as rR}from"node:fs";import{homedir as nR}from"node:os";import{dirname as oR,join as on}from"node:path";import{createInterface as iR}from"node:readline/promises";var uc=["claude-desktop","claude-code","cursor","vscode"],by=`setup options:
431
+ Report the guide paths, the steps, and anything you would check before sharing it.`};function ky(t){t.registerPrompt("bug-repro-clip",{title:"Record a bug reproduction",description:"Record a target, find the bug moment, redact secrets, trim, annotate, and export a GIF for an issue.",argsSchema:{target:at.string().optional().describe("What to record, e.g. window:My App (default: full)."),notes:at.string().optional().describe("What the bug is.")}},({target:e,notes:r})=>io(so.bugReproClip(e||"full",r??""))),t.registerPrompt("file-bug-report",{title:"File a bug report",description:"Record a repro with input events, then package it with bug_report: redacted clip, GIF, steps, error text, and report.md.",argsSchema:{target:at.string().optional().describe("What to record, e.g. window:My App (default: full)."),notes:at.string().optional().describe("What the bug is."),expected:at.string().optional().describe("What should happen instead.")}},({target:e,notes:r,expected:n})=>io(so.fileBugReport(e||"full",r??"",n??""))),t.registerPrompt("demo-gif",{title:"Make a demo GIF",description:"Record a feature walkthrough and export a GIF small enough for a README or PR.",argsSchema:{target:at.string().optional().describe("What to record (default: full)."),maxMB:at.string().optional().describe("Size budget in MB (default 10).")}},({target:e,maxMB:r})=>io(so.demoGif(e||"full",r||"10"))),t.registerPrompt("verify-ui-change",{title:"Verify a UI change",description:"Screenshot before, make the change, wait for the screen to settle, diff, and check the text.",argsSchema:{target:at.string().optional().describe("What to watch (default: full)."),expectation:at.string().optional().describe("What should change.")}},({target:e,expectation:r})=>io(so.verifyUiChange(e||"full",r??""))),t.registerPrompt("review-recording",{title:"Review a recording",description:"Summarize what happens in a recording, with timestamps, using a contact sheet and scene frames.",argsSchema:{path:at.string().describe("Path to the recording.")}},({path:e})=>io(so.reviewRecording(e))),t.registerPrompt("document-steps",{title:"Document what I just did",description:"Record a task with input events and markers, then turn it into a step-by-step guide with step_guide.",argsSchema:{target:at.string().optional().describe("What to record (default: full)."),task:at.string().optional().describe("The task the guide teaches.")}},({target:e,task:r})=>io(so.documentSteps(e||"full",r??"")))}import{fileURLToPath as nA}from"node:url";import{RootsListChangedNotificationSchema as oA}from"@modelcontextprotocol/sdk/types.js";function iA(t){let e=[];for(let{uri:r}of t)if(r.startsWith("file:"))try{e.push(nA(r))}catch{}return e}function Ey(t){let e=t.server,r=async o=>{if(!e.getClientCapabilities()?.roots){bo(null);return}o&&bo("pending");try{let{roots:i}=await e.listRoots();bo(iA(i))}catch(i){o&&bo([]),process.stderr.write(`roots/list failed: ${z(i)}
432
+ `)}},n=e.oninitialized;e.oninitialized=()=>{n?.(),r(!0)},e.setNotificationHandler(oA,()=>r(!1))}var aA=xt();function uc(t={}){let e=bi(t.toolsets??process.env.SCREENCAST_TOOLSETS);e.unknown.length>0&&console.error(`screencast-mcp: ignoring unknown SCREENCAST_TOOLSETS entries: ${e.unknown.join(", ")} (known: all, ${gi.join(", ")})`);let r=new sA({name:"screencast-mcp",version:aA},{capabilities:{logging:{}},instructions:Yl(e)});zp(r);let n=cA(r);return kf(r),_f(r),hh(r),wh(r),xh(r),gh(r),$h(r),kh(r),_h(r),Th(r),Yh(r),Kh(r),Qh(r),Zh(r),sg(r),lg(r),mg(r),xg(r),$g(r),kg(r),Eg(r),Fg(r),Og(r),Wg(r),jg(r),Ug(r),Hg(r),Gg(r),Vg(r),ob(r),ib(r),lb(r),gb(r),vb(r),Rb(r),Ab(r),Mb(r),Ob(r),Nb(r),Db(r),Lb(r),Dh(r),Bb(r),Wb(r),Jb(r),Yb(r),Kb(r),vh(r),ew(r),vw(r),$w(r),kw(r),Ew(r),_w(r),Rw(r),Aw(r),Ow(r),Kw(r),Vw(r),Zw(r),by(r),uA(n,e),$y(r),ky(r),Ey(r),r}function cA(t){let e=new Map,r=t.registerTool.bind(t);return t.registerTool=((...n)=>{let o=n.length-1,i=n[o];n[o]=(a,c)=>{try{ic(a)}catch(u){return E(u)}return i(a,c)};let s=r(...n);return e.set(n[0],s),s}),e}function uA(t,e){for(let[r,n]of t){let o=Jl(r);if(!o)throw new Error(`Tool "${r}" belongs to no toolset; add it to TOOLSETS in src/utils/toolsets.ts.`);e.enabled.includes(o)||n.remove()}}import{spawn as Ty}from"node:child_process";import{copyFileSync as lA,existsSync as pA,mkdirSync as dA,readFileSync as mA,writeFileSync as fA}from"node:fs";import{homedir as hA}from"node:os";import{dirname as gA,join as un}from"node:path";import{createInterface as bA}from"node:readline/promises";var lc=["claude-desktop","claude-code","cursor","vscode"],Ry=`setup options:
432
433
  --yes, -y answer yes: install FFmpeg and write client configs without asking
433
434
  --dry-run print the checks and the config changes; change nothing
434
435
  --clients <list> (or --clients=<list>) detected (default) | none | a comma list of
435
- ${uc.join(", ")}
436
+ ${lc.join(", ")}
436
437
  --no-install never offer to install FFmpeg
437
438
  --force replace an existing, different "screencast" server entry
438
439
  --test record a 3 s test clip and export a GIF
439
440
 
440
441
  setup exits 0 when the doctor checks pass, 1 when something still needs fixing.
441
- `,Bl="@tmhs/screencast-mcp",io="screencast",Ll={command:"npx",args:["-y",Bl]},hy=["install","--id","Gyan.FFmpeg","-e","--accept-source-agreements","--accept-package-agreements"];function wy(t){let e={yes:!1,dryRun:!1,install:!0,clients:"detected",force:!1,test:!1};for(let r=0;r<t.length;r++){let n=t[r]??"",o=n.startsWith("--")?n.indexOf("="):-1;switch(o===-1?n:n.slice(0,o)){case"--yes":case"-y":e.yes=!0;break;case"--dry-run":e.dryRun=!0;break;case"--no-install":e.install=!1;break;case"--force":e.force=!0;break;case"--test":e.test=!0;break;case"--clients":{let s;if(o!==-1?s=n.slice(o+1):s=t[++r],s===void 0||s==="")throw new Error("--clients needs a value.");if(s==="detected"||s==="none"){e.clients=s;break}let a=s.split(",").map(u=>u.trim()).filter(Boolean),c=a.filter(u=>!uc.includes(u));if(c.length>0)throw new Error(`--clients: unknown client ${c.map(u=>`"${u}"`).join(", ")}; use ${uc.join(", ")}, detected, or none.`);e.clients=a;break}default:throw new Error(`Unknown setup option "${n}". Run screencast-mcp --help.`)}}return e}function sR(t){return t.env.APPDATA??on(t.home,"AppData","Roaming")}function yy(t){let e=sR(t);return[{id:"claude-desktop",name:"Claude Desktop",path:on(e,"Claude","claude_desktop_config.json"),key:"mcpServers",entry:Ll,marker:on(e,"Claude")},{id:"cursor",name:"Cursor",path:on(t.home,".cursor","mcp.json"),key:"mcpServers",entry:Ll,marker:on(t.home,".cursor")},{id:"vscode",name:"VS Code",path:on(e,"Code","User","mcp.json"),key:"servers",entry:{type:"stdio",...Ll},marker:on(e,"Code","User")}]}function aR(t){return["mcp","add","--scope","user",io,"--",...t==="win32"?["cmd","/c","npx","-y",Bl]:["npx","-y",Bl]]}var cR=(t,e)=>JSON.stringify(t)===JSON.stringify(e);function uR(t,e,r,n,o=!1){let i={};if(t!==null&&t.trim()!==""){let u;try{u=JSON.parse(t.charCodeAt(0)===65279?t.slice(1):t)}catch(d){return{status:"invalid",reason:`not plain JSON (${U(d)})`}}if(typeof u!="object"||u===null||Array.isArray(u))return{status:"invalid",reason:"the file is not a JSON object"};i=u}let s=i[e]??{};if(typeof s!="object"||s===null||Array.isArray(s))return{status:"invalid",reason:`"${e}" is not an object`};let a=s[r];if(a!==void 0){if(cR(a,n))return{status:"unchanged"};if(!o)return{status:"conflict",existing:a}}let c={...i,[e]:{...s,[r]:n}};return{status:"added",text:JSON.stringify(c,null,2)+`
442
- `}}function lR(t,e){let r=t===""?[]:t.replace(/\n$/,"").split(`
442
+ `,Wl="@tmhs/screencast-mcp",ao="screencast",Bl={command:"npx",args:["-y",Wl]},_y=["install","--id","Gyan.FFmpeg","-e","--accept-source-agreements","--accept-package-agreements"];function Ay(t){let e={yes:!1,dryRun:!1,install:!0,clients:"detected",force:!1,test:!1};for(let r=0;r<t.length;r++){let n=t[r]??"",o=n.startsWith("--")?n.indexOf("="):-1;switch(o===-1?n:n.slice(0,o)){case"--yes":case"-y":e.yes=!0;break;case"--dry-run":e.dryRun=!0;break;case"--no-install":e.install=!1;break;case"--force":e.force=!0;break;case"--test":e.test=!0;break;case"--clients":{let s;if(o!==-1?s=n.slice(o+1):s=t[++r],s===void 0||s==="")throw new Error("--clients needs a value.");if(s==="detected"||s==="none"){e.clients=s;break}let a=s.split(",").map(u=>u.trim()).filter(Boolean),c=a.filter(u=>!lc.includes(u));if(c.length>0)throw new Error(`--clients: unknown client ${c.map(u=>`"${u}"`).join(", ")}; use ${lc.join(", ")}, detected, or none.`);e.clients=a;break}default:throw new Error(`Unknown setup option "${n}". Run screencast-mcp --help.`)}}return e}function wA(t){return t.env.APPDATA??un(t.home,"AppData","Roaming")}function My(t){let e=wA(t);return[{id:"claude-desktop",name:"Claude Desktop",path:un(e,"Claude","claude_desktop_config.json"),key:"mcpServers",entry:Bl,marker:un(e,"Claude")},{id:"cursor",name:"Cursor",path:un(t.home,".cursor","mcp.json"),key:"mcpServers",entry:Bl,marker:un(t.home,".cursor")},{id:"vscode",name:"VS Code",path:un(e,"Code","User","mcp.json"),key:"servers",entry:{type:"stdio",...Bl},marker:un(e,"Code","User")}]}function yA(t){return["mcp","add","--scope","user",ao,"--",...t==="win32"?["cmd","/c","npx","-y",Wl]:["npx","-y",Wl]]}var xA=(t,e)=>JSON.stringify(t)===JSON.stringify(e);function SA(t,e,r,n,o=!1){let i={};if(t!==null&&t.trim()!==""){let u;try{u=JSON.parse(t.charCodeAt(0)===65279?t.slice(1):t)}catch(d){return{status:"invalid",reason:`not plain JSON (${z(d)})`}}if(typeof u!="object"||u===null||Array.isArray(u))return{status:"invalid",reason:"the file is not a JSON object"};i=u}let s=i[e]??{};if(typeof s!="object"||s===null||Array.isArray(s))return{status:"invalid",reason:`"${e}" is not an object`};let a=s[r];if(a!==void 0){if(xA(a,n))return{status:"unchanged"};if(!o)return{status:"conflict",existing:a}}let c={...i,[e]:{...s,[r]:n}};return{status:"added",text:JSON.stringify(c,null,2)+`
443
+ `}}function vA(t,e){let r=t===""?[]:t.replace(/\n$/,"").split(`
443
444
  `),n=e===""?[]:e.replace(/\n$/,"").split(`
444
445
  `),o=Array.from({length:r.length+1},()=>new Array(n.length+1).fill(0));for(let c=r.length-1;c>=0;c--)for(let u=n.length-1;u>=0;u--)o[c][u]=r[c]===n[u]?o[c+1][u+1]+1:Math.max(o[c+1][u],o[c][u+1]);let i=[],s=0,a=0;for(;s<r.length||a<n.length;)s<r.length&&a<n.length&&r[s]===n[a]?(i.push(` ${r[s]}`),s++,a++):a<n.length&&(s>=r.length||o[s][a+1]>=o[s+1][a])?(i.push(`+ ${n[a]}`),a++):(i.push(`- ${r[s]}`),s++);return i.join(`
445
446
  `)+`
446
- `}function pR(t,e){let r=o=>String(o).padStart(2,"0"),n=`${e.getFullYear()}${r(e.getMonth()+1)}${r(e.getDate())}-${r(e.getHours())}${r(e.getMinutes())}${r(e.getSeconds())}`;return`${t}.bak-${n}`}function dR(t,e,r){let n=[],o=Number((t.server?.node??process.version).replace(/^v/,"").split(".")[0]);n.push({state:o>=22?"ok":"fail",text:`Node.js ${t.server?.node??process.version}${o>=22?"":" (needs 22+)"}`});let i=t.ffmpeg??{};i.found?i.meetsFfmpeg8===!1?n.push({state:"warn",text:`FFmpeg ${i.version??"?"}: works, but transcribe and backend "wgc" need FFmpeg 8+`}):n.push({state:"ok",text:`FFmpeg ${i.version??"?"}${i.path?` (${i.path})`:""}`}):n.push({state:"fail",text:"FFmpeg not found on PATH (or FFMPEG_PATH)"}),n.push(t.ffprobe?.found?{state:"ok",text:`ffprobe ${t.ffprobe.version??""}`.trim()}:{state:"fail",text:"ffprobe not found"}),r==="win32"?(n.push({state:t.devices?.gdigrab?"ok":"fail",text:t.devices?.gdigrab?"Screen capture (gdigrab)":"No gdigrab: this ffmpeg cannot capture the screen"}),n.push({state:t.wgc?.available?"ok":"info",text:t.wgc?.available?"Windows Graphics Capture (backend wgc)":'Windows Graphics Capture unavailable (backend "wgc" needs FFmpeg 8)'}),n.push(t.ocr?.available?{state:"ok",text:`Windows OCR${t.ocr.language?` (${t.ocr.language})`:""}`}:{state:"warn",text:"Windows OCR unavailable: find_text cannot read the screen (add an OCR language in Settings > Time & language > Language)"}),t.tts&&n.push(t.tts.available?{state:"ok",text:"Windows speech (narrate)"}:{state:"warn",text:"No Windows voice: narrate cannot speak"})):n.push({state:"warn",text:"Not Windows: capture and OCR are unavailable; the edit and watch tools work"});let s=t.env?.SCREENCAST_WHISPER_MODEL??e.SCREENCAST_WHISPER_MODEL;return n.push(s?{state:"ok",text:`Whisper model: ${s}`}:{state:"info",text:"transcribe needs a Whisper model: download a ggml model and set SCREENCAST_WHISPER_MODEL to its path"}),n}var mR={ok:"[ok] ",warn:"[warn]",fail:"[fail]",info:"[info]"};async function fR(t,e,r){let{fs:n}=r,o=n.exists(t.path),i=null;if(o)try{i=n.readFile(t.path)}catch(a){return r.out(` ${t.name}: could not read ${t.path}: ${U(a)}
447
- `),!1}let s=uR(i,t.key,io,t.entry,e.force);switch(s.status){case"unchanged":return r.out(` ${t.name}: already configured (${t.path})
447
+ `}function $A(t,e){let r=o=>String(o).padStart(2,"0"),n=`${e.getFullYear()}${r(e.getMonth()+1)}${r(e.getDate())}-${r(e.getHours())}${r(e.getMinutes())}${r(e.getSeconds())}`;return`${t}.bak-${n}`}function kA(t,e,r){let n=[],o=Number((t.server?.node??process.version).replace(/^v/,"").split(".")[0]);n.push({state:o>=22?"ok":"fail",text:`Node.js ${t.server?.node??process.version}${o>=22?"":" (needs 22+)"}`});let i=t.ffmpeg??{};i.found?i.meetsFfmpeg8===!1?n.push({state:"warn",text:`FFmpeg ${i.version??"?"}: works, but transcribe and backend "wgc" need FFmpeg 8+`}):n.push({state:"ok",text:`FFmpeg ${i.version??"?"}${i.path?` (${i.path})`:""}`}):n.push({state:"fail",text:"FFmpeg not found on PATH (or FFMPEG_PATH)"}),n.push(t.ffprobe?.found?{state:"ok",text:`ffprobe ${t.ffprobe.version??""}`.trim()}:{state:"fail",text:"ffprobe not found"}),r==="win32"?(n.push({state:t.devices?.gdigrab?"ok":"fail",text:t.devices?.gdigrab?"Screen capture (gdigrab)":"No gdigrab: this ffmpeg cannot capture the screen"}),n.push({state:t.wgc?.available?"ok":"info",text:t.wgc?.available?"Windows Graphics Capture (backend wgc)":'Windows Graphics Capture unavailable (backend "wgc" needs FFmpeg 8)'}),n.push(t.ocr?.available?{state:"ok",text:`Windows OCR${t.ocr.language?` (${t.ocr.language})`:""}`}:{state:"warn",text:"Windows OCR unavailable: find_text cannot read the screen (add an OCR language in Settings > Time & language > Language)"}),t.tts&&n.push(t.tts.available?{state:"ok",text:"Windows speech (narrate)"}:{state:"warn",text:"No Windows voice: narrate cannot speak"})):n.push({state:"warn",text:"Not Windows: capture and OCR are unavailable; the edit and watch tools work"});let s=t.env?.SCREENCAST_WHISPER_MODEL??e.SCREENCAST_WHISPER_MODEL;return n.push(s?{state:"ok",text:`Whisper model: ${s}`}:{state:"info",text:"transcribe needs a Whisper model: download a ggml model and set SCREENCAST_WHISPER_MODEL to its path"}),n}var EA={ok:"[ok] ",warn:"[warn]",fail:"[fail]",info:"[info]"};async function _A(t,e,r){let{fs:n}=r,o=n.exists(t.path),i=null;if(o)try{i=n.readFile(t.path)}catch(a){return r.out(` ${t.name}: could not read ${t.path}: ${z(a)}
448
+ `),!1}let s=SA(i,t.key,ao,t.entry,e.force);switch(s.status){case"unchanged":return r.out(` ${t.name}: already configured (${t.path})
448
449
  `),!0;case"invalid":return r.out(` ${t.name}: left ${t.path} alone: ${s.reason}. Add the server by hand (see docs/connect.html).
449
- `),!1;case"conflict":return r.out(` ${t.name}: ${t.path} already has a different "${io}" entry; kept it (pass --force to replace).
450
+ `),!1;case"conflict":return r.out(` ${t.name}: ${t.path} already has a different "${ao}" entry; kept it (pass --force to replace).
450
451
  `),!1}if(e.dryRun)return r.out(` ${t.name}: would ${o?"update":"create"} ${t.path}:
451
- `),r.out(lR(i??"",s.text).replace(/^/gm," ")),!0;if(!e.yes&&!await r.confirm(`Add the screencast server to ${t.name} (${t.path})?`))return r.out(` ${t.name}: skipped (run with --yes to write it, or --dry-run to see the change).
452
- `),!1;try{let a=null;return o?(a=pR(t.path,r.now()),n.copyFile(t.path,a)):n.mkdir(oR(t.path)),n.writeFile(t.path,s.text),r.out(` ${t.name}: ${o?"updated":"created"} ${t.path}${a?` (backup: ${a})`:""}. Restart it to load the server.
453
- `),!0}catch(a){return r.out(` ${t.name}: could not write ${t.path}: ${U(a)}
454
- `),!1}}async function hR(t,e){let r=aR(e.platform);if((await e.exec("claude",["mcp","get",io])).code===0)return e.out(` Claude Code: already has a "${io}" server (claude mcp get ${io}).
452
+ `),r.out(vA(i??"",s.text).replace(/^/gm," ")),!0;if(!e.yes&&!await r.confirm(`Add the screencast server to ${t.name} (${t.path})?`))return r.out(` ${t.name}: skipped (run with --yes to write it, or --dry-run to see the change).
453
+ `),!1;try{let a=null;return o?(a=$A(t.path,r.now()),n.copyFile(t.path,a)):n.mkdir(gA(t.path)),n.writeFile(t.path,s.text),r.out(` ${t.name}: ${o?"updated":"created"} ${t.path}${a?` (backup: ${a})`:""}. Restart it to load the server.
454
+ `),!0}catch(a){return r.out(` ${t.name}: could not write ${t.path}: ${z(a)}
455
+ `),!1}}async function TA(t,e){let r=yA(e.platform);if((await e.exec("claude",["mcp","get",ao])).code===0)return e.out(` Claude Code: already has a "${ao}" server (claude mcp get ${ao}).
455
456
  `),!0;if(t.dryRun)return e.out(` Claude Code: would run: claude ${r.join(" ")}
456
457
  `),!0;if(!t.yes&&!await e.confirm("Add the screencast server to Claude Code (user scope)?"))return e.out(` Claude Code: skipped. To add it yourself: claude ${r.join(" ")}
457
458
  `),!1;let o=await e.exec("claude",r);return o.code!==0?(e.out(` Claude Code: claude mcp add failed (${(o.stderr||o.stdout).trim()||`exit ${o.code}`}).
458
459
  `),!1):(e.out(` Claude Code: added (user scope). Check it with claude mcp list.
459
- `),!0)}async function gR(t){let e=[];for(let n of yy(t))t.fs.exists(n.marker)&&e.push(n.id);return(await t.exec("claude",["--version"]).catch(()=>({code:1,stdout:"",stderr:""}))).code===0&&e.push("claude-code"),uc.filter(n=>e.includes(n))}async function xy(t,e){let r=e.out;r(`screencast-mcp setup${t.dryRun?" (dry run: nothing is installed or written)":""}
460
+ `),!0)}async function RA(t){let e=[];for(let n of My(t))t.fs.exists(n.marker)&&e.push(n.id);return(await t.exec("claude",["--version"]).catch(()=>({code:1,stdout:"",stderr:""}))).code===0&&e.push("claude-code"),lc.filter(n=>e.includes(n))}async function Cy(t,e){let r=e.out;r(`screencast-mcp setup${t.dryRun?" (dry run: nothing is installed or written)":""}
460
461
 
461
- `);let n;try{n=await e.doctor()}catch(c){return e.err(`screencast-mcp: the doctor checks failed to run: ${U(c)}
462
- `),1}for(let c of dR(n,e.env,e.platform))r(`${mR[c.state]} ${c.text}
462
+ `);let n;try{n=await e.doctor()}catch(c){return e.err(`screencast-mcp: the doctor checks failed to run: ${z(c)}
463
+ `),1}for(let c of kA(n,e.env,e.platform))r(`${EA[c.state]} ${c.text}
463
464
  `);let o=n.problems??[];if(o.length>0){r(`
464
465
  What doctor says to fix:
465
466
  `);for(let c of o)r(` - ${c}
466
- `)}let i=n.ffmpeg??{};if((!i.found||i.meetsFfmpeg8===!1)&&t.install&&e.platform==="win32"){let c=`winget ${hy.join(" ")}`;if(r(`
467
+ `)}let i=n.ffmpeg??{};if((!i.found||i.meetsFfmpeg8===!1)&&t.install&&e.platform==="win32"){let c=`winget ${_y.join(" ")}`;if(r(`
467
468
  FFmpeg 8 ${i.found?"is not installed (found an older one)":"is missing"}.
468
469
  `),t.dryRun)r(` would run: ${c}
469
470
  `);else if(t.yes||await e.confirm("Install FFmpeg 8 with winget now?")){r(` running: ${c}
470
- `);let u=await e.exec("winget",hy).catch(d=>({code:1,stdout:"",stderr:U(d)}));u.code===0?r(` FFmpeg installed. Open a new terminal so PATH picks it up, then run setup again.
471
+ `);let u=await e.exec("winget",_y).catch(d=>({code:1,stdout:"",stderr:z(d)}));u.code===0?r(` FFmpeg installed. Open a new terminal so PATH picks it up, then run setup again.
471
472
  `):r(` winget failed (${(u.stderr||u.stdout).trim().split(`
472
473
  `).pop()||`exit ${u.code}`}). Install it yourself: ${c}
473
474
  `)}else r(` skipped. Install it yourself: ${c}
474
- `)}if(t.clients!=="none"){let c=t.clients==="detected"?await gR(e):t.clients;r(`
475
+ `)}if(t.clients!=="none"){let c=t.clients==="detected"?await RA(e):t.clients;r(`
475
476
  MCP clients:
476
477
  `),c.length===0&&r(` none found (Claude Desktop, Claude Code, Cursor, VS Code). Name one with --clients, or see docs/connect.html.
477
- `);let u=new Map(yy(e).map(d=>[d.id,d]));for(let d of c){let p=u.get(d);p?await fR(p,t,e):await hR(t,e)}}if(t.test)if(r(`
478
+ `);let u=new Map(My(e).map(d=>[d.id,d]));for(let d of c){let p=u.get(d);p?await _A(p,t,e):await TA(t,e)}}if(t.test)if(r(`
478
479
  Test clip:
479
480
  `),t.dryRun)r(` would record 3 s of the screen and export a GIF.
480
481
  `);else try{let c=await e.testClip();r(` recorded 3 s and exported ${c}
481
- `),await e.open(c).catch(()=>{})}catch(c){return r(` the test clip failed: ${U(c)}
482
+ `),await e.open(c).catch(()=>{})}catch(c){return r(` the test clip failed: ${z(c)}
482
483
  `),1}let a=n.ok??o.length===0;return r(a?`
483
484
  All checks passed.
484
485
  `:`
485
486
  Some checks need attention (above). Run setup again after fixing them.
486
- `),a?0:1}function bR(t){return(e,r)=>new Promise(n=>{let o=gy(e,r,{shell:t==="win32",windowsHide:!0}),i="",s="";o.stdout?.on("data",a=>i+=a.toString()),o.stderr?.on("data",a=>s+=a.toString()),o.on("error",a=>n({code:127,stdout:i,stderr:a.message})),o.on("close",a=>n({code:a??1,stdout:i,stderr:s}))})}var wR={exists:t=>ZA(t),readFile:t=>tR(t,"utf8"),writeFile:(t,e)=>rR(t,e),mkdir:t=>{eR(t,{recursive:!0})},copyFile:(t,e)=>QA(t,e)};function Sy(t){let e=process.platform,r=bR(e),n=async i=>{let s=await t.connect();try{return await i(s)}finally{await s.close()}},o=async(i,s,a)=>{let c=await i.call(s,a);if(c.isError)throw new Error(`${s}: ${c.text}`);return c.structured??{}};return{out:t.io.out,err:t.io.err,env:process.env,platform:e,home:nR(),fs:wR,exec:r,doctor:()=>n(async i=>await o(i,"doctor",{})),confirm:async i=>{if(!process.stdin.isTTY||!process.stdout.isTTY)return!1;let s=iR({input:process.stdin,output:process.stdout});try{return/^y(es)?$/i.test((await s.question(`${i} [y/N] `)).trim())}finally{s.close()}},testClip:()=>n(async i=>{let s=await o(i,"start_recording",{target:"full",fps:15,maxDurationSec:30});await new Promise(u=>setTimeout(u,3e3));let a=await o(i,"stop_recording",{sessionId:String(s.sessionId)}),c=await o(i,"export_gif",{input:String(a.outputPath)});return String(c.outputPath)}),open:async i=>{e!=="win32"||!process.stdout.isTTY||gy("explorer.exe",[i],{detached:!0,stdio:"ignore"}).unref()},now:()=>new Date}}var Ey=wt(),Ie=class extends Error{},_R=new Set(["record","call","setup","help","--help","-h","--version","-v"]);function _y(t){return t.length>0&&_R.has(t[0]??"")}var TR=`screencast-mcp: an MCP server for Windows screen recording.
487
+ `),a?0:1}function AA(t){return(e,r)=>new Promise(n=>{let o=Ty(e,r,{shell:t==="win32",windowsHide:!0}),i="",s="";o.stdout?.on("data",a=>i+=a.toString()),o.stderr?.on("data",a=>s+=a.toString()),o.on("error",a=>n({code:127,stdout:i,stderr:a.message})),o.on("close",a=>n({code:a??1,stdout:i,stderr:s}))})}var MA={exists:t=>pA(t),readFile:t=>mA(t,"utf8"),writeFile:(t,e)=>fA(t,e),mkdir:t=>{dA(t,{recursive:!0})},copyFile:(t,e)=>lA(t,e)};function Py(t){let e=process.platform,r=AA(e),n=async i=>{let s=await t.connect();try{return await i(s)}finally{await s.close()}},o=async(i,s,a)=>{let c=await i.call(s,a);if(c.isError)throw new Error(`${s}: ${c.text}`);return c.structured??{}};return{out:t.io.out,err:t.io.err,env:process.env,platform:e,home:hA(),fs:MA,exec:r,doctor:()=>n(async i=>await o(i,"doctor",{})),confirm:async i=>{if(!process.stdin.isTTY||!process.stdout.isTTY)return!1;let s=bA({input:process.stdin,output:process.stdout});try{return/^y(es)?$/i.test((await s.question(`${i} [y/N] `)).trim())}finally{s.close()}},testClip:()=>n(async i=>{let s=await o(i,"start_recording",{target:"full",fps:15,maxDurationSec:30});await new Promise(u=>setTimeout(u,3e3));let a=await o(i,"stop_recording",{sessionId:String(s.sessionId)}),c=await o(i,"export_gif",{input:String(a.outputPath)});return String(c.outputPath)}),open:async i=>{e!=="win32"||!process.stdout.isTTY||Ty("explorer.exe",[i],{detached:!0,stdio:"ignore"}).unref()},now:()=>new Date}}var Ny=xt(),Oe=class extends Error{},LA=new Set(["record","call","setup","help","--help","-h","--version","-v"]);function Dy(t){return t.length>0&&LA.has(t[0]??"")}var BA=`screencast-mcp: an MCP server for Windows screen recording.
487
488
 
488
489
  Usage:
489
490
  screencast-mcp run the MCP server over stdio (default)
@@ -508,37 +509,40 @@ record options:
508
509
  --redact-secrets OCR the recording and blur on-screen secrets (API keys, tokens,
509
510
  password: values) in the GIF and contact sheet (Windows OCR)
510
511
  --secret-pattern <re> with --redact-secrets, the regex to blur instead of the default
511
- --max-duration <sec> stop recording after <sec> seconds, an integer 0-${Ct}
512
+ --max-duration <sec> stop recording after <sec> seconds, an integer 0-${It}
512
513
  (0 = no cap; default SCREENCAST_MAX_RECORDING_SEC, else 3600)
514
+ --events also log clicks, scrolls and typing bursts to recording.events.jsonl
515
+ --perf also sample CPU and memory to recording.perf.jsonl
516
+ --log <path> follow an app log into recording.logs.jsonl (repeatable)
513
517
  --command-env <NAME> run the command line in environment variable NAME instead of
514
518
  the arguments after --, so quotes and & survive any shell
515
519
 
516
520
  record exits with the command's exit code and writes <out>/evidence.json.
517
521
 
518
- ${by}`;function AR(t,e,r){let n=t[e+1];if(n===void 0||n==="--")throw new Ie(`${r} needs a value.`);return n}function Wl(t,e,r,n=1/0,o=!1){let i=Number(t);if(t.trim()===""||!Number.isFinite(i)||i<r||i>n||o&&!Number.isInteger(i)){let s=n===1/0?`>= ${r}`:`${r}-${n}`;throw new Ie(`${e} must be ${o?"an integer":"a number"} ${s}, got "${t}".`)}return i}function RR(t,e){let r=t.indexOf("--"),n={target:"full",fps:15,outDir:"screencast-evidence",artifacts:"failure",lastSec:30,gif:!0,contactSheet:!0,discardOnSuccess:!1,ocrErrors:!1,redactSecrets:!1,command:r===-1?[]:t.slice(r+1)},o,i=r===-1?t:t.slice(0,r);for(let s=0;s<i.length;s++){let a=i[s]??"",c=a.startsWith("--")?a.indexOf("="):-1,u=c===-1?a:a.slice(0,c),d=c===-1?void 0:a.slice(c+1),p=()=>{if(d!==void 0)return d;let f=AR(i,s,u);return s++,f};switch(u){case"--target":n.target=p();break;case"--fps":n.fps=Wl(p(),u,1,120,!0);break;case"--out":n.outDir=p();break;case"--artifacts":{let f=p();if(f!=="failure"&&f!=="always"&&f!=="never")throw new Ie(`--artifacts must be failure, always, or never, got "${f}".`);n.artifacts=f;break}case"--last":n.lastSec=Wl(p(),u,0);break;case"--max-duration":n.maxDurationSec=Wl(p(),u,0,Ct,!0);break;case"--command-env":o=p();break;case"--no-gif":n.gif=!1;break;case"--no-contact-sheet":n.contactSheet=!1;break;case"--discard-on-success":n.discardOnSuccess=!0;break;case"--redact-secrets":n.redactSecrets=!0;break;case"--secret-pattern":n.secretPattern=p();break;case"--ocr-errors":n.ocrErrors=!0;break;default:throw new Ie(`Unknown record option "${a}". Run screencast-mcp --help.`)}}if(o!==void 0){if(n.command.length>0)throw new Ie("Give the command either after -- or with --command-env, not both.");let s=e[o];if(s===void 0||s.trim()==="")throw new Ie(`--command-env ${o}: the environment variable is unset or empty.`);n.command=[s]}else if(n.command.length===0)throw new Ie("record needs a command after -- (or --command-env NAME), e.g. screencast-mcp record -- npm test");return n}function MR(t,e=process.env){let[r,...n]=t;switch(r){case"help":case"--help":case"-h":return{kind:"help"};case"--version":case"-v":return{kind:"version"};case"record":return n[0]==="--help"||n[0]==="-h"?{kind:"help"}:{kind:"record",options:RR(n,e)};case"call":{let[o,i,s]=n;if(!o||o.startsWith("-"))throw new Ie("call needs a tool name, e.g. screencast-mcp call doctor");if(s!==void 0)throw new Ie("call takes one JSON argument; quote it as a single string.");return{kind:"call",tool:o,args:i}}case"setup":{if(n[0]==="--help"||n[0]==="-h")return{kind:"help"};try{return{kind:"setup",options:wy(n)}}catch(o){throw new Ie(U(o))}}default:throw new Ie(`Unknown command "${r??""}". Run screencast-mcp --help.`)}}var vy=/([()\][%!^"`<>&|;, *?])/g,CR=/(\.(cmd|bat)$)|^(npm|npx|pnpm|yarn|corepack)$/i;function $y(t){return`"${t.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}var Ul=/[\s"&|<>^()!;'`$*?%,[\]]/;function PR(t,e=process.platform){if(t.length===1)return t[0]??"";if(e!=="win32")return t.map(n=>/^[\w@%+=:,./-]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`).join(" ");let r=CR.test(t[0]??"");return t.map((n,o)=>{if(o===0)return n!==""&&Ul.test(n)?$y(n):n;if(!Ul.test(n)&&n!=="")return n;let i=$y(n).replace(vy,"^$1");return r&&(i=i.replace(vy,"^$1")),i}).join(" ")}function IR(t){return t.length===1?t[0]??"":t.map(e=>Ul.test(e)||e===""?`"${e.replace(/"/g,'\\"')}"`:e).join(" ")}function Ty(t,e){return!e||t===null||t<=e?{}:{start:Math.round((t-e)*1e3)/1e3,duration:e}}function FR(t){let e=[...t].sort((o,i)=>(Number(i.t)||0)-(Number(o.t)||0)),r=new Set,n=[];for(let o of e){let i=String(o.line??o.text??"").trim(),s=i.toLowerCase().replace(/\s+/g," ");if(!(!i||r.has(s))&&(r.add(s),n.push(i),n.length>=Iu))break}return Oe(n,Ge)}function OR(t,e=r=>SR(r,"utf8")){if(t===void 0||t.trim()==="")return{};let r=t.startsWith("@")?e(t.slice(1)):t,n;try{n=JSON.parse(r)}catch(o){throw new Ie(`Tool arguments are not valid JSON: ${U(o)}`)}if(typeof n!="object"||n===null||Array.isArray(n))throw new Ie("Tool arguments must be a JSON object.");return n}async function zl(){let[t,e]=ER.createLinkedPair();await cc({toolsets:"all"}).connect(e);let r=new kR({name:"screencast-mcp-cli",version:Ey});return await r.connect(t),{async call(n,o){let i=await r.callTool({name:n,arguments:o}),s=i.content.map(a=>a.type==="text"?a.text??"":`[${a.type} omitted]`).join(`
519
- `);return{isError:i.isError===!0,text:s,structured:i.structuredContent}},close:()=>r.close()}}async function Ar(t,e,r){let n=await t.call(e,r);if(n.isError)throw new Error(`${e}: ${n.text}`);return n.structured??{}}var Ay={out:t=>process.stdout.write(t),err:t=>process.stderr.write(t)};function NR(t){return new Promise(e=>{let r=yR(PR(t),{shell:!0,stdio:"inherit"}),n=a=>()=>r.kill(a),o=n("SIGINT"),i=n("SIGTERM");process.on("SIGINT",o),process.on("SIGTERM",i);let s=a=>{process.off("SIGINT",o),process.off("SIGTERM",i),e(a)};r.on("error",a=>{process.stderr.write(`screencast-mcp: could not run the command: ${a.message}
520
- `),s(127)}),r.on("exit",(a,c)=>s(a??(c?1:0)))})}function DR(t,e,r){if(t===null)return null;let n=r===null?"":` at ${r} s`,o="so the GIF and contact sheet show the end of the recording, not the end of the run.";return e==="max_duration"?`the recording hit its max-duration cap${n} before the command finished, ${o} Raise --max-duration (0 = no cap).`:t==="failed"||e==="crashed"?`the recording failed${n} before the command finished (endReason ${e??"unknown"}), ${o}`:e==="window_closed"?`the recorded window closed${n} before the command finished, ${o}`:e!==null&&e!=="stopped"?`the recording ended early${n} (endReason ${e}), ${o}`:null}var LR={connect:zl,run:NR,now:()=>Date.now()};async function BR(t,e=Ay,r=LR){let n=$R(t.outDir);xR(n,{recursive:!0});let o={command:IR(t.command),exitCode:0,target:t.target,recording:null,durationSec:null,commandSec:0,status:null,endReason:null,gif:null,contactSheet:null,errors:null,warnings:[]},i=a=>{o.warnings.push(a),e.err(`screencast-mcp: ${a}
521
- `)},s=await r.connect();try{let a=null;try{let p=await Ar(s,"start_recording",{target:t.target,fps:t.fps,output:so(n,"recording.mp4"),overwrite:!0,...t.maxDurationSec!==void 0?{maxDurationSec:t.maxDurationSec}:{}});a=String(p.sessionId),e.err(`screencast-mcp: recording ${t.target} to ${String(p.outputPath)}
522
- `)}catch(p){i(`recording did not start, running the command without it: ${U(p)}`)}let c=r.now();if(o.exitCode=await r.run(t.command),o.commandSec=Math.round(r.now()-c)/1e3,a)try{let p=await Ar(s,"stop_recording",{sessionId:a});o.recording=String(p.outputPath),o.durationSec=typeof p.durationSec=="number"?p.durationSec:null,o.status=typeof p.status=="string"?p.status:null,o.endReason=typeof p.endReason=="string"?p.endReason:o.status==="stopped"?"stopped":null;let f=DR(o.status,o.endReason,o.durationSec);f&&i(f)}catch(p){i(`stop_recording failed: ${U(p)}`)}let u=o.exitCode!==0,d=t.artifacts==="always"||t.artifacts==="failure"&&u;if(o.recording&&d){let p=o.recording,f=null;if(t.redactSecrets)try{let m=await WR(s,o.recording,o.durationSec,t.secretPattern,n,i);o.redactions=m?.regions??0,f=m?.path??null,f&&(p=f)}catch(m){i(`secret scan failed, so the GIF and contact sheet were skipped: ${U(m)}`),p=null}if(p&&t.gif)try{let m=await Ar(s,"export_gif",{input:p,...Ty(o.durationSec,t.lastSec),output:so(n,"evidence.gif"),overwrite:!0});o.gif=String(m.outputPath)}catch(m){i(`export_gif failed: ${U(m)}`)}if(p&&t.contactSheet)try{let m=await Ar(s,"contact_sheet",{input:p,output:so(n,"contact-sheet.png"),overwrite:!0,returnImage:!1});o.contactSheet=String(m.outputPath)}catch(m){i(`contact_sheet failed: ${U(m)}`)}f&&jl(f,{force:!0})}o.recording&&u&&t.ocrErrors&&(o.errors=await jR(s,o.recording,o.durationSec,t.lastSec,n,i)),!u&&t.discardOnSuccess&&o.recording&&(jl(o.recording,{force:!0}),o.recording=null)}finally{await s.close()}return vR(so(n,"evidence.json"),JSON.stringify(o,null,2)+`
522
+ ${Ry}`;function WA(t,e,r){let n=t[e+1];if(n===void 0||n==="--")throw new Oe(`${r} needs a value.`);return n}function jl(t,e,r,n=1/0,o=!1){let i=Number(t);if(t.trim()===""||!Number.isFinite(i)||i<r||i>n||o&&!Number.isInteger(i)){let s=n===1/0?`>= ${r}`:`${r}-${n}`;throw new Oe(`${e} must be ${o?"an integer":"a number"} ${s}, got "${t}".`)}return i}function jA(t,e){let r=t.indexOf("--"),n={target:"full",fps:15,outDir:"screencast-evidence",artifacts:"failure",lastSec:30,gif:!0,contactSheet:!0,discardOnSuccess:!1,ocrErrors:!1,redactSecrets:!1,command:r===-1?[]:t.slice(r+1)},o,i=r===-1?t:t.slice(0,r);for(let s=0;s<i.length;s++){let a=i[s]??"",c=a.startsWith("--")?a.indexOf("="):-1,u=c===-1?a:a.slice(0,c),d=c===-1?void 0:a.slice(c+1),p=()=>{if(d!==void 0)return d;let f=WA(i,s,u);return s++,f};switch(u){case"--target":n.target=p();break;case"--fps":n.fps=jl(p(),u,1,120,!0);break;case"--out":n.outDir=p();break;case"--artifacts":{let f=p();if(f!=="failure"&&f!=="always"&&f!=="never")throw new Oe(`--artifacts must be failure, always, or never, got "${f}".`);n.artifacts=f;break}case"--last":n.lastSec=jl(p(),u,0);break;case"--max-duration":n.maxDurationSec=jl(p(),u,0,It,!0);break;case"--command-env":o=p();break;case"--no-gif":n.gif=!1;break;case"--no-contact-sheet":n.contactSheet=!1;break;case"--discard-on-success":n.discardOnSuccess=!0;break;case"--redact-secrets":n.redactSecrets=!0;break;case"--secret-pattern":n.secretPattern=p();break;case"--ocr-errors":n.ocrErrors=!0;break;case"--events":n.events=!0;break;case"--perf":n.perf=!0;break;case"--log":n.logs=[...n.logs??[],p()];break;default:throw new Oe(`Unknown record option "${a}". Run screencast-mcp --help.`)}}if(o!==void 0){if(n.command.length>0)throw new Oe("Give the command either after -- or with --command-env, not both.");let s=e[o];if(s===void 0||s.trim()==="")throw new Oe(`--command-env ${o}: the environment variable is unset or empty.`);n.command=[s]}else if(n.command.length===0)throw new Oe("record needs a command after -- (or --command-env NAME), e.g. screencast-mcp record -- npm test");return n}function UA(t,e=process.env){let[r,...n]=t;switch(r){case"help":case"--help":case"-h":return{kind:"help"};case"--version":case"-v":return{kind:"version"};case"record":return n[0]==="--help"||n[0]==="-h"?{kind:"help"}:{kind:"record",options:jA(n,e)};case"call":{let[o,i,s]=n;if(!o||o.startsWith("-"))throw new Oe("call needs a tool name, e.g. screencast-mcp call doctor");if(s!==void 0)throw new Oe("call takes one JSON argument; quote it as a single string.");return{kind:"call",tool:o,args:i}}case"setup":{if(n[0]==="--help"||n[0]==="-h")return{kind:"help"};try{return{kind:"setup",options:Ay(n)}}catch(o){throw new Oe(z(o))}}default:throw new Oe(`Unknown command "${r??""}". Run screencast-mcp --help.`)}}var Iy=/([()\][%!^"`<>&|;, *?])/g,zA=/(\.(cmd|bat)$)|^(npm|npx|pnpm|yarn|corepack)$/i;function Fy(t){return`"${t.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}var zl=/[\s"&|<>^()!;'`$*?%,[\]]/;function HA(t,e=process.platform){if(t.length===1)return t[0]??"";if(e!=="win32")return t.map(n=>/^[\w@%+=:,./-]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`).join(" ");let r=zA.test(t[0]??"");return t.map((n,o)=>{if(o===0)return n!==""&&zl.test(n)?Fy(n):n;if(!zl.test(n)&&n!=="")return n;let i=Fy(n).replace(Iy,"^$1");return r&&(i=i.replace(Iy,"^$1")),i}).join(" ")}function GA(t){return t.length===1?t[0]??"":t.map(e=>zl.test(e)||e===""?`"${e.replace(/"/g,'\\"')}"`:e).join(" ")}function Ly(t,e){return!e||t===null||t<=e?{}:{start:Math.round((t-e)*1e3)/1e3,duration:e}}function qA(t){let e=[...t].sort((o,i)=>(Number(i.t)||0)-(Number(o.t)||0)),r=new Set,n=[];for(let o of e){let i=String(o.line??o.text??"").trim(),s=i.toLowerCase().replace(/\s+/g," ");if(!(!i||r.has(s))&&(r.add(s),n.push(i),n.length>=Fu))break}return Le(n,De)}function XA(t,e=r=>IA(r,"utf8")){if(t===void 0||t.trim()==="")return{};let r=t.startsWith("@")?e(t.slice(1)):t,n;try{n=JSON.parse(r)}catch(o){throw new Oe(`Tool arguments are not valid JSON: ${z(o)}`)}if(typeof n!="object"||n===null||Array.isArray(n))throw new Oe("Tool arguments must be a JSON object.");return n}async function Hl(){let[t,e]=DA.createLinkedPair();await uc({toolsets:"all"}).connect(e);let r=new NA({name:"screencast-mcp-cli",version:Ny});return await r.connect(t),{async call(n,o){let i=await r.callTool({name:n,arguments:o}),s=i.content.map(a=>a.type==="text"?a.text??"":`[${a.type} omitted]`).join(`
523
+ `);return{isError:i.isError===!0,text:s,structured:i.structuredContent}},close:()=>r.close()}}async function Ir(t,e,r){let n=await t.call(e,r);if(n.isError)throw new Error(`${e}: ${n.text}`);return n.structured??{}}var By={out:t=>process.stdout.write(t),err:t=>process.stderr.write(t)};function JA(t){return new Promise(e=>{let r=CA(HA(t),{shell:!0,stdio:"inherit"}),n=a=>()=>r.kill(a),o=n("SIGINT"),i=n("SIGTERM");process.on("SIGINT",o),process.on("SIGTERM",i);let s=a=>{process.off("SIGINT",o),process.off("SIGTERM",i),e(a)};r.on("error",a=>{process.stderr.write(`screencast-mcp: could not run the command: ${a.message}
524
+ `),s(127)}),r.on("exit",(a,c)=>s(a??(c?1:0)))})}function YA(t,e,r){if(t===null)return null;let n=r===null?"":` at ${r} s`,o="so the GIF and contact sheet show the end of the recording, not the end of the run.";return e==="max_duration"?`the recording hit its max-duration cap${n} before the command finished, ${o} Raise --max-duration (0 = no cap).`:t==="failed"||e==="crashed"?`the recording failed${n} before the command finished (endReason ${e??"unknown"}), ${o}`:e==="window_closed"?`the recorded window closed${n} before the command finished, ${o}`:e!==null&&e!=="stopped"?`the recording ended early${n} (endReason ${e}), ${o}`:null}var KA={connect:Hl,run:JA,now:()=>Date.now()};async function VA(t,e=By,r=KA){let n=OA(t.outDir);PA(n,{recursive:!0});let o={command:GA(t.command),exitCode:0,target:t.target,recording:null,durationSec:null,commandSec:0,status:null,endReason:null,gif:null,contactSheet:null,errors:null,warnings:[]},i=a=>{o.warnings.push(a),e.err(`screencast-mcp: ${a}
525
+ `)},s=await r.connect();try{let a=null;try{let p=await Ir(s,"start_recording",{target:t.target,fps:t.fps,output:co(n,"recording.mp4"),overwrite:!0,...t.maxDurationSec!==void 0?{maxDurationSec:t.maxDurationSec}:{},...t.events?{events:!0}:{},...t.perf?{perf:!0}:{},...t.logs?.length?{logs:t.logs.map(f=>({path:f}))}:{}});a=String(p.sessionId),e.err(`screencast-mcp: recording ${t.target} to ${String(p.outputPath)}
526
+ `)}catch(p){i(`recording did not start, running the command without it: ${z(p)}`)}let c=r.now();if(o.exitCode=await r.run(t.command),o.commandSec=Math.round(r.now()-c)/1e3,a)try{let p=await Ir(s,"stop_recording",{sessionId:a});o.recording=String(p.outputPath),o.durationSec=typeof p.durationSec=="number"?p.durationSec:null,o.status=typeof p.status=="string"?p.status:null,o.endReason=typeof p.endReason=="string"?p.endReason:o.status==="stopped"?"stopped":null;let f=YA(o.status,o.endReason,o.durationSec);f&&i(f)}catch(p){i(`stop_recording failed: ${z(p)}`)}let u=o.exitCode!==0,d=t.artifacts==="always"||t.artifacts==="failure"&&u;if(o.recording&&d){let p=o.recording,f=null;if(t.redactSecrets)try{let m=await QA(s,o.recording,o.durationSec,t.secretPattern,n,i);o.redactions=m?.regions??0,f=m?.path??null,f&&(p=f)}catch(m){i(`secret scan failed, so the GIF and contact sheet were skipped: ${z(m)}`),p=null}if(p&&t.gif)try{let m=await Ir(s,"export_gif",{input:p,...Ly(o.durationSec,t.lastSec),output:co(n,"evidence.gif"),overwrite:!0});o.gif=String(m.outputPath)}catch(m){i(`export_gif failed: ${z(m)}`)}if(p&&t.contactSheet)try{let m=await Ir(s,"contact_sheet",{input:p,output:co(n,"contact-sheet.png"),overwrite:!0,returnImage:!1});o.contactSheet=String(m.outputPath)}catch(m){i(`contact_sheet failed: ${z(m)}`)}f&&Ul(f,{force:!0})}o.recording&&u&&t.ocrErrors&&(o.errors=await ZA(s,o.recording,o.durationSec,t.lastSec,n,i)),!u&&t.discardOnSuccess&&o.recording&&(Ul(o.recording,{force:!0}),o.recording=null)}finally{await s.close()}return FA(co(n,"evidence.json"),JSON.stringify(o,null,2)+`
523
527
  `),e.err(`screencast-mcp: command exited ${o.exitCode}; evidence in ${n}`+(o.gif?` (gif: ${o.gif})`:"")+`
524
- `),o.exitCode}var ky=120;async function WR(t,e,r,n,o,i){let s=Math.max(1,Math.ceil((r??0)/ky)),a=await Ar(t,"find_text",{input:e,scanEverySec:s,maxFrames:ky,query:n??Ge,regex:!0,redact:!0,returnImage:!1}),c=Array.isArray(a.redactRegions)?a.redactRegions:[];if(c.length===0)return null;let u=await Ar(t,"redact_region",{input:e,regions:c,style:"blur",output:so(o,".redacted.mp4"),overwrite:!0});return i(`blurred ${c.length} on-screen secret region(s) in the shared files`),{path:String(u.outputPath),regions:c.length}}async function jR(t,e,r,n,o,i){let s=Ty(r,n),a=e,c=null;try{if(s.start!==void 0){let p=await Ar(t,"trim",{input:e,start:s.start,duration:s.duration,output:so(o,".ocr-tail.mp4"),overwrite:!0});c=String(p.outputPath),a=c}let u=await Ar(t,"find_text",{input:a,scanEverySec:1,maxFrames:30,query:Os,regex:!0,returnImage:!1}),d=Array.isArray(u.matches)?u.matches:[];return FR(d)}catch(u){return i(`OCR of error lines failed: ${U(u)}`),null}finally{c&&jl(c,{force:!0})}}async function UR(t,e,r){let n=OR(e),o=await zl();try{let i=await o.call(t,n);return i.isError?(r.err(`${i.text}
528
+ `),o.exitCode}var Oy=120;async function QA(t,e,r,n,o,i){let s=Math.max(1,Math.ceil((r??0)/Oy)),a=await Ir(t,"find_text",{input:e,scanEverySec:s,maxFrames:Oy,query:n??De,regex:!0,redact:!0,returnImage:!1}),c=Array.isArray(a.redactRegions)?a.redactRegions:[];if(c.length===0)return null;let u=await Ir(t,"redact_region",{input:e,regions:c,style:"blur",output:co(o,".redacted.mp4"),overwrite:!0});return i(`blurred ${c.length} on-screen secret region(s) in the shared files`),{path:String(u.outputPath),regions:c.length}}async function ZA(t,e,r,n,o,i){let s=Ly(r,n),a=e,c=null;try{if(s.start!==void 0){let p=await Ir(t,"trim",{input:e,start:s.start,duration:s.duration,output:co(o,".ocr-tail.mp4"),overwrite:!0});c=String(p.outputPath),a=c}let u=await Ir(t,"find_text",{input:a,scanEverySec:1,maxFrames:30,query:Os,regex:!0,returnImage:!1}),d=Array.isArray(u.matches)?u.matches:[];return qA(d)}catch(u){return i(`OCR of error lines failed: ${z(u)}`),null}finally{c&&Ul(c,{force:!0})}}async function eM(t,e,r){let n=XA(e),o=await Hl();try{let i=await o.call(t,n);return i.isError?(r.err(`${i.text}
525
529
  `),1):(r.out((i.structured?JSON.stringify(i.structured,null,2):i.text)+`
526
- `),0)}finally{await o.close()}}async function Ry(t,e=Ay){let r;try{r=MR(t)}catch(n){if(n instanceof Ie)return e.err(`screencast-mcp: ${n.message}
527
- `),2;throw n}switch(r.kind){case"help":return e.out(TR),0;case"version":return e.out(`${Ey}
528
- `),0;case"record":return BR(r.options,e);case"setup":return xy(r.options,Sy({connect:zl,io:e}));case"call":try{return await UR(r.tool,r.args,e)}catch(n){if(n instanceof Ie)return e.err(`screencast-mcp: ${n.message}
529
- `),2;throw n}}}import{readdir as My,rmdir as zR,stat as HR,unlink as GR}from"node:fs/promises";import{join as ao}from"node:path";var Gl="SCREENCAST_RETENTION_DAYS";function Cy(t=process.env){let e=Number(t[Gl]);return Number.isFinite(e)&&e>0?e:null}var Hl=/\.index\.json(\.\d+\.tmp)?$/;async function Py(t,e=Date.now(),r=Me()){let n=e-t*864e5,o={removed:0,bytes:0},i=async(s,a,c)=>{let u;try{u=await My(s)}catch{return}for(let d of u){let p=ao(s,d);try{let f=await HR(p);if(f.isDirectory()){if(!c)continue;await i(p,a,!0),(await My(p)).length===0&&f.mtimeMs<n&&await zR(p)}else!a(d)&&f.mtimeMs<n&&(await GR(p),o.removed++,o.bytes+=f.size)}catch{}}};return await i(ao(r,"screenshots"),()=>!1,!0),await i(ao(r,"frames"),()=>!1,!0),await i(ao(r,"recordings"),s=>!/\.events\.raw(\.stop)?$/.test(s)&&!Hl.test(s),!1),await i(ao(r,"edits"),s=>!Hl.test(s),!1),await i(ao(r,"edits","indexes"),s=>!Hl.test(s),!1),o}var Iy=1e4;async function XR(){let t=cc();JR();try{let n=re().reapOrphans();n.length>0&&process.stderr.write(`Reaped ${n.length} orphaned recording(s) on startup.
530
- `)}catch(n){process.stderr.write(`Orphan reaping skipped: ${U(n)}
531
- `)}try{let n=re().list().flatMap(i=>i.status==="recording"&&i.replay?[i.replay.dir]:[]),o=Hd(n);o>0&&process.stderr.write(`Removed ${o} leftover replay buffer(s).
532
- `)}catch(n){process.stderr.write(`Replay buffer cleanup skipped: ${U(n)}
533
- `)}let e=new qR;await t.connect(e);let r=Cy();r!==null&&Py(r).then(n=>{n.removed>0&&process.stderr.write(`Deleted ${n.removed} capture file(s) older than ${r} day(s) (${Gl}).
534
- `)},n=>{process.stderr.write(`Retention prune failed: ${U(n)}
535
- `)}),process.stdin.on("end",()=>{co("client disconnected")}),process.stdin.on("close",()=>{co("client disconnected")}),t.server.onclose=()=>{co("transport closed")};for(let n of["SIGINT","SIGTERM","SIGHUP"])process.on(n,()=>{co(n)})}function JR(){process.stdout.on("error",t=>{t.code!=="EPIPE"&&process.stderr.write(`stdout error: ${t.message}
536
- `),co("client pipe closed")}),process.on("uncaughtException",t=>{process.stderr.write(`Uncaught exception: ${t.stack??t.message}
537
- `),co("uncaught exception",1)}),process.on("unhandledRejection",t=>{process.stderr.write(`Unhandled rejection: ${t instanceof Error?t.stack??t.message:String(t)}
538
- `)})}async function co(t,e=0){if(ys())return;Hm();let r=rd();try{await qm(Iy)||process.stderr.write(`Shutdown (${t}): a start_recording call did not finish within ${Iy/1e3}s.
539
- `),of();let o=re();if(o.activeIds().length>0){let i=null;try{i=k().ffprobe}catch{}let s=await Sm(o,a=>i?se(a,{ffprobe:i}):Promise.resolve(null));process.stderr.write(`Shutdown (${t}): stopped ${s.length} recording(s).
540
- `)}}catch(o){process.stderr.write(`Shutdown cleanup failed: ${U(o)}
530
+ `),0)}finally{await o.close()}}async function Wy(t,e=By){let r;try{r=UA(t)}catch(n){if(n instanceof Oe)return e.err(`screencast-mcp: ${n.message}
531
+ `),2;throw n}switch(r.kind){case"help":return e.out(BA),0;case"version":return e.out(`${Ny}
532
+ `),0;case"record":return VA(r.options,e);case"setup":return Cy(r.options,Py({connect:Hl,io:e}));case"call":try{return await eM(r.tool,r.args,e)}catch(n){if(n instanceof Oe)return e.err(`screencast-mcp: ${n.message}
533
+ `),2;throw n}}}import{readdir as jy,rmdir as tM,stat as rM,unlink as nM}from"node:fs/promises";import{join as uo}from"node:path";var ql="SCREENCAST_RETENTION_DAYS";function Uy(t=process.env){let e=Number(t[ql]);return Number.isFinite(e)&&e>0?e:null}var Gl=/\.index\.json(\.\d+\.tmp)?$/;async function zy(t,e=Date.now(),r=Pe()){let n=e-t*864e5,o={removed:0,bytes:0},i=async(s,a,c)=>{let u;try{u=await jy(s)}catch{return}for(let d of u){let p=uo(s,d);try{let f=await rM(p);if(f.isDirectory()){if(!c)continue;await i(p,a,!0),(await jy(p)).length===0&&f.mtimeMs<n&&await tM(p)}else!a(d)&&f.mtimeMs<n&&(await nM(p),o.removed++,o.bytes+=f.size)}catch{}}};return await i(uo(r,"screenshots"),()=>!1,!0),await i(uo(r,"frames"),()=>!1,!0),await i(uo(r,"recordings"),s=>!/\.events\.raw(\.stop)?$/.test(s)&&!Gl.test(s),!1),await i(uo(r,"edits"),s=>!Gl.test(s),!1),await i(uo(r,"edits","indexes"),s=>!Gl.test(s),!1),o}var Hy=1e4;async function iM(){let t=uc();sM();try{let n=oe().reapOrphans();n.length>0&&process.stderr.write(`Reaped ${n.length} orphaned recording(s) on startup.
534
+ `)}catch(n){process.stderr.write(`Orphan reaping skipped: ${z(n)}
535
+ `)}try{let n=oe().list().flatMap(i=>i.status==="recording"&&i.replay?[i.replay.dir]:[]),o=qd(n);o>0&&process.stderr.write(`Removed ${o} leftover replay buffer(s).
536
+ `)}catch(n){process.stderr.write(`Replay buffer cleanup skipped: ${z(n)}
537
+ `)}let e=new oM;await t.connect(e);let r=Uy();r!==null&&zy(r).then(n=>{n.removed>0&&process.stderr.write(`Deleted ${n.removed} capture file(s) older than ${r} day(s) (${ql}).
538
+ `)},n=>{process.stderr.write(`Retention prune failed: ${z(n)}
539
+ `)}),process.stdin.on("end",()=>{lo("client disconnected")}),process.stdin.on("close",()=>{lo("client disconnected")}),t.server.onclose=()=>{lo("transport closed")};for(let n of["SIGINT","SIGTERM","SIGHUP"])process.on(n,()=>{lo(n)})}function sM(){process.stdout.on("error",t=>{t.code!=="EPIPE"&&process.stderr.write(`stdout error: ${t.message}
540
+ `),lo("client pipe closed")}),process.on("uncaughtException",t=>{process.stderr.write(`Uncaught exception: ${t.stack??t.message}
541
+ `),lo("uncaught exception",1)}),process.on("unhandledRejection",t=>{process.stderr.write(`Unhandled rejection: ${t instanceof Error?t.stack??t.message:String(t)}
542
+ `)})}async function lo(t,e=0){if(xs())return;qm();let r=od();try{await Jm(Hy)||process.stderr.write(`Shutdown (${t}): a start_recording call did not finish within ${Hy/1e3}s.
543
+ `),af();let o=oe();if(o.activeIds().length>0){let i=null;try{i=k().ffprobe}catch{}let s=await $m(o,a=>i?ue(a,{ffprobe:i}):Promise.resolve(null));process.stderr.write(`Shutdown (${t}): stopped ${s.length} recording(s).
544
+ `)}}catch(o){process.stderr.write(`Shutdown cleanup failed: ${z(o)}
541
545
  `)}let n=await r;n>0&&process.stderr.write(`Shutdown (${t}): cancelled ${n} edit job(s).
542
- `),process.exit(e)}var Fy=t=>{process.stderr.write(`Fatal error: ${U(t)}
543
- `),process.exit(1)},Oy=process.argv.slice(2);_y(Oy)?(process.stdout.on("error",t=>{t.code!=="EPIPE"&&process.stderr.write(`stdout error: ${t.message}
544
- `)}),Ry(Oy).then(t=>process.exit(t),Fy)):XR().catch(Fy);
546
+ `),process.exit(e)}var Gy=t=>{process.stderr.write(`Fatal error: ${z(t)}
547
+ `),process.exit(1)},qy=process.argv.slice(2);Dy(qy)?(process.stdout.on("error",t=>{t.code!=="EPIPE"&&process.stderr.write(`stdout error: ${t.message}
548
+ `)}),Wy(qy).then(t=>process.exit(t),Gy)):iM().catch(Gy);