@tmhs/screencast-mcp 0.51.1 → 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.
- package/README.md +59 -18
- package/dist/index.js +128 -137
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{StdioServerTransport as
|
|
3
|
-
`)}import{spawn as
|
|
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=
|
|
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
|
|
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 ${
|
|
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<${
|
|
65
|
-
double g=${
|
|
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)>${
|
|
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>=${
|
|
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
|
-
`,
|
|
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
|
-
`,
|
|
144
|
-
`)}function
|
|
145
|
-
${r(t)}`;return e===-1/0?n:
|
|
146
|
-
`).replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&").trim():t.trim()}var Hl=2e4;async function Vl(t,e,r={}){if(process.platform!=="win32")throw new l("The input event log is implemented for Windows only.");ac(`${t}.stop`,{force:!0});let n=Buffer.from(Cy(t,e,process.pid,r),"utf16le").toString("base64"),o=$y("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=[];Ql.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=My(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 ${Hl/1e3}s`),Hl);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(Fy(i)||`helper exited with code ${m}`))}),ep.set(o,`${t}.stop`),o}var Ql=new WeakMap;function Zl(t){return[...Ql.get(t)??[]]}var ep=new WeakMap,Gl=2e3;function hi(t){if(t.exitCode!==null||t.signalCode!==null)return Promise.resolve();let e=ep.get(t);if(e)try{Xl(e,"")}catch{e=void 0}return new Promise(r=>{let n=setTimeout(()=>t.kill(),e?Gl:0),o=setTimeout(r,Gl+5e3);t.once("exit",()=>{clearTimeout(n),clearTimeout(o),r()})}).finally(()=>{e&&ac(e,{force:!0})})}function $e(t){let e=t.replace(/\.[^./\\]+$/,"");return{raw:`${e}.events.raw`,jsonl:`${e}.events.jsonl`}}function gi(t,e=!1){if(!e){let r=[t.jsonl,t.raw].find(n=>sc(n));if(r)throw new l(`Event log already exists: ${r}. Pass overwrite: true to replace it, or choose a different output path.`);return}ac(t.raw,{force:!0})}function tp(t,e){let r=sc(t.raw)?ql(t.raw,"utf8"):"",n=lc(r,e);Xl(t.jsonl,pc(n));try{ky(t.raw)}catch{}return n}var uo=new Map;function mo(t,e){let r=uo.get(t),n=r?Promise.all([r,e]).then(()=>{}):e;uo.set(t,n),n.finally(()=>{uo.get(t)===n&&uo.delete(t)})}async function Yt(t,e=1e4){let r=uo.get(t);r&&await Promise.race([r,new Promise(n=>setTimeout(n,e))])}import{existsSync as Li,mkdirSync as Dx,renameSync as Nx,rmSync as Lx,statSync as Bx,writeFileSync as Wx}from"node:fs";import{basename as jx,dirname as Ux,extname as Kp,join as vo}from"node:path";import{spawn as zp,spawnSync as Oi}from"node:child_process";import{existsSync as dx,mkdtempSync as mx,rmSync as fx,writeFileSync as hx}from"node:fs";import{tmpdir as gx}from"node:os";import{join as Bp}from"node:path";import{extname as Ei}from"node:path";import{homedir as Oy,tmpdir as Dy}from"node:os";import{basename as Ny,delimiter as Ly,dirname as By,join as Rr,isAbsolute as Wy,relative as jy,resolve as Kt,sep as Uy}from"node:path";import{mkdirSync as np,existsSync as zy,realpathSync as Hy}from"node:fs";function Ie(){let t=process.env.SCREENCAST_HOME;return t&&t.trim().length>0?t:Rr(Oy(),".screencast-mcp")}function we(t){let e=Rr(Ie(),t);return np(e,{recursive:!0}),e}function op(){let t=Ie();return np(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 ip=/\.(png|jpe?g|bmp|tiff?)$/i;function dc(t){return ip.test(t)}function Ee(t){return ip.test(t)?["-update","1",t]:[t]}function Ue(t=""){return Rr(Dy(),`screencast-${ge()}-${be()}${t}`)}var bi="SCREENCAST_ALLOWED_DIRS";function fo(t=process.env){let e=t[bi];return e?e.split(Ly).map(r=>r.trim()).filter(r=>r.length>0).map(r=>Kt(r)):[]}var cn=null;function ho(t){cn=t===null||t==="pending"?t:t.map(e=>Kt(e))}function Mr(t=process.env){let e=fo(t);if(cn===null&&e.length===0)return null;let r=Array.isArray(cn)?cn:[];return[Kt(Ie()),...e,...r]}function rp(t){let e=[],r=Kt(t);for(;;)try{return Rr(Hy.native(r),...e.reverse())}catch{let n=By(r);if(n===r)return Kt(t);e.push(Ny(r)),r=n}}function Ar(t,e){let r=jy(rp(e),rp(t));return r===""||r!==".."&&!r.startsWith(`..${Uy}`)&&!Wy(r)}function Gy(t){let e=t.trim();return/^[\\/]{2}/.test(e)?!/^[\\/]{2}\?[\\/][A-Za-z]:[\\/]/.test(e):!1}function Vt(t,e="Path"){if(Gy(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 sp(t,e="Input"){Vt(t,e);let r=Kt(t);if(cn==="pending"&&fo().length===0&&!Ar(r,Ie()))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=>Ar(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 ${bi} or the client's workspace roots.`)}function Qt(t){if(Vt(t,"Output"),cn==="pending"&&fo().length===0&&!Ar(t,Ie()))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=>Ar(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 ${bi} or the client's workspace roots.`)}function mc(t){if(!(Mr()!==null||Ar(t,Ie())))throw new l(`Refusing to replace ${t}: it is outside SCREENCAST_HOME and no allowed directories are set. Add its folder to ${bi} (or the client's workspace roots) to allow overwriting there, or write to a new path.`)}function Zt(t,e,r,n=!1){if(t&&t.trim().length>0){Vt(t,"Output");let o=Kt(e,t);if(Qt(o),zy(o)){if(!n)throw new l(`Output already exists: ${o}. Pass overwrite: true to replace it, or choose a different path.`);mc(o)}return o}return Rr(e,r)}function ln(t,e){if(!t||t.trim().length===0)return;Vt(t,"Output directory");let r=Kt(e,t);return Qt(r),r}var fc={draft:{preset:"ultrafast",crf:28},standard:{preset:"veryfast",crf:23},high:{preset:"medium",crf:18}},yi=30,xi="standard";function cp(t){return!t||t.device.trim().length===0?[]:["-f","dshow","-i",`audio=${t.device}`]}function go(t,e){if(!/^-?\d+$/.test(t.trim()))throw new l(`${e} must be an integer, got "${t}".`);return parseInt(t,10)}function up(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=go(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]=[go(s,"region x"),go(a,"region y"),go(c,"region w"),go(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 lp(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 bo(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 pp(t,e){if(e.length===0)return;let r=bo(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=fc[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 qy="160k";function Cr(t=qy){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 Si(t,e,r={}){switch(t.kind){case"full":{let n=bo(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=lp(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 Xy(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 hc=3600;function dp(t,e=process.env){if(t!==void 0)return mp(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>Mt)throw new l(`SCREENCAST_MAX_RECORDING_SEC must be an integer from 0 (no cap) to ${Mt} (7 days), got "${r}".`);return n}return hc}var Mt=168*3600;function mp(t){if(!Number.isInteger(t)||t<0||t>Mt)throw new l(`maxDurationSec must be an integer from 0 (no cap) to ${Mt} (7 days).`);return t}function Jy(t){if(!Number.isInteger(t)||t<1||t>120)throw new l("fps must be an integer between 1 and 120.");return t}function wi(t){return["-g",String(Math.max(1,Math.round(t*2)))]}var ap=["-movflags","+frag_keyframe+empty_moov+default_base_moof"];function vi(t,e){let r=Jy(e.fps??yi),n=e.quality??xi,o=e.monitors??[],i=mp(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"]:[],...Si(t,o,{evenSize:!0})],...cp(e.audio),...a?Xy(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),...wi(r),...e.audio?Cr():[],...ap,...s,e.output,...a?["-map",`${c}:v`,...a.codec??_e(n),...wi(r),...ap,...s,a.output]:[]]}var Yy=30;function fp(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(Yy),...Si(t,r),"-frames:v","1",...Ee(e)]}function ki(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=lp(t.index,e);return{x:r.x,y:r.y,w:tt(r.width),h:tt(r.height)}}case"full":{let r=bo(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 gc(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 er(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 Ky=/[:,;=[\]'"\\\s]/;function Ne(t,e="color"){if(t.length===0||Ky.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 bc(t){if(t===void 0)return null;let e=Number(t);return Number.isFinite(e)?e:null}function hp(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 Vy(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=Vy(r),c=a!==null&&Math.abs(a)%180===90;return{durationSec:s,videoDurationSec:r?bc(r.duration)??s:null,width:(c?r?.height:r?.width)??null,height:(c?r?.width:r?.height)??null,...a?{rotation:a}:{},fps:hp(r?.avg_frame_rate)??hp(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:bc(r?.nb_frames),sampleRate:bc(n?.sample_rate),channels:n?.channels??null}}function Or(t){return["-v","quiet","-print_format","json","-show_format","-show_streams",t]}function wc(t,e){if(!Number.isFinite(t)||t<=0)throw new l(`${e} must be a positive number.`);return t}var _i=100,yc=1e3;function Ti(t,e,r){if(wc(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 bp(t,e){for(let r of t)if(/^frame_\d+\.png$/i.test(r))return`frame_${e}_`;return"frame_"}function Ai(t,e,r,n=_i,o=!1,i){wc(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 ht=.1;function tr(t,e=ht){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 rr(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=Ei(t).toLowerCase();return r===".mp4"||r===".mkv"||r===".mov"||e.audio&&wp.has(r)?r:".mp4"}var wp=new Set([".wav",".mp3",".m4a"]);function Ri(t){return wp.has(Ei(t).toLowerCase())}function Dr(t){if(t===void 0)return;let e=Ei(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 yp(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(wc(r.duration,"duration")));return r.exact===!1?o.push("-c","copy",e):o.push(...Se({quality:dn,audio:"aac",bitrate:null}),e),o}function wo(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(/>/g,">").replace(/</g,"<").replace(/&/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 xp(t){if(t.length<2)throw new l("concat requires at least two input files.");return wo(t)}function hn(t,e,r={}){return["-y",...r.quiet?["-v","error"]:[],"-f","concat","-safe","0","-i",t,"-c","copy",e]}function Qy(t){let{videoFrames:e,videoDurationSec:r,fps:n}=t;return e===null||r===null||n===null?!1:e>r*n*1.05+2}function Sp(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(Qy(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 vp(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 Ct(t,e){if(!Number.isInteger(t)||t<=0)throw new l(`${e} must be a positive integer.`);return t}function Mi(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 xc(t,e){let r=pn(t.x,"crop x"),n=pn(t.y,"crop y"),o=er(Ct(t.width,"crop width"),"crop width"),i=er(Ct(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 $p(t,e,r,n,o=dn){return["-y","-i",t,"-vf",xc(r,n),...Se({quality:o,audio:"copy"}),e]}function Sc(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&&er(Ct(t.width,"scale width"),"scale width"),t.height!==void 0&&er(Ct(t.height,"scale height"),"scale height"),`scale=${t.width??-2}:${t.height??-2}`}function kp(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 Ep(t,e,r,n=dn){return["-y","-i",t,"-vf",Sc(r),...Se({quality:n,audio:"copy"}),e]}function vc(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 _p(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",vc(r)),i.push(...Se({quality:o,audio:n?"aac":"none",bitrate:null}),e),i}var Zy="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 Tp(t,e,r,n,o=dn){let i=pn(n.x,"overlay x"),s=pn(n.y,"overlay y"),a=Mi(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&&Ct(n.scale.width,"overlay scale width"),n.scale.height!==void 0&&Ct(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+=`,${Zy}`);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 ex={light:23,medium:28,heavy:32};function Ap(t,e,r={}){let n=r.level??"medium",o=ex[n];if(o===void 0)throw new l(`Unknown compress level "${n}".`);let i=["-y","-i",t];return r.maxWidth!==void 0&&(Ct(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 tx={mp3:["-c:a","libmp3lame","-q:a","2"],aac:Cr("192k"),wav:["-c:a","pcm_s16le"],copy:["-c:a","copy"]};function Rp(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 Mp(t,e,r){let n=tx[r];if(!n)throw new l(`Unknown audio format "${r}".`);return["-y","-i",t,"-vn",...n,e]}function Cp(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 Ci=["box","blur","pixelate"];function rx(t,e,r){return t.map((n,o)=>{let i=pn(n.x,`region[${o}] x`),s=pn(n.y,`region[${o}] y`),a=Ct(n.width,`region[${o}] width`),c=Ct(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:Mi(n.start,n.end)}})}var nx=8,gp=3,ox=16;function ix(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(nx,Math.min(20,Math.floor(e/4)))),o=Math.min(n,r(Math.ceil(e/2)));return`lr=${n}:lp=${gp}:cr=${o}:cp=${gp}`}function sx(t){let e=Math.max(ox,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 $c(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=Ne(e.color??"black","color"),c=rx(t,s,r);if(i==="box"){let m=c.map(h=>{let g=h.enable?`:enable='${h.enable}'`:"";return`drawbox=x=${h.x}:y=${h.y}:w=${h.w}:h=${h.h}:color=${a}:t=fill${g}`}).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 g=`crop=${m.w}:${m.h}:${m.x}:${m.y}`,w=i==="blur"?`boxblur=${ix(m)}`:sx(m);d.push(`[${o}s${h}]${g},${w}[${o}b${h}]`)});let f=`${o}base`;return c.forEach((m,h)=>{let g=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}${g}[${w}]`),f=`${o}c${h}`}),{steps:d,out:`[${o}out]`}}function Pi(t,e){if(!dc(t))return Dr(e),{still:!1,ext:V(t)};if(e&&!dc(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)?Ei(t).toLowerCase():".png"}}function Pp(t,e,r,n={},o,i=!1){let s=i?r.map(({start:d,end:p,...f})=>f):r,{steps:a,out:c}=$c(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 ax="screencast-mcp",Ip=new Set;function Fp(t){Ip.add(t)}function nr(t,e,r={}){for(let n of Ip)n.isConnected()&&n.sendLoggingMessage({level:t,logger:ax,data:{message:e,...r}}).catch(()=>{})}var Op=/^\s*(?:frame|size)=/,cx=/\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,ux=/^\s*configuration:|deprecated pixel format used/i,Dp=20;function Np(t){return!Op.test(t)&&cx.test(t)&&!ux.test(t)}function lx(t){let e=new Set;for(let r of t.split(/[\r\n]+/)){let n=r.trim();if(n&&Np(n)&&e.add(n),e.size>=Dp)break}return[...e]}function Lp(t,e={}){let r=lx(t);r.length>0&&nr("warning","ffmpeg reported warnings.",{...e,warnings:r})}var px=1e4,Ii=class{constructor(e,r=nr,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(Op.test(e)){let r=Number(/\bdrop=\s*(\d+)/.exec(e)?.[1]??0);r>this.dropped&&this.now()-this.lastDropReport>=px&&(this.lastDropReport=this.now(),this.dropped=r,this.send("warning",`The recording has dropped ${r} frame(s) so far.`,{...this.data(),dropped:r}));return}!Np(e)||this.seen.has(e)||this.seen.size>=Dp||(this.seen.add(e),this.send("warning",e,{...this.data(),source:"ffmpeg"}))}}};var bx="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 Wp(t,e){let r=process.env[t];return r&&r.trim().length>0?r:e}function jp(t){try{return Oi(t,["-version"],{stdio:"ignore",windowsHide:!0}).status===0}catch{return!1}}function kc(){let t=Wp("FFMPEG_PATH","ffmpeg"),e=Wp("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.`,bx);return{ffmpeg:t,ffprobe:e}}var Fi=null;function k(){return Fi||(Fi=kc(),Fi)}var bn=null;function or(){if(bn!==null)return bn;if(process.platform!=="win32")return bn=!1;try{let t=Oi(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 Up=new Map;function Ye(t){let e=Up.get(t);if(e!==void 0)return e;let r;try{let n=Oi(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 Up.set(t,r),r}var Hp=["ignore","pipe","pipe"],xo=class extends l{};function ne(t,e,r=300*1e3,n={}){return new Promise((o,i)=>{let s=zp(t,e,{windowsHide:!0,stdio:Hp}),a="",c="",u=null,d,p=b=>{u||(u=b,s.kill("SIGKILL"),d=setTimeout(()=>i(b),5e3))},f=()=>p(new l(`${t} was cancelled.`)),m=setTimeout(()=>p(new l(`${t} timed out after ${Math.round(r/1e3)}s.`)),r),h,g=()=>{n.stallMs&&(clearTimeout(h),h=setTimeout(()=>p(new xo(`${t} wrote nothing for ${Math.round(n.stallMs/1e3)}s and was stopped.`)),n.stallMs))};g();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",b=>{g();let y=b.toString();a+=y,n.onStdout?.(y)}),s.stderr?.on("data",b=>{g(),c+=b.toString()}),s.on("error",b=>{w(),i(b)}),s.on("close",b=>{w(),u?i(u):o({code:b,stdout:a,stderr:c})})})}var wx=new Set(["-vf","-af","-filter_complex","-lavfi","-filter:v","-filter:a"]),yx=8e3,xx={"-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"},yo=null;function Sx(){if(yo!==null)return yo;try{let t=Oi(k().ffmpeg,["-hide_banner","-version"],{encoding:"utf8",windowsHide:!0,timeout:1e4}),e=/^\s*libavutil\s+(\d+)\./m.exec(t.stdout??"");yo=e?.[1]===void 0||Number(e[1])>=59}catch{yo=!0}return yo}function Di(t,e){let r=null,n=[...t];for(let[i,s]of t.entries()){let a=t[i-1];if(a===void 0||!wx.has(a)||s.length<=yx)continue;r??=mx(Bp(gx(),"screencast-filter-"));let c=Bp(r,`filter${i}.txt`);hx(c,s),e??=Sx(),n[i-1]=e?`-/${a.slice(1)}`:xx[a]??a,n[i]=c}let o=r;return{args:n,cleanup:()=>o&&fx(o,{recursive:!0,force:!0})}}async function Nr(t,e=3e4,r={}){let n=[];return await Gp(t,e,o=>n.push(o),r),Buffer.concat(n)}async function Ni(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 Gp(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 Gp(t,e,r,n){let{ffmpeg:o}=k(),{args:i,cleanup:s}=Di(t);return new Promise((a,c)=>{let u=zp(o,i,{windowsHide:!0,stdio:Hp}),d="",p=null,f,m=b=>{p||(p=b,u.kill("SIGKILL"),f=setTimeout(()=>c(b),5e3))},h=()=>m(new l("ffmpeg was cancelled.")),g=setTimeout(()=>m(new l(`ffmpeg timed out after ${Math.round(e/1e3)}s.`)),e),w=()=>{clearTimeout(g),clearTimeout(f),n.signal?.removeEventListener("abort",h)};n.signal?.aborted?h():n.signal?.addEventListener("abort",h,{once:!0}),u.stdout?.on("data",b=>{if(!p)try{r(b)}catch(y){m(y)}}),u.stderr?.on("data",b=>d+=b.toString()),u.on("error",b=>{w(),c(b)}),u.on("close",b=>{w(),p?c(p):b===0?a():c(new l(`ffmpeg failed (exit ${b}):
|
|
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
|
|
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}`)}
|
|
155
|
-
`),
|
|
156
|
-
`)[0]:String(h)}`),
|
|
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
|
|
158
|
-
`).slice(-3).join(" ")}`)}let c=i.filter(u=>u.webcamPath&&
|
|
159
|
-
`).slice(-3).join(" ")}`)}return a||
|
|
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
|
-
`,
|
|
174
|
-
`,
|
|
175
|
-
`}function
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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,37 +263,23 @@ public static class ScDxgi {
|
|
|
263
263
|
return sb.ToString(); } }
|
|
264
264
|
"@
|
|
265
265
|
[ScDxgi]::List()
|
|
266
|
-
`,
|
|
267
|
-
`)}catch{}return new Map}}parseDisk(){let e=JSON.parse(
|
|
268
|
-
`),r=e()}this.records=new Map(
|
|
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(!
|
|
270
|
-
`),t.stdin.end();let n=await
|
|
271
|
-
`)}}),i,s=new Promise(a=>{i=setTimeout(a,r)});return await Promise.race([Promise.allSettled(o),s]),clearTimeout(i),n}function
|
|
272
|
-
`)}var
|
|
273
|
-
`),o=[];t.length<
|
|
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 cs(t){return t.map(e=>({start:e.t,title:e.label}))}function km(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 av(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 Em(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:av(a.text)}),s=Math.max(s,a.end)}return i}var os=8;function _m(t,e,r,n){let o=n.subtitles??[];if(o.length>os)throw new l(`At most ${os} 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 cv(t){return["-v","quiet","-print_format","json","-show_chapters",t]}function uv(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:Pt(o),end:Pt(i),title:r.tags?.title??`Chapter ${n+1}`}]})}async function lv(t,e){let{ffprobe:r}=k(),n=await ne(r,cv(t),3e4,{signal:e});return n.code===0?uv(n.stdout):[]}async function dr(t,e){let r=Le(t);if(r.length>0)return{markers:r,from:"sidecar"};let n=await lv(t,e);return n.length>0?{markers:n.map(o=>({t:o.start,label:o.title})),from:"chapters"}:{markers:[],from:null}}function us(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=Sm(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=is(o.markers??[],s);t.update(e,{markers:a});let c=lr(o.outputPath),u;try{c=pr(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 pv,readFileSync as dv}from"node:fs";import{dirname as Tm,join as ls}from"node:path";import{fileURLToPath as mv}from"node:url";var Am="@tmhs/screencast-mcp",Gc=null,fv=null;function Rm(t){try{return JSON.parse(dv(t,"utf8"))}catch{return null}}function hv(t){for(let e=t;;){let r=ls(e,"package.json");if(pv(r)&&Rm(r)?.name===Am)return e;let n=Tm(e);if(n===e)return null;e=n}}function qc(){if(Gc)return Gc;let t=hv(Tm(mv(import.meta.url)));if(!t)throw new l(`Cannot find the ${Am} package root (its package.json).`);return Gc=t}function bt(){return fv??=Rm(ls(qc(),"package.json"))?.version??"0.0.0"}function vn(...t){return ls(qc(),"assets",...t)}function Mm(){return ls(qc(),"dist","wgcRecorder.js")}async function at(t,e={}){let r=up(t);if(r.kind==="window"){let n=await md(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 sr()}:r.kind==="region"?(pp(r,await sr()),{target:r,monitors:[]}):{target:r,monitors:await sr()}}var gv=["virtual-audio-capturer","stereo mix","what u hear","wave out mix","cable output","voicemeeter output"],Ro="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 bv(t){return Cm(t,"audio")}function wv(t){return Cm(t,"video")}function Cm(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 Xc(t,e){if(e&&e.trim().length>0)return t.includes(e)?e:null;let r=n=>n.toLowerCase();return t.find(n=>gv.some(o=>r(n).includes(o)))??null}var yv=12e3,xv="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. "+Ro,ps=null,ds=null;async function Jc(t=!1){return!t&&ps?ps:(await Im(),ps??[])}async function Yc(t=!1){return!t&&ds?ds:(await Im(),ds??[])}async function Pm(t){let e=await Yc();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 Im(){let{ffmpeg:t}=k(),e;try{e=await ne(t,["-hide_banner","-list_devices","true","-f","dshow","-i","dummy"],yv)}catch(r){throw new l(`Could not enumerate audio devices (${U(r)}).`,xv)}ps=bv(e.stderr),ds=wv(e.stderr)}async function Fm(t){let e=await Jc(),r=Xc(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}.`,Ro)}throw new l("No system-audio loopback device found.",Ro)}var Mo="SCREENCAST_CONFIRM_CAPTURE",Kc=300*1e3;function Om(t=process.env){let e=(t[Mo]??"").trim().toLowerCase();return["1","true","yes","on","always"].includes(e)?"always":["0","false","no","off","never"].includes(e)?"off":"auto"}function Dm(t=process.env){return Om(t)==="always"}function It(t,e){return e?`window "${e.matchedTitle}"`:t==="full"?"the full screen (all monitors)":t}async function Ft(t,e,r){let n=Om();if(n==="off")return;if(!t.server.getClientCapabilities()?.elicitation?.form){if(n==="auto")return;throw new l(`Capture blocked: ${Mo} 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 ${Mo}=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:Kc}))}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 ms=null;function re(){return ms||(ms=new Zi(op()),ms.load()),ms}var Qc=!1;function Nm(){Qc=!0}function hs(){return Qc}var fs=0,Vc=[];function Lm(){if(Qc)throw new l("The server is shutting down; the recording was not started.");fs++;let t=!1;return()=>{if(!t&&(t=!0,fs--,fs===0)){let e=Vc;Vc=[];for(let r of e)r()}}}function Bm(t){return fs===0?Promise.resolve(!0):new Promise(e=>{let r=setTimeout(()=>e(!1),t);r.unref?.(),Vc.push(()=>{clearTimeout(r),e(!0)})})}import{existsSync as i0,mkdirSync as s0,mkdtempSync as a0,rmSync as du,writeFileSync as af}from"node:fs";import{tmpdir as c0}from"node:os";import{spawn as Sv}from"node:child_process";var Wm=15e3;async function Ot(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(!or())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=Sv("powershell",["-NoProfile","-NonInteractive","-Command",Ld(n,100,process.pid)],{stdio:"ignore",windowsHide:!0});o.on("error",()=>{});try{await Z(fp(n,e),Wm)}catch(i){throw i instanceof l&&/timed out/.test(i.message)?new l(`Windows Graphics Capture got no frame from the window in ${Wm/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 Zc}from"node:path";import{readdirSync as Dv}from"node:fs";import{runInNewContext as vv}from"node:vm";var $v=[2,4],kv=1e4;function Ev(t){return{script:Iv,payload:JSON.stringify(t)}}async function Um(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}=Ev(t),o=await st(r,"text (OCR)",{timeoutMs:ir(Cv+Math.max(0,t.length-2)*Pv),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)=>_v(a,e[c]??1))}function _v(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,...zm(i)})}return n}function zm(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 Tv(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 Hm(t){let e=[];for(let r of t)for(let n of r){let o=e.findIndex(s=>Tv(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,Av=1e3,Rv=`JSON.stringify(texts.map((text) => {
|
|
276
|
-
const re = new RegExp(query, "gi");
|
|
277
|
-
const seen = new Set();
|
|
278
|
-
const ranges = [];
|
|
279
|
-
for (const variant of [text, text.replace(/-/g, "_"), text.replace(/_/g, "-")]) {
|
|
280
|
-
for (const m of variant.matchAll(re)) {
|
|
281
|
-
const key = m.index + ":" + m[0].length;
|
|
282
|
-
if (m[0].length > 0 && !seen.has(key)) {
|
|
283
|
-
seen.add(key);
|
|
284
|
-
ranges.push([m.index, m.index + m[0].length]);
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
return ranges;
|
|
289
|
-
}))`;function $n(t,e,r=Av){try{new RegExp(e,"gi")}catch(n){throw new l(`Invalid regex: ${U(n)}`)}try{return JSON.parse(vv(Rv,{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 wt(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(Mv(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,...zm(m)}))}}),i}function Mv(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 gs(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 Gm(t,e){let r=kv/Math.max(t,e),n=$v.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 Cv=6e4,Pv=5e3,jm=2e4,Iv=`
|
|
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=`
|
|
290
276
|
$ErrorActionPreference = 'Stop'
|
|
291
277
|
Add-Type -AssemblyName System.Runtime.WindowsRuntime
|
|
292
278
|
$null = [Windows.Storage.StorageFile, Windows.Storage, ContentType = WindowsRuntime]
|
|
293
279
|
$null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
|
|
294
280
|
$null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime]
|
|
295
281
|
$asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' })[0]
|
|
296
|
-
function Await($op, [Type]$t) { $task = $asTask.MakeGenericMethod($t).Invoke($null, @($op)); if (-not $task.Wait(${
|
|
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 }
|
|
297
283
|
$paths = $Payload | ConvertFrom-Json
|
|
298
284
|
$engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
|
|
299
285
|
$out = foreach ($p in $paths) {
|
|
@@ -311,46 +297,48 @@ $out = foreach ($p in $paths) {
|
|
|
311
297
|
} catch { [pscustomobject]@{ error = $_.Exception.Message } }
|
|
312
298
|
}
|
|
313
299
|
ConvertTo-Json -InputObject @($out) -Depth 6 -Compress
|
|
314
|
-
`;import{availableParallelism as
|
|
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(`
|
|
315
301
|
`)+(t.length?`
|
|
316
|
-
`:"")}function
|
|
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(`
|
|
317
303
|
`)+(t.length?`
|
|
318
|
-
`:"")}function
|
|
319
|
-
${s.message}`}),{head:()=>r,tail:()=>n,outputAt:()=>o}}function
|
|
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(`
|
|
320
306
|
`).slice(-e).join(`
|
|
321
|
-
`)}function
|
|
322
|
-
${
|
|
323
|
-
`)})
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
`))}function
|
|
327
|
-
`)}
|
|
328
|
-
${
|
|
329
|
-
(Retried with libx264 after ${ie})`:""));i.child=x;let{startMs:Q,frame:te,record:T}=S0(r,s,{id:N,child:x,watch:q,spawnedAt:H,captureOpts:de,webcam:G,encoder:ae.encoder,evPaths:P,keyMode:R,webcamRaw:i.webcamRaw}),_=re();v0(_,T,x),i.handOff();let A=i.logger;return A&&P&&f0(_,N,{logger:A,evPaths:P,keyMode:R,startMs:Q,frame:te,replay:m,child:x}),pu(_,N,x,{backend:f,maxDurationSec:w,spawnedAt:H,watch:q}),r.perf&&h0(_,N,{output:b,startMs:Q,window:p}),j&&r.logs&&g0(_,N,{tailer:j,logs:r.logs,output:b,startMs:Q}),r.hotkeys&&(X=b0(_,N)),r.stopWhen&&w0(_,N,{target:r.target,exactTitle:r.exactTitle,text:r.stopWhen.text}),v(bd({record:T,audioDevice:y?.device,maxDurationSec:w,encoder:ae.encoder,encoderNote:ae.note,...S?{gpuFrames:ae.gpuFrames}:{},webcamDevice:$,window:p,...P?{events:{jsonl:P.jsonl,keys:R}}:{},...r.logs?{logs:{path:Nt(b),missing:r.logs.some(z=>!i0(z.path))}}:{},...r.hotkeys?{hotkeys:{taken:A?Zl(A):[]}}:{},...m?{replay:{...m,events:!!P}}:{}}))}catch(s){return await i.release(),E(s)}finally{o()}})}import{z as An}from"zod";import{existsSync as hu}from"node:fs";function mf(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 $0(t,e){if(t.error||!hu(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?ad(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 k0={sessionId:An.string().min(1).describe("Session id returned by start_recording."),save:An.boolean().optional().describe("Replay buffer: write it all to outputPath first (default: discard).")};function ff(t){t.registerTool("stop_recording",{title:"Stop Recording",description:"Stop a recording gracefully so the file is finalized; returns the path and duration.",inputSchema:k0,outputSchema:D({sessionId:An.string(),status:An.string(),outputPath:An.string(),durationSec:An.number().nullable()}),annotations:Ui},async e=>{try{let r=re(),n=e.sessionId;if(ys(n)){let f=xs(n);if(!f)throw new l(`No armed recording with id "${n}".`);let m={sessionId:n,outputPath:"",durationSec:null};if(ru(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&&hu(o.replay.dir)?await Xi(o.replay,{save:e.save??!1,output:o.outputPath,quality:o.quality,tools:k}):void 0;return v({...f?{replay:mf(f)}:{},sessionId:o.id,status:o.status,outputPath:o.outputPath,durationSec:o.durationSec??null,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=em(o,process.pid,Wc(o));if(i)throw new l(i);let{ffprobe:s}=k(),{record:a,graceful:c,durationSec:u,replay:d,segments:p}=await _o(r,o,{reason:"stopped",probe:f=>ue(f,{ffprobe:s}),saveReplay:e.save});return v({sessionId:o.id,status:"stopped",outputPath:o.outputPath,durationSec:u??null,finalizedGracefully:c,...d?{replay:mf(d)}:{},...p&&p.count>1?{segmentsJoined:p.count}:{},...p?.error?{segmentsError:p.error}:{},...a?.webcam?{webcam:await $0(a.webcam,o.outputPath)}:{},...a?.events?{eventsPath:a.events.path,events:a.events.summary??{},...a.events.error?{eventsError:a.events.error}:{}}:{},fileExists:hu(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 fr}from"zod";import{existsSync as Iu,readdirSync as Vf,rmSync as b$,statSync as w$}from"node:fs";import{dirname as y$,resolve as Qf}from"node:path";import{createHash as Cf}from"node:crypto";import{closeSync as e$,existsSync as Rn,openSync as t$,readFileSync as r$,readdirSync as n$,readSync as o$,renameSync as i$,statSync as s$,writeFileSync as a$}from"node:fs";import{basename as Pf,dirname as c$,join as Mn,resolve as Is}from"node:path";import{closeSync as C0,existsSync as wu,openSync as P0,readSync as I0,statSync as F0}from"node:fs";import{basename as Es,isAbsolute as O0,join as yu}from"node:path";function xt(t,e,r){if(t.length<e)throw new Error(`Truncated font: ${r}.`);return t}function E0(t,e){let r=xt(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 xt(t(12+e*4,4),4,"collection offsets").readUInt32BE(0)}var ks=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 _0(t){let e=xt(t,14,"cmap format 4").readUInt16BE(6),r=14,n=r+e+2,o=n+e,i=o+e;xt(t,i+e,"cmap format 4 segments");let s=new ks;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 T0(t,e){let r=xt(t,16,`cmap format ${e}`).readUInt32BE(12);xt(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 ks;for(let[i,s]of n)o.add(i,s);return o.ranges}function A0(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 hf(t,e=0){let r=E0(t,e),n=xt(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=xt(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=xt(t(a,4),4,"cmap header").readUInt16BE(2),d=xt(t(a+4,u*8),u*8,"cmap records"),p=[];for(let f=0;f<u;f++){let m=A0(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 _0(t(f,m.readUInt16BE(2)));if(h===12||h===13)return T0(t(f,m.readUInt32BE(4)),h)}throw new Error("Font has no Unicode cmap subtable this reader understands (formats 4, 12, 13).")}function R0(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 M0(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 Io(t,e){let r=new Set,n=[];for(let o of t){let i=o.codePointAt(0);r.has(i)||(r.add(i),M0(i)&&!R0(e,i)&&n.push(o))}return n}var D0={regular:"Inter-Regular.ttf",bold:"Inter-Bold.ttf"};function Lt(t="bold"){return vn("fonts",D0[t])}function ye(t){return t.replace(/\\/g,"/").replace(/:/g,"\\\\:").replace(/'/g,"\\\\\\'").replace(/([,;[\]])/g,"\\$1")}var N0={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"]}},L0=["segoe","japanese","chineseSimplified","chineseTraditional","korean","indic","thai","ethiopic","emoji","symbol"];function B0(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,...L0.filter(r=>!e.includes(r))].map(r=>N0[r])}function W0(t,e){let r=null;for(let n of e){let o=Io(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 bf(){return yu(process.env.WINDIR??process.env.SystemRoot??"C:\\Windows","Fonts")}var gf=new Map;function gu(t){let e=gf.get(t);if(e!==void 0)return e;let r,n=null;try{n=P0(t,"r");let o=n;r=hf((s,a)=>{let c=Buffer.alloc(a);return c.subarray(0,I0(o,c,0,a,s))})}catch{r=null}finally{n!==null&&C0(n)}return gf.set(t,r),r}function j0(t){if(wu(t)&&F0(t).isFile())return t;if(!O0(t)&&Es(t)===t){let e=yu(bf(),t);if(wu(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 bu(t){let e=t.replace(/\s+/g," ").trim();return`"${e.length>40?`${e.slice(0,39)}\u2026`:e}"`}function St(t,e={}){if(e.fontFile){let c=j0(e.fontFile),u=gu(c);if(!u)return{fontFile:c,missing:[],fallback:!1,warning:`Could not read the character map of ${Es(c)}; glyph coverage of ${bu(t)} was not checked.`};let d=Io(t,u);return d.length===0?{fontFile:c,missing:d,fallback:!1}:{fontFile:c,missing:d,fallback:!1,warning:`${Es(c)} has no glyph for ${d.join(" ")} in ${bu(t)}; they render as empty boxes.`}}let r=e.weight??"bold",n=Lt(r),o=gu(n);if(o&&Io(t,o).length===0)return{fontFile:n,missing:[],fallback:!1};let i=e.fontsDir??bf(),s=o?[{path:n,coverage:o}]:[];for(let c of B0(t))for(let u of c[r]){let d=yu(i,u),p=wu(d)?gu(d):null;if(p){if(Io(t,p).length===0)return{fontFile:d,missing:[],fallback:!0};s.push({path:d,coverage:p});break}}let a=W0(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 ${bu(t)}; they render as empty boxes (drawn with ${Es(a.fontFile)}). Pass fontFile with a font that covers them.`}}import{mkdtempSync as U0,rmSync as z0,writeFileSync as H0}from"node:fs";import{join as xu}from"node:path";import{tmpdir as G0}from"node:os";var Fo=12,wf=48,Oo=320;function _s(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 q0(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 X0(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 J0(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 yf(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 Ts(t,e,r,n,o){let i=q0(e.length,n.columns),s=U0(xu(G0(),"screencast-sheet-"));try{let a=Lt("bold");await He(e,async(c,u)=>{let d=xu(s,`label_${u}.txt`);H0(d,Fe(c));let p=xu(s,`tile_${String(u).padStart(3,"0")}.png`);await Z(X0(t,c,p,n.tileWidth,a,d),6e4,{signal:o})}),await Z(J0(un(s,"tile_%03d.png"),i,r),6e4,{signal:o})}finally{z0(s,{recursive:!0,force:!0})}return i}import{existsSync as As}from"node:fs";var xf=t=>Math.round(t*1e3)/1e3,Y0={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 Su(t){return t.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()}function vu(t){let e=Su(t.role),r=t.app?` in ${t.app}`:"";return t.name?`the "${t.name}" ${e}${r}`:`${/^[aeiou]/.test(e)?"an":"a"} ${e}${r}`}function Sf(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} ${vu(r.element)}`:r.inFrame?`${o} at (${r.x}, ${r.y})`:`${o} outside the recorded area`}function $u(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=Sf(s.button,!0,a.e),n=null;continue}let c={t:s.t,action:"click",text:Sf(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 ${xf(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=Y0[s.reason??"input_not_seen"],c=xf(s.durationSec??0);e.push({t:s.t,action:"gap",text:`Input may be missing for ${c} s (${a})`,durationSec:c})}}return e}function ku(t){return $u(t).map(({button:e,inFrame:r,keys:n,durationSec:o,element:i,...s})=>s)}var Eu=30,Rs=600,_u=1,Ms=100,Tu=20,Ge=["\\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("|"),Cs="error|exception|fail(?:ed|ure)?|fatal|crash|denied|refused|not found|cannot|can't|unable|invalid|timed? ?out|traceback|panic|unhandled|warning",Bt={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 $f(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??Eu,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>Rs)throw new l(`The clip would be ${Do(r-o)}s; at most ${Rs}s. Narrow start/end.`);return{start:Do(o),end:Do(r)}}function K0(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 kf(t){let e=[];for(let r of[...t].sort((n,o)=>n.start-o.start)){let n=e.find(s=>r.start<=s.end&&K0(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 V0="[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?V0:""),a=u);return s+n.slice(a)})}function Ef(t,e,r){let n=new Map;for(let a of t){let c=new Set(wt(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,Tu);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 Q0=t=>`\`${t.replace(/`/g,"'").replace(/\s+/g," ").trim()}\``,vf=t=>t.replace(/\|/g,"\\|").replace(/\s*\n\s*/g," ");function _f(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}\` ${Q0(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. -->",``,""),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(`| ${vf(i)} | ${vf(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(`
|
|
330
|
-
`)}async function Ps(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 Yt(n.id),!As(n.outputPath))throw new l(`The session's recording is missing: ${n.outputPath}`);let o=n.events?.path;return{path:n.outputPath,eventsPath:o&&As(o)?o:null,record:n}}let e=t.input;if(!As(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=$e(e);return{path:e,eventsPath:As(r)?r:null}}var Z0=40;function Tf(t,e,r){let n=t.filter(i=>i.t>=e.start-5&&i.t<=e.end).slice(-Z0),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 Af(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=_n(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 Au=1,Ru=.03,Mu=120,If=600,u$=10,Fs=10,Ff=50,Rf=200,l$=5,mr=t=>Math.round(t*1e3)/1e3;function No(t){return`${t}.index.json`}function Cu(t){return`${t.replace(/\.[^./\\]+$/,"")}.index.json`}function Lo(t,e){let r=n=>process.platform==="win32"?Is(n).toLowerCase():Is(n);return r(t)===r(e)}function Os(t,e,r){return typeof t.video=="string"&&Lo(t.video,e)?!0:r!==void 0&&!!t.fingerprint&&js(t.fingerprint,r)}function Ds(t,e){let r=Cf("sha1").update(Is(t).toLowerCase()).digest("hex").slice(0,12),n=Pf(t).replace(/\.[^.]+$/,"");return Mn(e,"indexes",`${n}-${r}.index.json`)}function Of(t,e){let r=No(t);try{return Qt(r),r}catch{return Ds(t,e)}}function Ns(t,e,r){for(let o of[No(t),Ds(t,e)])if(Rn(o))return o;let n=Cu(t);if(n!==No(t)&&Rn(n)){let o=zr(n);if(o&&Os(o,t,r))return n}return null}function Df(t,e){return t!==null&&js(t.fingerprint,e.fingerprint)&&t.sceneThreshold===e.sceneThreshold&&t.maxFrames===e.maxFrames&&(t.ocr||!e.ocrAvailable)}function Nf(t,e=Ge){return t.map(r=>r.ocr.length>0?{...r,ocr:Oe(r.ocr,e)}:r)}var p$=/\.(mp4|mkv|mov|webm|avi|m4v|wmv|flv|gif|ts|mpg|mpeg)$/i,Mf=t=>t.replace(/\.[^.]+$/,"").toLowerCase();function Ls(t,e){let r=new Set(e.map(s=>s.toLowerCase())),n=Pf(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()&&p$.test(s)&&Mf(s)===Mf(n))?{path:null,ambiguous:!0}:{path:Mn(c$(t),o),ambiguous:!1}:{path:null,ambiguous:!1}}function Lf(t,e,r,n=u$){let o=mn(t.filter(i=>i.timeSec<e),r).map(mr);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,mr(o[i]+s/2))}return[...new Set(o)].sort((i,s)=>i-s)}function Bf(t,e){return t.map((r,n)=>({start:r,end:mr(t[n+1]??e)}))}function Bs(t){return mr(t.start+Math.min(.25,(t.end-t.start)/2))}function Wf(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. -->",``,""),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(`
|
|
331
318
|
`)===r.ocr.join(`
|
|
332
|
-
`)&&!r.events&&!r.markers&&!r.transcript?n.end=r.end:e.push({...r,ocr:[...r.ocr]})}return e}function jf(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?` ${Su(i.role)}${i.name?` ${i.name}`:""}${i.app?` ${i.app}`:""}`:"")}else r.type==="key"?o=`shortcut ${r.keys??"key"}`:r.type==="typing"?o=`typing ${mr(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:mr(r.t),text:o})}return e}function Uf(t){return t.map(e=>({t:mr(e.t),text:e.label}))}function zf(t){return t.map(e=>({t:mr(e.start),text:e.text.replace(/\s+/g," ").trim()})).filter(e=>e.text)}function Ur(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 Ws(t){let e=s$(t),r=Cf("sha1"),n=64*1024,o=t$(t,"r");try{let i=Buffer.alloc(n);for(let s of e.size>n?[0,e.size-n]:[0]){let a=o$(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 js(t,e){return t.size===e.size&&t.mtimeMs===e.mtimeMs&&t.sample===e.sample}function d$(t){try{let e=JSON.parse(t);return e?.version!==Au||!Array.isArray(e.segments)||!e.fingerprint?null:e}catch{return null}}function zr(t){try{return d$(r$(t,"utf8"))}catch{return null}}function Hf(t,e){let r=`${t}.${process.pid}.tmp`;a$(r,JSON.stringify(e)),i$(r,t)}function m$(t){let e=t.replace(/\s+/g," ").trim();return e.length>Rf?`${e.slice(0,Rf-1)}\u2026`:e}function f$(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 Gf(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)}function Pu(t,e,r={}){if(Gf(e,r.regex===!0),r.video!==void 0&&!Os(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,o=f$(t),i=n?Oe(o.map(f=>f.text),n):o.map(f=>f.text),s=o.map((f,m)=>({...f,text:i[m]??""})),a=new Map,c=(f,m)=>{let h=a.get(f.seg)??{score:0,matches:[]};h.score+=m,h.matches.push(f),a.set(f.seg,h)};if(r.regex){let f=$n(s.map(m=>m.text),e);s.forEach((m,h)=>{(f[h]??[]).length>0&&c(m,2)})}else{let f=Dt(e.trim()),m=f.split("_").filter(Boolean),h=s.map(g=>Dt(g.text));if(s.forEach((g,w)=>{h[w].includes(f)&&c(g,2)}),m.length>1){let g=new Map;s.forEach((w,b)=>g.set(w.seg,[...g.get(w.seg)??[],b]));for(let[w,b]of g)if(!a.has(w)&&m.every(y=>b.some($=>h[$].includes(y)))){for(let y of b)m.some($=>h[y].includes($))&&c(s[y],0);a.get(w).score=1}}}return{hits:[...a.entries()].map(([f,m])=>({seg:f,...m})).sort((f,m)=>m.score-f.score||t.segments[f.seg].start-t.segments[m.seg].start).slice(0,r.limit??Fs).map(f=>{let m=t.segments[f.seg],h=f.matches.slice(0,l$).map(g=>({source:g.source,t:g.t,text:m$(g.text)}));return{start:m.start,end:m.end,t:Math.min(...f.matches.map(g=>g.t)),score:f.score,matches:h}}),total:a.size}}var h$=20;function g$(t){return[Mn(t,"recordings"),Mn(t,"edits"),Mn(t,"edits","indexes")]}function qf(t){let e=[];for(let r of g$(t)){let n;try{n=n$(r)}catch{continue}for(let o of n)o.endsWith(".index.json")&&e.push(Mn(r,o))}return e}function Xf(t,e,r={}){Gf(e,r.regex===!0);let n=new Map;for(let c of t){let u=Is(c.index.video).toLowerCase(),d=n.get(u);(!d||c.index.createdAt>d.index.createdAt)&&n.set(u,c)}let o=r.limit??Fs,i=[],s=[],a=0;for(let c of n.values()){let u=Pu(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,h$),searched:n.size}}async function Us(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 Yt(n.id),!Rn(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&&Rn(o)?o:null,markers:i}}let e=t.input;if(!Rn(e))throw new l(`Input file not found: ${e}`);let{jsonl:r}=$e(e);return{path:e,eventsPath:Rn(r)?r:null,markers:Le(e)}}import{basename as Jf}from"node:path";function Yf(t,e,r){let n=$e(t),o=Ls(t,e),i=[n.jsonl,n.raw,`${n.raw}.stop`,Lr(t),No(t),Ds(t,r),lr(t),Nt(t),yt(t),Ji(t),...o.path&&!o.ambiguous?[o.path]:[]];return{files:[...new Set(i)].filter(s=>Jf(s)!==Jf(t)),dirs:[gt(t)]}}function Kf(t){if(Vt(t,"Recording"),![Ie(),...Mr()??[]].some(r=>Ar(t,r)))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:fr.string().min(1).optional().describe("Session id of the recording to delete."),input:fr.string().min(1).optional().describe("Or the recording's path.")};function Zf(t){try{let e=w$(t);return e.isDirectory()?Vf(t).reduce((r,n)=>r+Zf(Qf(t,n)),0):e.size}catch{return 0}}async function S$(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form){if(Dm())throw new l(`Not deleted: ${Mo} 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:Kc}))}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 eh(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:D({outputPath:fr.string(),deleted:fr.array(fr.string()),bytesFreed:fr.number(),sessionsRemoved:fr.array(fr.string())}),annotations:yd},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=Qf(e.input);Kf(o);let i=n.list().filter(g=>Lo(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=Vf(y$(o))}catch{}let c=Yf(o,a,we("edits")),u=[o,...c.files,...c.dirs].filter(g=>Iu(g));if(u.length===0&&i.length===0)throw new l(`Nothing to delete: ${o} does not exist.`);let d=await S$(t,`Delete ${o} and ${u.length-(Iu(o)?1:0)} sidecar file(s)? This cannot be undone.`,r.signal),p=0,f=[],m=[];for(let g of u){let w=Zf(g);try{b$(g,{recursive:!0,force:!0}),f.push(g),p+=w}catch(b){m.push(`${g}: ${U(b)}`)}}let h=Iu(o)?[]:i.map(g=>g.id);return h.length>0&&n.remove(h),v({outputPath:o,deleted:f,bytesFreed:p,sessionsRemoved:h,confirmedByUser:d,...m.length>0?{failed:m,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 hr}from"zod";import{existsSync as v$}from"node:fs";function F(t,e="Input file"){if(!v$(t))throw new l(`${e} not found: ${t}`)}function B(t,e,r,n={}){return n.anyContainer||Dr(t),Zt(t,we(n.dir??"edits"),`${e}-${ge()}-${be()}${r}`,n.overwrite)}var $$={sessionId:hr.string().min(1).describe("Session id of a replay buffer."),lastSec:hr.number().positive().max(yn).optional().describe("Seconds back from now (default and max: the buffer length)."),output:hr.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),overwrite:hr.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),reencode:hr.boolean().optional().describe("Frame-exact re-encode. Default: instant stream copy that may hide up to 2 s of earlier frames.")};function th(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:$$,outputSchema:D({sessionId:hr.string(),outputPath:hr.string(),durationSec:hr.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&&gi($e(c),e.overwrite);let u=Date.now(),d=await Fc(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;nr("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:Od(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 zs}from"zod";var rh=t=>Math.round(t*1e3)/1e3;function nh(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:zs.string().min(1).describe("From start_recording.")},outputSchema:D({sessionId:zs.string(),status:zs.string(),recordedSec:zs.number()}),annotations:Ui},async e=>{try{let r=re(),n=r.get(e.sessionId);if(!n)throw new l(`No session with id "${e.sessionId}".`);if(n.status==="paused")return v({sessionId:n.id,status:"paused",recordedSec:rh(rt(n.segments?.parts??[])),note:"Already paused."});let{ffprobe:o}=k(),i=await mm(r,n,{probe:s=>ue(s,{ffprobe:o})});return v({sessionId:n.id,status:"paused",recordedSec:rh(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 Hs}from"zod";var oh=t=>Math.round(t*1e3)/1e3;function ih(t){t.registerTool("resume_recording",{title:"Resume Recording",description:"Resume a paused recording (same target and settings).",inputSchema:{sessionId:Hs.string().min(1).describe("From start_recording.")},outputSchema:D({sessionId:Hs.string(),status:Hs.string(),recordedSec:Hs.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(n.status==="recording")return v({sessionId:n.id,status:"recording",recordedSec:oh(rt(n.segments?.parts??[])),note:"Already recording."});let{ffmpeg:o}=k(),i=await of(r,n,o);return nr("notice",`Recording ${n.id} resumed.`,{sessionId:n.id}),v({sessionId:n.id,status:"recording",recordedSec:oh(i.recordedSec),pid:i.record.pid,...i.capSec>0?{remainingSec:i.capSec}:{}})}catch(r){return E(r)}})}import{z as sh}from"zod";function ah(t){t.registerTool("list_video_devices",{title:"List Video Devices",description:"List DirectShow cameras for start_recording's webcam.device.",inputSchema:{},outputSchema:D({devices:sh.array(sh.string())}),annotations:he},async()=>{try{k();let e=await Yc(!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 Cn}from"zod";function ch(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:D({count:Cn.number().int(),sessions:Cn.array(D({id:Cn.string(),status:Cn.string(),outputPath:Cn.string(),alive:Cn.boolean()}))}),annotations:he},async()=>{try{let e=re().list().map(n=>({...n,alive:n.status==="recording"&&ze(n.pid)})),r=Xm();return v({count:e.length,sessions:e,...r.length?{armed:r}:{}})}catch(e){return E(e)}})}import{z as Pn}from"zod";import{existsSync as k$}from"node:fs";var E$={sessionId:Pn.string().min(1).describe("Session id returned by start_recording.")};function uh(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:E$,outputSchema:D({id:Pn.string(),status:Pn.string(),outputPath:Pn.string(),alive:Pn.boolean(),fileExists:Pn.boolean()}),annotations:he},async e=>{try{if(ys(e.sessionId)){let n=xs(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:k$(r.outputPath)})}catch(r){return E(r)}})}import{z as Be}from"zod";import{existsSync as _$,readFileSync as T$}from"node:fs";var lh=200,A$=5e3,R$={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(cc)).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(A$).optional().describe(`Most events to return (default ${lh}).`)};function ph(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:R$,outputSchema:D({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(!_$(r))throw new l(`No event log at ${r}. Record with start_recording events: true.`);let n=je(T$(r,"utf8")),o=fi(n,e),i=e.limit??lh,s=Yl(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 In}from"zod";var M$={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},C$={label:In.string().min(1).max(Hc).describe('e.g. "bug appears".'),sessionId:In.string().min(1).optional().describe("Recording to mark (a stopped one needs at)."),input:In.string().min(1).optional().describe("Or a video path (needs at)."),at:In.number().min(0).optional().describe("Video second (default: now, while recording).")};function dh(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:C$,outputSchema:D({count:In.number().int(),markersPath:In.string()}),annotations:M$},async e=>{try{if(!e.sessionId&&!e.input)throw new l("Pass sessionId or input.");if(e.sessionId){let i=us(re(),e.sessionId,e.label,e.at);return v({sessionId:e.sessionId,marker:{t:Math.round(i.t*1e3)/1e3,label:Ao(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),Qt(lr(r));let n=is(Le(r),{t:e.at,label:e.label,at:new Date().toISOString()}),o=pr(r,n);return v({marker:{t:Math.round(e.at*1e3)/1e3,label:Ao(e.label)},count:n.length,markersPath:o})}catch(r){return E(r)}})}import{z as ve}from"zod";import{extname as F$,join as Sh}from"node:path";import{existsSync as O$,mkdtempSync as D$,readFileSync as N$,rmSync as L$,writeFileSync as B$}from"node:fs";import{tmpdir as W$}from"node:os";import{existsSync as P$}from"node:fs";var qs="SCREENCAST_WHISPER_MODEL",mh=`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 ${qs}.`;function gr(t,e=process.env){let r=t??e[qs];if(!r||r.trim().length===0)throw new l("No whisper model given.",mh);if(!P$(r))throw new l(`Whisper model not found: ${r}`,mh);return r}function Fn(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 bh(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 fh=/(\d+):(\d{2}):(\d{2})[,.](\d{3})/,hh=t=>Number(t[1])*3600+Number(t[2])*60+Number(t[3])+Number(t[4])/1e3;function gh(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,`
|
|
333
321
|
`).split(/\n\s*\n/)){let o=n.split(`
|
|
334
|
-
`).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(
|
|
335
|
-
`);if(!p)continue;let f=e.index&&i>0&&/^\d+$/.test(o[i-1])?Number(o[i-1]):void 0;r.push({start:
|
|
336
|
-
${
|
|
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)}
|
|
337
325
|
${e.text}
|
|
338
326
|
`).join(`
|
|
339
|
-
`)}var
|
|
340
|
-
`).trim();if(!o)throw new l(`Translation ${n+1} is empty.`);if(o.length>
|
|
341
|
-
`)}})}function
|
|
342
|
-
${t}</script>`)}function Y$(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 K$(t){return t&&t.length>0?{markers:t.map(({t:e,label:r})=>({t:e,label:r}))}:{}}function Fh(t){t.registerResource("review-player",Bo,{title:"Recording review player",description:"Interactive player: scrub, trim, and draw redaction boxes on a recording.",mimeType:Js},async()=>({contents:[{uri:Bo,mimeType:Js,text:J$(),_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:D({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:kh},async n=>{try{k();let o=Y$(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,...K$(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(_h).optional().describe(`Frames on the even grid (default ${Ys}); scene-change frames come on top, up to as many again.`),width:lt.number().int().min(64).max(1280).optional().describe(`Frame width (default ${Ou}).`)},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=Th(s,n.maxFrames??Ys),c=Ue(".txt"),u,d;try{let b=await Nr(Ah(n.input,a,n.width??Ou,c),le(s),{signal:o.signal});u=Ch(b),d=Rh(q$(c)?Ih(c,"utf8"):"").slice(0,u.length)}finally{X$(c,{force:!0})}let[p]=d;if(!p)throw new l("ffmpeg returned no preview frames.");let f=Mh(d,a.count).flatMap(b=>{let y=d[b],$=u[b];return y&&$?[{frame:y,jpeg:$}]:[]}),m=p.timeSec,h=[];try{h=(await dr(n.input,o.signal)).markers.map(({t:b,label:y})=>({t:b,label:y}))}catch{}let g=f.map(({frame:b})=>Math.round((b.timeSec-m)*1e3)/1e3),w=f.flatMap(({frame:b},y)=>b.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:g,intervalSec:a.intervalSec,sceneFrames:w,markers:h})},...f.map(({jpeg:b})=>({type:"image",data:b.toString("base64"),mimeType:"image/jpeg"}))]}}catch(i){return E(i)}});e.disable();let r=t.server.oninitialized;t.server.oninitialized=()=>{r?.(),Eh(t.server.getClientCapabilities())&&e.enable()}}import{z as pt}from"zod";import{readFileSync as V$,rmSync as Q$}from"node:fs";var Ae=1280,Ks=8,Wo=20;function Z$(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 Vs(t){return Math.max(0,Math.min(Wo,Math.floor(t??Ks)))}async function Re(t,e=Ae,r=Ks){let n=t.slice(0,r);return{images:await He(n,async i=>{let s=Ue(".jpg");try{return await Z(Z$(i,s,e),3e4),{type:"image",data:V$(s).toString("base64"),mimeType:"image/jpeg"}}finally{Q$(s,{force:!0})}}),omitted:t.length-n.length}}var ek={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 Oh(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:ek,outputSchema:D({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 Ft(t,`Take a screenshot of ${It(e.target,o)}, saved to ${i}?`,r.signal),await Ot(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?ar(o):{},inlineImages:a.length},a)}catch(n){return E(n)}})}import{z as Ce}from"zod";import{join as Du}from"node:path";import{mkdirSync as tk,readdirSync as Dh,existsSync as rk,rmSync as nk}from"node:fs";var ok={input:Ce.string().min(1).describe("Path to the source video file."),mode:Ce.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:Ce.number().positive().optional().describe("Frames per second (mode fps)."),timestamps:Ce.array(Ce.number().nonnegative()).optional().describe("Seconds to grab a frame at (mode timestamps)."),sceneThreshold:Ce.number().gt(0).lt(1).optional().describe(`Mode scenes: change needed to count, 0-1 (default ${ht}).`),dedupe:Ce.boolean().optional().describe("Mode fps: drop near-duplicate frames (default false)."),outputDir:Ce.string().optional().describe("Optional folder for the frames (a relative path resolves under SCREENCAST_HOME/frames). Defaults to SCREENCAST_HOME/frames/<id>."),maxFrames:Ce.number().int().min(1).max(yc).optional().describe(`Frame cap (default ${_i}); fps is lowered to fit while still spanning the video.`),returnImages:Ce.boolean().optional().describe("Return the first maxInlineImages frames inline (default true)."),maxInlineImages:Ce.number().int().min(0).max(Wo).optional().describe(`Frames to embed inline (default ${Ks}); all are listed by path.`),maxImageWidth:Ce.number().int().min(16).optional().describe(`Max inline image width (default ${Ae}).`)};function Nh(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:ok,outputSchema:D({frameDir:Ce.string(),frameCount:Ce.number().int(),frames:Ce.array(Ce.string()),mode:Ce.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??_i;if(o&&e.timestamps.length>a)throw new l(`${e.timestamps.length} timestamps exceeds maxFrames (${a}). Pass fewer timestamps, or raise maxFrames (up to ${yc}).`);let c=i==="timestamps"?null:(await L(e.input)).durationSec,u=i==="fps"?Ti(c,e.fps,a):null,d=null,p=[];if(i==="scenes"){let{ffmpeg:w}=k(),b=await ne(w,tr(e.input,e.sceneThreshold??ht),le(c),{signal:r.signal});if(b.code!==0)throw new l(`Scene scan failed (exit ${b.code}): ${b.stderr.trim().slice(-400)}`);d=rr(b.stdout),p=mn(d,a)}let f=ln(e.outputDir,we("frames"))??Du(we("frames"),`sample-${ge()}-${be()}`);tk(f,{recursive:!0});let m=[],h=[];if(u){let w=S=>S.endsWith(".png"),b=new Set(Dh(f).filter(w)),y=bp(b,`${ge()}-${be()}`),$=un(f,`${y}%05d.png`);await Z(Ai(e.input,u.fps,$,a,e.dedupe===!0),le(c),{signal:r.signal}),m=Dh(f).filter(S=>w(S)&&S.startsWith(y)&&!b.has(S)).sort().map(S=>Du(f,S))}else{let w=i==="scenes"?p:e.timestamps,b=await He(w,async(y,$)=>{let S=Du(f,`frame_${String($).padStart(3,"0")}_${y}s.png`);return nk(S,{force:!0}),await Z(fn(e.input,y,S),6e4,{signal:r.signal}),S});for(let[y,$]of b.entries())rk($)?m.push($):h.push(w[y])}let g=e.returnImages===!1?{images:[],omitted:0}:await Re(m,e.maxImageWidth??Ae,Vs(e.maxInlineImages));return v({frameDir:f,frameCount:m.length,frames:m,mode:u?`fps=${u.fps}${e.dedupe?" (deduped)":""}`:d?`scenes (threshold ${e.sceneThreshold??ht})`:`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:g.images.length,...g.omitted>0?{inlineNote:`Embedded the first ${g.images.length} of ${m.length} frames inline; the other ${g.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(", ")}].`}:{}},g.images)}catch(n){return E(n)}})}import{z as Ve}from"zod";var ik={input:Ve.string().min(1).describe("Path to the source video."),count:Ve.number().int().min(1).max(wf).optional().describe(`Frames to tile (default ${Fo}).`),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 ${ht}).`),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 ${Oo}).`),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 Lh(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:ik,outputSchema:D({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=Zt(e.output,we("frames"),`${i}-${ge()}-${be()}.png`,e.overwrite),a=e.tileWidth??Oo,c;if(e.poster)await Z(yf(e.input,o,s,Math.max(a,1280)),le(o),{signal:r.signal}),c={outputPath:s,poster:!0};else{let d=e.count??Fo,p;if(e.mode==="scenes"){let m=await ne(n,tr(e.input,e.sceneThreshold??ht),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(rr(m.stdout),d)}else p=_s(o,d);let f=await Ts(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 kt}from"zod";import{rmSync as uk}from"node:fs";var Bh=320,sk=4,ak=1600,vt=8,jo=12;function Wh(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(Bh,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 Zs(t,e){if(!(t>0)||!(e>0))throw new l("Image has no size.");let r=Math.min(t,Math.max(Bh,Math.min(ak,Math.ceil(t/sk)))),n=Math.max(2,Math.round(e*r/t/2)*2);return{width:Math.max(2,Math.round(r/2)*2),height:n}}function ea(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 ck(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 $t(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??jo,s=Math.ceil(r/vt),a=Math.ceil(n/vt),c=new Uint8Array(s*a);for(let b=0;b<a;b++)for(let y=0;y<s;y++){let $=0,S=0;for(let C=b*vt;C<Math.min(n,(b+1)*vt);C++)for(let M=y*vt;M<Math.min(r,(y+1)*vt);M++){let R=C*r+M;$+=Math.abs(t[R]-e[R]),S++}$/S>i&&(c[b*s+y]=1)}let u=new Uint8Array(s*a),d=[];for(let b=0;b<c.length;b++){if(!c[b]||u[b])continue;let y={x0:1/0,y0:1/0,x1:-1,y1:-1,cells:0},$=[b];for(u[b]=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 N=X*s+j;c[N]&&!u[N]&&(u[N]=1,$.push(N))}}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,g=d.sort((b,y)=>y.cells-b.cells).slice(0,o.maxRegions??20).map(b=>{let y=b.x0*vt,$=b.y0*vt,S=Math.min(r,(b.x1+1)*vt)-y,C=Math.min(n,(b.y1+1)*vt)-$;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((b,y)=>b+y,0);return{meanDiff:ck(t,e),changedFraction:w/c.length,regions:g}}function jh(t,e,r){return{scaleX:t.width/e.width,scaleY:t.height/e.height,pixelThreshold:r}}var Qs=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=$t(this.previous,e,this.width,this.height,this.opts).regions,n=r.length>0?r:$t(this.anchor,e,this.width,this.height,this.opts).regions;return this.previous=e,n.length>0&&(this.anchor=e),n}};function Uo(t,e){return["-v","error","-i",t,"-frames:v","1","-vf",`scale=${e.width}:${e.height}:flags=area,format=gray`,"-f","rawvideo","-"]}function Uh(t,e,r,n){return["-v","error","-probesize","32","-analyzeduration","0","-f","gdigrab","-framerate",String(Math.round(n*1e3)/1e3),...Si(t,e),"-vf",`scale=${r.width}:${r.height}:flags=area,format=gray`,"-flush_packets","1","-f","rawvideo","-"]}function zh(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 zo(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 Hh(t){let e=t.match(/All:([\d.]+)/);return e?Number(e[1]):null}import{tmpdir as lk}from"node:os";import{join as pk}from"node:path";var dk={a:kt.string().min(1).describe("Before image (or video: first frame)."),b:kt.string().min(1).describe("After image (or video); scaled to a's size."),pixelThreshold:kt.number().min(0).max(255).optional().describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${jo}).`),returnImage:kt.boolean().optional().describe("Return b inline with changes outlined (default true).")};function Gh(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:dk,outputSchema:D({identical:kt.boolean(),ssim:kt.number().nullable(),meanDiff:kt.number(),changedFraction:kt.number(),regions:kt.array(kt.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=Zs(n.width,n.height),[s,a,c]=await Promise.all([Nr(Uo(e.a,i),3e4,{signal:r.signal}),Nr(Uo(e.b,i),3e4,{signal:r.signal}),ne(k().ffmpeg,zh(e.a,e.b,i),3e4,{signal:r.signal})]),u=$t(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=pk(lk(),`screencast-diff-${ge()}-${be()}.png`);try{await Z(zo(e.b,u.regions,p),3e4,{signal:r.signal}),d.push(...(await Re([p],Ae,1)).images)}finally{uk(p,{force:!0})}}return v({identical:u.regions.length===0,ssim:Hh(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 mk=t=>new Promise(e=>setTimeout(e,t));async function qh(t){let e=t.now??Date.now,r=t.sleep??mk,n=e(),o=await t.grab(),i=new Qs(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=$t(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 fk=t=>new Promise(e=>setTimeout(e,t));async function Xh(t){let e=t.now??Date.now,r=t.sleep??fk,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($t(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 ta=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 ra}from"node:path";import{mkdtempSync as hk,rmSync as Ho}from"node:fs";import{tmpdir as Jh}from"node:os";var gk={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 ${jo}).`),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 Yh(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:gk,outputSchema:D({outcome:Te.string(),mode:Te.string(),elapsedSec:Te.number(),regions:Te.array(Te.unknown()),origin:D({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 Ft(t,`Watch ${It(e.target,p)} for up to ${i/1e3} s, until it ${f}?`,r.signal);let m=hk(ra(Jh(),"screencast-wait-")),h=0,g=async()=>{let x=ra(m,`still-${h++}.png`);return await Ot(c,x,o),x},w=ea(u,d);if(o==="wgc")try{let x=await L(await g());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 Ho(m,{recursive:!0,force:!0}),x}let b=Zs(w.width,w.height),y=jh(w,b,e.pixelThreshold),$=new ta,S=new AbortController,C=o==="gdigrab"?Ni(Uh(u,d,b,1e3/a),b.width*b.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 g();try{return await Nr(Uo(x,b),3e4,{signal:r.signal})}finally{Ho(x,{force:!0})}},R=o==="gdigrab"?async()=>{}:void 0,P,j=null,X=0;try{if(n==="text"){let x=await Xh({grab:M,read:async()=>{let q=await g(),[H]=await ct([q],m,r.signal);return Ho(q,{force:!0}),H?wt(H.lines,e.text,e.regex===!0):[]},width:b.width,height:b.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 qh({grab:M,mode:n,width:b.width,height:b.height,diff:y,timeoutMs:i,settleMs:s,intervalMs:a,signal:r.signal,...R?{sleep:R}:{}});X=Date.now()}finally{S.abort(),await C,Ho(m,{recursive:!0,force:!0})}let{outcome:N,regions:se,everChanged:ee,startedAt:J}=P,ie={outcome:N,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:se,origin:{x:w.x,y:w.y},...o==="wgc"?{backend:o}:{},...p?ar(p):{}},ae=[];if(e.returnImage!==!1&&N!=="cancelled"){let x=e.keep?ra(we("screenshots"),`wait-${ge()}-${be()}.png`):ra(Jh(),`screencast-wait-${ge()}-${be()}.png`);try{o==="wgc"?await Ot(c,x,"wgc"):await Z($i(u,x,d),6e4,{signal:r.signal}),e.keep&&(ie.screenshotPath=x),ae.push(...(await Re([x],Ae,1)).images)}finally{e.keep||Ho(x,{force:!0})}}return v(ie,ae)}catch(n){return E(n)}})}import{z as qe}from"zod";import{extname as Kh,join as On}from"node:path";import{mkdtempSync as bk,rmSync as wk}from"node:fs";import{tmpdir as yk}from"node:os";var Vh=new Set([".png",".jpg",".jpeg",".bmp",".gif",".webp",".tif",".tiff"]),na=300,xk={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(ws).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 Qh(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:D({imageSize:D({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=bk(On(yk(),"screencast-ocr-"));try{if(e.scanEverySec!==void 0)return await Sk(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?On(we("screenshots"),`ocr-${ge()}-${be()}.png`):On(n,"capture.png");let g=e.backend??"gdigrab";await Ft(t,`Capture ${It(e.target,h.window)} once to read the text on it?`,r.signal),await Ot(h,o,g),h.window&&(i=ar(h.window));let w=ea(h.target,h.monitors);s=g==="wgc"&&h.window?.client?h.window.client:{x:w.x,y:w.y}}else{F(e.input);let h=Vh.has(Kh(e.input).toLowerCase());o=On(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?wt(c,e.query,e.regex===!0):[],f=[];if(e.returnImage??!!e.query){let h=On(n,"shown.png");await Z(zo(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:gs(p,{width:u,height:d})}:{}}:{},text:c.map(h=>h.text).join(`
|
|
343
|
-
`),lines:c.slice(0,
|
|
344
|
-
`);return
|
|
345
|
-
`)||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
|
|
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,`
|
|
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,`
|
|
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=`
|
|
346
334
|
$ErrorActionPreference = 'Stop'
|
|
347
335
|
$null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
|
|
348
336
|
$e = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
|
|
349
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
|
|
350
|
-
`;async function br(){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(kk,"OCR languages",{timeoutMs:ir(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 Ek=["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"];function rg(t=process.env){return Object.fromEntries(Ek.map(e=>{let r=t[e];return[e,r&&r.trim().length>0?r:null]}))}var ng=[{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 Bu=8,Ck={input:wr.string().optional().describe("Recording path."),sessionId:wr.string().optional().describe("Or a stopped session id."),sceneThreshold:wr.number().gt(0).lt(1).optional().describe(`Change starting a segment (default ${Ru}).`),maxFrames:wr.number().int().min(1).max(If).optional().describe(`Keyframes to OCR (default ${Mu}).`),transcript:wr.string().optional().describe("An .srt, or 'whisper' to transcribe. Default: <video>.srt if any."),force:wr.boolean().optional().describe("Re-OCR despite a matching cached index.")};function og(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:Ck,outputSchema:D({indexPath:wr.string(),segments:wr.number()}),annotations:I},async(e,r)=>{let n=Ak(Lu(Mk(),"screencast-index-"));try{let{ffmpeg:o}=k(),i=await Us(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??Ru,u=e.maxFrames??Mu,d=we("edits"),p=Of(i.path,d),f=Ws(i.path),m=So(r),h=[],g=e.force?null:Ns(i.path,d,f),w=g?zr(g):null,b=null,y=async()=>b??=process.platform==="win32"&&(await br()).available,$=Df(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,tr(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=Bf(Lf(rr(J.stdout),a,u),a),ae=ie.map(()=>[]);if(M=await y(),M)for(let q=0;q<ie.length;q+=Bu){r.signal.throwIfAborted();let H=ie.slice(q,q+Bu),G=(await He(H,async(te,T)=>{let _=Lu(n,`key_${q+T}.png`);return await Z(fn(i.path,Bs(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)=>ae[G[T].at]=te.lines.map(_=>_.text)),C+=Q.length,m?.(.1+.85*Math.min(ie.length,q+Bu)/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:ae[H]??[]}));S=M?Wf(x):x}S=Nf(S);let R=i.eventsPath?jf(je(Nn(i.eventsPath,"utf8"))):[];S=Ur(S,R,"events"),S=Ur(S,Uf(i.markers),"markers");let P=yt(i.path);if(Dn(P)){let J=Tn(Nn(P,"utf8")),{busy:ie}=_n(J),ae=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)`}});ae.length&&(S=Ur(S,[...S.flatMap(x=>x.events??[]),...ae],"events"))}let j=Nt(i.path);if(Dn(j)){let J=vs(Nn(j,"utf8")),ie=Oe(J.map(ae=>`${ae.source}: ${ae.line}`),Ge);S=Ur(S,J.map((ae,x)=>({t:ae.t,text:ie[x]??""})),"logs")}let X=await Pk(e.transcript,i.path,s.audioCodec!==null,a,r.signal,h);if(X!==null)S=Ur(S,zf(X),"transcript");else if($&&w){let J=w.segments.flatMap(ie=>ie.transcript??[]);S=Ur(S,J,"transcript")}let N={version:Au,video:i.path,fingerprint:f,durationSec:a,createdAt:new Date().toISOString(),sceneThreshold:c,maxFrames:u,framesRead:C,ocr:M,segments:S};Tk(Lu(p,".."),{recursive:!0}),Hf(p,N);let se=Cu(i.path);if(se!==p&&Dn(se)){let J=zr(se);J&&Os(J,i.path,f)&&Wu(se,{force:!0})}m?.(1);let ee=J=>S.reduce((ie,ae)=>ie+(ae[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{Wu(n,{recursive:!0,force:!0})}})}async function Pk(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=gr(void 0),u=Ue(".srt");try{return await Z(Fn(e,c,u),le(n),{signal:o}),Dn(u)?ut(We(Nn(u,"utf8"))):[]}finally{Wu(u,{force:!0})}}if(t!==void 0){if(!Dn(t))throw new l(`Transcript not found: ${t}`);return ut(We(Nn(t,"utf8")))}let s;try{s=Rk(_k(e))}catch{return null}let a=Ls(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(Nn(a.path,"utf8"))):null}import{z as Wt}from"zod";import{join as ig}from"node:path";import{existsSync as sg,mkdtempSync as Ik,rmSync as Fk}from"node:fs";import{tmpdir as Ok}from"node:os";var Dk=480,Nk={input:Wt.string().optional().describe("Recording path."),sessionId:Wt.string().optional().describe("Or a stopped session id."),query:Wt.string().min(1).describe("Text; tolerates OCR misreads."),regex:Wt.boolean().optional().describe("query is a regex."),limit:Wt.number().int().min(1).max(Ff).optional().describe(`Max hits (default ${Fs}).`),images:Wt.number().int().min(0).max(Wo).optional().describe("Thumbnails of the top N hits (default 0).")};function ag(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:Nk,outputSchema:D({total:Wt.number(),hits:Wt.array(Wt.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=qf(Ie()).flatMap(g=>{let w=zr(g);return w?[{indexPath:g,index:w}]:[]}),m=Xf(f,e.query,{regex:e.regex===!0,limit:e.limit}),h=m.recordings.map(g=>({...g,...sg(g.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 Us(e),o=Ws(n.path),i=Ns(n.path,we("edits"),o),s=i?zr(i):null;if(!i||!s)throw new l(`No index for ${n.path}.`,"Run index_recording on it first.");let a=!js(s.fingerprint,o),{hits:c,total:u}=Pu(s,e.query,{regex:e.regex===!0,limit:e.limit,video:n.path,fingerprint:o}),d=Math.min(Vs(e.images??0),c.length),p=[];if(d>0){k();let f=Ik(ig(Ok(),"screencast-search-"));try{let m=[];for(let[h,g]of c.slice(0,d).entries()){let w=g.t===g.start?Bs(g):g.t,b=ig(f,`hit_${h}.png`);await Z(fn(n.path,w,b),6e4,{signal:r.signal}),sg(b)&&m.push(b)}p=(await Re(m,Dk,d)).images}finally{Fk(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 yr}from"zod";var Lk={input:yr.string().min(1).describe("Path to the media file to probe.")};function cg(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:Lk,outputSchema:D({input:yr.string(),durationSec:yr.number().nullable(),width:yr.number().nullable(),height:yr.number().nullable(),fps:yr.number().nullable(),videoCodec:yr.string().nullable(),audioCodec:yr.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 Bk}from"node:path";var Wk={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 ug(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:Wk,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.exact===!1?Bk(e.input)||".mp4":V(e.input),o=B(e.output,"trim",n,{overwrite:e.overwrite,anyContainer:e.exact===!1}),i=yp(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 W(i,{output:o,durationSec:c,extra:r}),v({outputPath:o})}catch(n){return E(n)}})}import{z as ua}from"zod";import{extname as Xk,resolve as Jk}from"node:path";import{writeFileSync as Yk,rmSync as Kk}from"node:fs";var jk=1920,Uk=1080,lg=30,pg=48e3,Ln=1,ju="standard";function Uu(t){return Math.round(t*1e3)/1e3}function dg(t){return t.width!==void 0&&er(t.width,"width"),t.height!==void 0&&er(t.height,"height"),{w:t.width??jk,h:t.height??Uk}}function zk(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 Hk(t){return`aresample=${t},aformat=sample_fmts=fltp:channel_layouts=stereo`}function Gk(t,e){let r=[],n=0;for(let[o,i]of t.slice(0,-1).entries())n+=i,r.push(Math.max(0,Uu(n-(o+1)*e)));return r}function qr(t){return t.videoDurationSec??t.durationSec}function mg(t,e,r,n,o={},i=[!1,!1]){let s=gc(o.transition??"fade"),a=o.duration??Ln;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 Go([t,e],r,n,{...o,transition:s},i)}function Go(t,e,r,n={},o=[]){if(t.length<2)throw new l("assemble_highlights requires at least two clips.");let{w:i,h:s}=dg(n),a=n.fps??lg,c=n.audioRate??pg,u=n.transition??"cut",d=n.duration??Ln,p=t.length,f=zk(i,s,a),m=Hk(c),h=o.some(Boolean),g=[];for(let b=0;b<p;b++)if(g.push(`[${b}:v]${f}[v${b}]`),!!h)if(o[b]){let y=e[b]??Number.NaN,$=Number.isFinite(y)&&y>0?`,apad,atrim=duration=${Uu(y)}`:"";g.push(`[${b}:a]${m}${$}[a${b}]`)}else{let y=e[b]??Number.NaN;if(!Number.isFinite(y)||y<=0)throw new l(`clip ${b} has no audio track and its duration is unknown, so a matching silent track cannot be generated.`);g.push(`anullsrc=channel_layout=stereo:sample_rate=${c}:d=${y}[a${b}]`)}let w=[];if(u==="cut")if(h){let b=t.map((y,$)=>`[v${$}][a${$}]`).join("");g.push(`${b}concat=n=${p}:v=1:a=1[vout][aout]`),w.push("-map","[vout]","-map","[aout]")}else{let b=t.map((y,$)=>`[v${$}]`).join("");g.push(`${b}concat=n=${p}:v=1:a=0[vout]`),w.push("-map","[vout]")}else{if(gc(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 b=e.findIndex(S=>!Number.isFinite(S)||S<=d);if(b!==-1)throw new l(`clip ${b} (${e[b]}s) must be longer than the ${d}s ${u} transition. Use a shorter transition or trim fewer frames.`);let y=Gk(e,d),$="v0";for(let S=1;S<p;S++){let C=S===p-1?"vout":`vx${S}`;g.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}`;g.push(`[${S}][a${C}]acrossfade=d=${d}[${M}]`),S=M}w.push("-map","[aout]")}}return["-y",...t.flatMap(b=>["-i",b]),"-filter_complex",g.join(";"),...w,...Se({quality:n.quality??ju,audio:h?"aac":"none",faststart:!0}),r]}var zu=3;function fg(t,e,r,n={}){let{w:o,h:i}=dg(n),s=n.duration??zu,a=n.fps??lg,c=Ne(n.bg??"black","bg"),u=Ne(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 hg(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,g]of[[s,"musicVolume"],[a,"fadeIn"],[c,"fadeOut"]])if(!Number.isFinite(h)||h<0)throw new l(`${g} must be a non-negative number.`);let u=i.duck??!1,d=Math.max(0,Uu(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 Bn=["16:9","9:16","1:1","4:5"],sa=["pad","crop"],Wn={"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 aa(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 gg(t,e,r,n="pad",o=ju){let i=Wn[r];if(!i)throw new l(`Unknown aspect "${r}".`);return["-y","-i",t,"-vf",`${aa(i.w,i.h,n)},format=yuv420p`,...Se({quality:o,audio:"copy",faststart:!0}),e]}var ca=["youtube","instagram_reel","tiktok","x","square","steam_trailer","vertical_reel"],Hu={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 qk(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 Gu(t,e="pad",r=""){let n=Hu[t];if(!n)throw new l(`Unknown platform "${t}".`);let o=Wn[n.aspect],i=n.blurFill?qk(o.w,o.h,r):aa(o.w,o.h,e),s=n.loudness?`loudnorm=I=-14:TP=-1:LRA=11,aresample=${n.loudness.sampleRate??pg}`: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 bg(t,e,r,n="pad"){let{vf:o,af:i,encode:s}=Gu(r,n);return["-y","-i",t,"-vf",o,...i?["-af",i]:[],...s,e]}var Vk={inputs:ua.array(ua.string().min(1)).min(2).describe("Video paths to join, in order."),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 wg(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:Vk,outputSchema:Y,annotations:I},async(e,r)=>{try{k();let n=e.inputs.map(m=>Jk(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=Sp(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,g=Go(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(g,{output:m,durationSec:c,extra:r}),v({outputPath:m,inputCount:n.length,mode:"reencode",reason:u})}let d=Xk(i)||".mp4",p=B(e.output,"concat",d,{overwrite:e.overwrite,anyContainer:!0}),f=Ue(".txt");Yk(f,xp(n));try{await W(hn(f,p),{output:p,durationSec:c,extra:r})}finally{Kk(f,{force:!0})}return v({outputPath:p,inputCount:n.length,mode:"copy"})}catch(n){return E(n)}})}import{z as jn}from"zod";var Qk={input:jn.string().min(1).describe("Path to the source media."),format:jn.enum(["mp4","gif","webm"]).describe("mp4 (H.264), webm (VP9), or gif (palette)."),fps:jn.number().positive().optional().describe("gif only: fps (default 12)."),width:jn.number().positive().optional().describe("gif only: width in px (default 720)."),output:jn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:jn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function yg(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:Qk,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=vp(e.input,o,n,{fps:e.fps,width:e.width});return await W(i,{output:o,durationSec:await ue(e.input),extra:r}),v({outputPath:o,format:n})}catch(n){return E(n)}})}import{z as jt}from"zod";var la=12,pa=960,xr=1e7,xg=5;function Sg(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 vg(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 $g(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 Zk,dirname as eE,extname as tE,join as rE}from"node:path";import{renameSync as nE,rmSync as oE,statSync as iE}from"node:fs";async function Un(t,e,r,n){let o=r.format??"gif",i=r.maxBytes??xr,s=await ue(t),a=r.duration??(s!==null?s-(r.start??0):null),c=Sg(o,r.fps??la,r.width??pa),u=tE(e),d=f=>rE(eE(e),`${Zk(e,u)}.try${f}${u}`),p=[];try{let f=0;for(;f!==null&&p.length<xg;){let g=c[f];if(!g)break;let w=d(p.length),b={start:r.start,duration:r.duration};await W($g(t,w,o,g,b),{output:w,durationSec:a,extra:n});let y=iE(w).size;if(p.push({path:w,size:y,settings:g}),y<=i)break;f=vg(f,y,i,c.length)}let m=p.find(g=>g.size<=i),h=m??p.reduce((g,w)=>w.size<g.size?w:g);return nE(h.path,e),{outputPath:e,format:o,sizeBytes:h.size,maxBytes:i,withinBudget:h.size<=i,settings:h.settings,attempts:p.map(g=>({...g.settings,sizeBytes:g.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)oE(f.path,{force:!0})}}var sE={input:jt.string().min(1).describe("Path to the source video."),format:jt.enum(["gif","webp"]).optional().describe("gif (default) or webp (usually much smaller)."),maxBytes:jt.number().int().min(1e4).optional().describe(`Size budget in bytes (default ${xr}, under GitHub's 10 MB image limit).`),fps:jt.number().positive().max(30).optional().describe(`Starting frame rate (default ${la}).`),width:jt.number().int().min(64).max(1920).optional().describe(`Starting width in px (default ${pa}).`),start:jt.number().nonnegative().optional().describe("Start second."),duration:jt.number().positive().optional().describe("Seconds to export (default: to the end)."),output:jt.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:jt.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function kg(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:sE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.format??"gif",o=e.maxBytes??xr,i=B(e.output,"anim",`.${n}`,{overwrite:e.overwrite,anyContainer:!0});return v(await Un(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 aE={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 Eg(t){t.registerTool("crop",{title:"Crop Video",description:"Crop a video to a pixel rectangle; one running off the frame is rejected.",inputSchema:aE,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=$p(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 qo}from"zod";var cE={input:qo.string().min(1).describe("Path to the source video."),width:qo.number().int().positive().optional().describe("Target width in px. Omit to derive from height (keeps aspect)."),height:qo.number().int().positive().optional().describe("Target height in px. Omit to derive from width (keeps aspect)."),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 _g(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:cE,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=Ep(e.input,o,{width:e.width,height:e.height});return await W(i,{output:o,durationSec:await ue(e.input),extra:r}),v({outputPath:o})}catch(n){return E(n)}})}import{z as Yo}from"zod";import{z as da}from"zod";function Et(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 Et(e)}var Yr=2,Xo=.4,zn=200;function ma(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 Tg(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 fa(t,e){return Tg(t,/freeze_start:\s*([\d.]+)/,/freeze_end:\s*([\d.]+)/,e)}function ha(t,e){return Tg(t,/silence_start:\s*([\d.]+)/,/silence_end:\s*([\d.]+)/,e)}function ga(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 ba(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>zn)throw new l(`Too many idle stretches (${t.length}); raise minIdleSec.`);let e=Et(t.map(n=>`between(t,${n.start},${n.end})`)),r=Et(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,wa=da.object({start:da.number().min(0),end:da.number().positive(),factor:da.number().gt(1).max(Jr)}),Jo=8;function ya(t,e){if(t.length===0)throw new l("segments needs at least one range.");if(t.length>zn)throw new l(`Too many ranges (${t.length}); at most ${zn}.`);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 xa(t,e){if(t.length===0)throw new l("Nothing to speed up.");let r=s=>Number((1-1/s.factor).toFixed(6)),n=Et(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=Et(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 Sa(t,e,r,n){let o=xa(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 va(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 uE={input:Yo.string().min(1).describe("Path to the source video."),factor:Yo.number().positive().optional().describe("Whole clip: >1 faster, <1 slower."),segments:Yo.array(wa).min(1).optional().describe("Or fast-forward just these ranges (audio shortened, not pitched)."),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 Ag(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:uE,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=ya(e.segments,o),f=Kr(p);return await W(Sa(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=_p(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 lE={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 Rg(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:lE,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 ue(e.input),a=Tp(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 fE,rmSync as hE,writeFileSync as gE}from"node:fs";import{tmpdir as bE}from"node:os";import{join as Fg}from"node:path";var Pg=["side_by_side","stack","grid"],$a=2,ka=9,Mg=3840,pE=1080,Cg=t=>Math.max(2,Math.round(t/2)*2);function dE(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 mE(t,e){let r=Math.min(t.height,pE),n=t.width*r/t.height,o=Math.min(1,Mg/(n*e.cols),Mg/(r*e.rows));return n*=o,r*=o,{width:Cg(n),height:Cg(r)}}function Xu(t,e){let r=t.map(n=>Math.max(0,n.durationSec-n.skipSec));return e==="longest"?Math.max(...r):Math.min(...r)}function Ig(t,e,r){let n=t.length;if(n<$a||n>ka)throw new l(`compose takes ${$a} to ${ka} inputs.`);let o=t[0],i=dE(r.layout,n),s=mE(o,i),a=Xu(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 g=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`+(g>.001?`,tpad=stop_mode=clone:stop_duration=${g.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 wE={inputs:ot.array(ot.object({path:ot.string().min(1),label:ot.string().min(1).max(80).optional()})).min($a).max(ka).describe('Videos in reading order, each with an optional label (e.g. "Before").'),layout:ot.enum(Pg).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 Og(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:wE,outputSchema:Y,annotations:I},async(e,r)=>{let n=fE(Fg(bE(),"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 g=0;if(e.alignMarker){let b=Le(m.path).find(y=>y.label===e.alignMarker);if(!b)throw new l(`Input ${f} has no marker "${e.alignMarker}".`,"Add one with add_marker, or leave alignMarker out.");g=b.t}let w;if(m.label){let b=St(m.label);b.warning&&i.push(b.warning);let y=Fg(n,`label${f}.txt`);gE(y,m.label),w={textFile:y,fontFile:b.fontFile}}o.push({path:m.path,width:h.width,height:h.height,durationSec:h.durationSec,hasAudio:h.audioCodec!==null,skipSec:g,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=Ig(o,u,{layout:e.layout??"side_by_side",endWith:s,audio:a,fps:Math.min(60,Math.round(c))}),p=Xu(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{hE(n,{recursive:!0,force:!0})}})}import{z as Vr}from"zod";import{existsSync as SE,mkdtempSync as vE,readFileSync as $E,rmSync as kE,writeFileSync as EE}from"node:fs";import{tmpdir as _E}from"node:os";import{join as jg}from"node:path";var Ng=["cpu","sysCpu","rssMB","sysMem"],Lg=["top_left","top_right","bottom_left","bottom_right"],yE=120,Ju={cpu:"App CPU %",sysCpu:"CPU %",rssMB:"App memory MB",sysMem:"Memory %"};function Bg(t,e,r,n=yE){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 xE(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 Dg=t=>Math.max(2,Math.round(t/2)*2);function Wg(t,e,r,n){let o=Dg(n.width),i=Dg(n.height);if(o>n.videoWidth||i>n.videoHeight)throw new l("The chart is larger than the video.");let s=xE(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>=au;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,g=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,b=`color=c=white:s=2x${i-a}:d=${p}:r=30`;return["-y","-i",t,"-filter_complex",`${w}[c];${b}[p];[c][p]overlay=x='min(${o-2},t/${p}*${o})':y=${a}:shortest=1[g];[0:v][g]overlay=x=${h}:y=${g}:shortest=1[v]`,"-map","[v]","-map","0:a?",...Se({quality:n.quality??"standard",audio:n.hasAudio?"copy":"omit",faststart:!0}),e]}var TE={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(Ng).optional().describe("Default cpu (the app's) if sampled, else sysCpu."),corner:Vr.enum(Lg).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 Ug(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:TE,outputSchema:Y,annotations:I},async(e,r)=>{let n=vE(jg(_E(),"screencast-perf-"));try{k(),F(e.input);let o=e.perf??yt(e.input);if(!SE(o))throw new l(`No performance track at ${o}.`,"Record with start_recording perf: true, or pass perf.");let i=Tn($E(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=Bg(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=St(Ju[a]),p=jg(n,"label.txt");EE(p,Ju[a]);let f=B(e.output,"perf",V(e.input),{overwrite:e.overwrite}),m=Wg(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{kE(n,{recursive:!0,force:!0})}})}import{z as Hn}from"zod";import{existsSync as AE,readFileSync as RE,writeFileSync as ME}from"node:fs";var Yu=2e3,CE={input:Hn.string().min(1).describe("The .srt to translate (e.g. from transcribe)."),language:Hn.string().regex(/^[a-z]{3}$/).optional().describe('With translations: ISO 639-2 code, e.g. "spa".'),translations:Hn.array(Hn.string().max(Gs)).max(Yu).optional().describe("One translated string per cue, in order. Omit to get the cues to translate."),output:Hn.string().optional().describe("Default: <input>.<language>.srt."),overwrite:Hn.boolean().optional().describe("Allow replacing an existing output file.")};function zg(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:CE,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(RE(e.input,"utf8"));if(r.length===0)throw new l(`No cues in ${e.input}.`);if(r.length>Yu)throw new l(`${r.length} cues; at most ${Yu} 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=yh(r,e.translations.map(i=>i.replace(/\s+\/\s+/g,`
|
|
351
|
-
`))),o=e.output??xh(e.input,e.language);if(!/\.srt$/i.test(o))throw new l("output must end in .srt.");if(Qt(o),AE(o)){if(!e.overwrite)throw new l(`${o} already exists.`,"Pass overwrite: true to replace it.");mc(o)}return ME(o,nt(n)),v({outputPath:o,language:e.language,count:n.length})}catch(r){return E(r)}})}import{z as Ta}from"zod";import{join as IE}from"node:path";import{mkdtempSync as FE,rmSync as OE}from"node:fs";import{tmpdir as DE}from"node:os";import{z as xe}from"zod";var Gn=(t,e)=>{if(!Number.isFinite(t)||t<0)throw new l(`${e} must be a non-negative number.`);return Math.round(t)};function Ku(t){let e=Mi(t.from,t.to);return e?`:enable='${e}'`:""}function Hg(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 Gg(t,e){let{length:r,thickness:n,angle:o}=Hg(t),i=Ne(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 Qu(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=Ne(c.color??"red"),f=c.fill?"fill":String(Math.max(1,Math.round(c.thickness??4)));s.push(`${a}drawbox=x=${Gn(c.x,"x")}:y=${Gn(c.y,"y")}:w=${Gn(c.width,"width")}:h=${Gn(c.height,"height")}:color=${p}:t=${f}${Ku(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=Ne(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=${Gn(c.x,"x")}:y=${Gn(c.y,"y")}:fontsize=${m}:fontcolor=${f}${h}${Ku(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}=Hg(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${Ku(c)}${d}`)}a=d}),{steps:s,out:a,extraInputs:i}}function qg(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}=Qu(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 Vu={from:xe.number().nonnegative().optional(),to:xe.number().positive().optional(),color:xe.string().optional()},Sr=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, ...)."),Ea=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."),...Vu}),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)."),...Vu}),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)."),...Vu})]);import{join as Xg}from"node:path";import{writeFileSync as PE}from"node:fs";function Zu(t,e){let r={fontFiles:[],fallbackFonts:[],warnings:[]};return t.forEach((n,o)=>{if(n.type!=="text"){r.fontFiles.push(null);return}let i=St(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 _a(t,e,r="",n){let o=Zu(t,n),i=t.map((a,c)=>{if(a.type!=="text")return null;let u=Xg(e,`${r}text_${c}.txt`);return PE(u,a.text),u}),s=[];for(let[a,c]of t.entries()){if(c.type!=="arrow"){s.push(null);continue}let u=Xg(e,`${r}arrow_${a}.png`);await Z(Gg(c,u),3e4),s.push(u)}return{fontFile:Lt("bold"),textFiles:i,arrowFiles:s,...o}}var NE={input:Ta.string().min(1).describe("Path to the source video or image (png/jpg; from/to are ignored for an image)."),items:Ta.array(Ea).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:Sr,output:Ta.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ta.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Jg(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:NE,outputSchema:Y,annotations:I},async(e,r)=>{try{k(),F(e.input);let n=e.items,{still:o,ext:i}=Pi(e.input,e.output),s=B(e.output,"callout",i,{overwrite:e.overwrite,anyContainer:!0}),a=FE(IE(DE(),"screencast-callout-"));try{let c=await _a(n,a,"",e.fontFile),u=qg(e.input,s,n,c,void 0,o);return await W(u,{output:s,durationSec:o?null:await ue(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{OE(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as Vo}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 Ut}from"zod";import{existsSync as LE,readFileSync as BE,writeFileSync as WE}from"node:fs";import{join as jE}from"node:path";var UE=["bottom","bottom-left","bottom-right","top","top-left","top-right"],el=1.2,zE=.5,Yg=8,Kg=100,Vg="Typing\u2026",HE=new Set(["Ctrl","Alt","Shift","Win"]),GE=/^(?:[A-Z0-9]|F\d{1,2}|Enter|Tab|Esc|Space|Backspace|Delete|Insert|Left|Up|Right|Down|Home|End|PageUp|PageDown|[=\-,./`[\];'\\])$/;function qE(t,e="shortcuts"){let r=t.split("+"),n=r.pop();return n===void 0||r.length===0||!GE.test(n)||!r.every(o=>HE.has(o))||new Set(r).size!==r.length?null:[...r,e==="masked"?"\u2026":n].join(" + ")}var XE={left:"Click",right:"Right click",middle:"Middle click",x1:"Back button",x2:"Forward button"},Aa=t=>Math.round(t*1e3)/1e3;function JE(t,e={}){let r=e.lingerSec??el;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=qE(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=XE[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<=zE&&Math.abs(a.x-(u.x??a.x))<=Yg&&Math.abs(a.y-(u.y??a.y))<=Yg){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:Vg,base:Vg,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:Aa(a.from),to:Aa(d),label:a.label,kind:a.kind})}),s}function Ra(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>Kg)throw new l(`${e.size} different badges is more than ${Kg}; trim the video or turn off keys or clicks.`);return[...e.values()]}function YE(t,e){return t.flatMap(r=>{let n=e(r.from,r.to);return n&&n[1]-n[0]>=.05?[{...r,from:Aa(n[0]),to:Aa(n[1])}]:[]})}function Qg(t,e){return YE(t,(r,n)=>Wr(r,n,e))}function KE(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 tl(t,e,r,n,o,i){if(t.length===0)throw new l("No badges to draw.");let s=KE(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=Ne(r.color??"white"),m=[],h=o;return t.forEach((g,w)=>{let b=e.textFiles[g.label];if(!b)throw new l(`Internal: no text file for badge "${g.label}".`);let y=Et(g.windows.map(([S,C])=>`between(t,${S},${C})`)),$=`[${i}k${w}]`;m.push(`${h}drawtext=fontfile=${ye(e.fontFile)}:textfile=${ye(b)}: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 Zg(t,e,r,n,o,i,s="standard"){let{steps:a,out:c}=tl(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 Ma={events:Ut.string().optional(),clicks:Ut.boolean().optional(),typing:Ut.boolean().optional(),keys:Ut.enum(["shortcuts","masked"]).optional(),lingerSec:Ut.number().positive().max(10).optional(),position:Ut.enum(UE).optional(),size:Ut.number().min(8).max(400).optional(),color:Ut.string().optional(),fontFile:Ut.string().min(1).optional()};function Ca(t,e,r){let n=e??$e(t).jsonl;if(!LE(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(BE(n,"utf8"));return{badges:JE(o,r),shortcutsLogged:o.filter(i=>i.type==="key").length,path:n}}function Ko(t,e,r="",n){let o=St(t.join(" "),{weight:"bold",fontFile:n}),i={};return t.forEach((s,a)=>{if(e===null){i[s]=`<badge ${a}>`;return}let c=jE(e,`${r}badge_${a}.txt`);WE(c,s),i[s]=c}),{fontFile:o.fontFile,textFiles:i,...o.fallback&&{fallbackFont:o.fontFile},warnings:o.warning?[o.warning]:[]}}var vr=Ma,t_={input:Vo.string().min(1).describe("Path to the recording."),events:vr.events.describe("Event log (default: the input's .events.jsonl)."),clicks:vr.clicks.describe("Show clicks (default true)."),typing:vr.typing.describe('Show typing as "Typing\u2026" (default true).'),keys:vr.keys.describe("shortcuts (default): the chord (Ctrl + S); masked: modifiers only (Ctrl + \u2026)."),lingerSec:vr.lingerSec.describe(`Seconds a badge stays up (default ${el}).`),position:vr.position.describe("Default bottom (centred)."),size:vr.size.describe("Font px (default 4.5% of the frame height)."),color:vr.color.describe("Text color (default white)."),fontFile:Sr,dryRun:Vo.boolean().optional().describe("Return the planned badges; write nothing."),output:Vo.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Vo.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function eb(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:t_,outputSchema:D({badges:Vo.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}=Ca(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=Ra(o);if(e.dryRun){let p=Ko(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=QE(VE(e_(),"screencast-keys-"));try{let p=Ko(a.map(h=>h.label),d,"",e.fontFile),f={position:e.position,size:e.size,color:e.color},m=Zg(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{ZE(d,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as Zo}from"zod";import{join as ib}from"node:path";import{mkdtempSync as x_,rmSync as S_,writeFileSync as v_}from"node:fs";import{tmpdir as $_}from"node:os";import{z as qn}from"zod";import{existsSync as r_,readFileSync as n_}from"node:fs";var Qo={w:114,h:168,hotX:9,hotY:9,arrowH:135};function Pa(){return vn("cursor","arrow.png")}var o_=.5,rl=2,nl=1.5,i_=.4,tb=240,s_=4,a_=.35,c_=new Set(["move","down","up","wheel"]),Xn=t=>Math.round(t*1e3)/1e3;function u_(t){let e=6+(1-t)*34;return{omega:e,lead:Math.min(2/e,.2)}}function l_(t){let e=[],r=uc/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 p_(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 d_(t,e,r,n,o){if(t.length===0)return[];let i=1/tb,s=0,a=w=>{let b=p_(t,w+r,s);return s=b.i,b},c=a(n),u=c.x,d=c.y,p=0,f=0,m=[{t:Xn(n),x:u,y:d}],h=Math.exp(-e*i),g=Math.max(0,Math.ceil((o-n)*tb));for(let w=1;w<=g;w++){let b=Math.min(o,n+w*i),y=a(b),$=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%s_===0||w===g)&&m.push({t:Xn(b),x:u,y:d})}return m}function m_(t,e=a_){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 f_(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??o_;if(!(n>=0&&n<=1))throw new l("smoothing must be between 0 and 1.");let o=e.hideAfterSec??rl;if(!(o>=0))throw new l("hideAfterSec must be 0 or more.");let i=t.filter(h=>c_.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,g)=>h.t-g.t);if(i.length===0)return{path:[],visible:[],clicks:[]};let s=l_(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=u_(n);d=h.lead;let g=Math.max(0,a-d),w=Math.max(g,r??c+8/h.omega);u=d_(s,h.omega,d,g,w)}let p=Math.max(0,a-d),f=o===0?[[p,r??1/0]]:f_(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,g])=>[Xn(h),r!==null?Math.min(g,r):g]).filter(([h,g])=>g>h),clicks:m}}var g_={sx:1,sy:1,ox:0,oy:0};function Ia(t,e=[],r=g_){let n=a=>{let c=rs(a.t,e);return c===null?null:{t:Xn(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?[[Xn(u[0]),Number.isFinite(u[1])?Xn(u[1]):u[1]]]:[]}),s=t.clicks.flatMap(a=>{let c=n(a);return c?[c]:[]});return{path:m_(o),visible:i,clicks:s}}var Me=(t,e=2)=>{let r=Number(t.toFixed(e));return Object.is(r,-0)?"0":String(r)};function rb(t,e,r){let n=Number(r.toFixed(3));return n===0?Me(t):`${Me(t)}${n<0?"-":"+"}(t-${Me(e,3)})*${Me(Math.abs(n),3)}`}function b_(t,e=nl){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/Qo.arrowH,o=Math.max(12,Math.round(r*2.2));return{spriteW:Math.max(2,Math.round(Qo.w*n)),spriteH:Math.max(2,Math.round(Qo.h*n)),hotX:Qo.hotX*n,hotY:Qo.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 w_(t){let e=new Map;for(let r of[...t].sort((n,o)=>n.t-o.t)){let n=Me(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(`
|
|
352
340
|
`)+`
|
|
353
|
-
`}function nb(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 ${rb(o.x+r,o.t,c)}, ${e} y ${rb(o.y+n,o.t,u)}`}})}function y_(t,e){return t.flatMap(([r,n])=>[{t:r,text:`${e} enable 1`},...Number.isFinite(n)?[{t:n,text:`${e} enable 0`}]:[]])}function ol(t,e,r,n,o,i,s,a){if(t.path.length===0)throw new l("No cursor positions to draw.");let c=b_(r.height,e.size),{width:u,height:d}=r,p=b=>`overlay@${i}c${b}`,f=[],m=[],h=t.path[0],g=`[${i}cm]`;f.push(`${n}sendcmd=f=${ye(a)}${g}`);let w=(b,y,$,S,C)=>{let M=`[${i}c${y}o]`;f.push(`${g}${b}${p(y)}=x=${Me(h.x+$)}:y=${Me(h.y+S)}:enable=0${M}`),m.push(...y_(C,p(y))),g=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-${Me(y/2)},Y-${Me($/2)})-${Me(S)})/${Me(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(...nb(t.path,p("s"),R,P))}if(e.clicks!==!1&&t.clicks.length>0){let b=i_/3;c.ripples.forEach((y,$)=>{let S=y/2,C=Math.max(1.5,y*.05),M=`abs(hypot(X-${Me(S-.5)},Y-${Me(S-.5)})-${Me(S-C-1)})`,R=[.9,.65,.4][$],P=`255*lt(${M},${Me(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(${Me(C)}-${M},0,1)'[${i}cr${$}]`);let j=t.clicks.map(X=>[X.t+$*b,X.t+($+1)*b]);w(`[${i}cr${$}]`,`r${$}`,-S,-S,[]);for(let[X,N]of t.clicks.entries()){let[se,ee]=j[X],J=j[X+1];m.push({t:se,text:`${p(`r${$}`)} x ${Me(N.x-S)}, ${p(`r${$}`)} y ${Me(N.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(...nb(t.path,p("p"),-c.hotX,-c.hotY)),{steps:f,out:g,extraInputs:["-i",s],commands:w_(m)}}function ob(t,e,r,n,o,i,s,a="standard"){let{steps:c,out:u,extraInputs:d,commands:p}=ol(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 Fa={events:qn.string().optional(),size:qn.number().min(.25).max(8).optional(),smoothing:qn.number().min(0).max(1).optional(),hideAfterSec:qn.number().min(0).max(600).optional(),clicks:qn.boolean().optional(),spotlight:qn.boolean().optional()};function Oa(t,e,r,n){let o=e??$e(t).jsonl;if(!r_(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_(je(n_(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 Jn=Fa,k_={input:Zo.string().min(1).describe("Path to the recording."),events:Jn.events.describe("Event log (default: the input's .events.jsonl)."),size:Jn.size.describe(`Times a typical cursor's size (default ${nl}).`),smoothing:Jn.smoothing.describe("0 = as logged, 1 = floaty (default 0.5)."),hideAfterSec:Jn.hideAfterSec.describe(`Hide when the mouse rests this long; 0 = never (default ${rl}).`),clicks:Jn.clicks.describe("Ripple on clicks (default true)."),spotlight:Jn.spotlight.describe("Dim all but the area around the cursor."),dryRun:Zo.boolean().optional().describe("Return the plan; write nothing."),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 sb(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:k_,outputSchema:D({segments:Zo.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=Ia(Oa(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=x_(ib($_(),"screencast-cursor-"));try{let c=ib(a,"cursor.cmd"),{args:u,commands:d}=ob(e.input,s,o,{size:e.size,clicks:e.clicks,spotlight:e.spotlight},{width:n.width,height:n.height},Pa(),c);return v_(c,d),await W(u,{output:s,durationSec:n.durationSec,extra:r}),v({outputPath:s,...i})}finally{S_(a,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as Yn}from"zod";import{existsSync as M_}from"node:fs";import{extname as C_}from"node:path";import{z as zt}from"zod";var ub={desktop:["#1B2330","#0A0D12"],rec:["#FF4545","#5C0F1A"],amber:["#FFB454","#FF4545"],light:["#F4F7FA","#B9C4D0"]},E_=Object.keys(ub),__="desktop",sl=4,T_=.5,ab=t=>2*Math.round(t/2),Da=t=>2*Math.floor(t/2);function il(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 A_(t,e,r={}){if(!(t>0&&e>0))throw new l("The input has no frame size.");let n=il(r.padding,"padding",2e3),o=il(r.radius,"radius",1e3),i=il(r.shadow,"shadow",200),s,a,c=t,u=e,d,p,f,m=!1;if(r.aspect){let $=Wn[r.aspect];if(!$)throw new l(`Unknown aspect "${r.aspect}".`);s=$.w,a=$.h,f=ab(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,Da(t*M)),u=Math.max(2,Da(e*M)),m=c!==t||u!==e,d=Da((s-c)/2),p=Da((a-u)/2)}else f=ab(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),g=Math.min(o??Math.round(h*.012),Math.floor(Math.min(c,u)/2)),w=i??Math.round(h*.025),b=a-p-u,y=w>0?Math.max(0,Math.min(Math.round(w/2),b)):0;return{canvasW:s,canvasH:a,contentW:c,contentH:u,x:d,y:p,padding:f,radius:g,shadow:w,shadowOffset:y,scaled:m}}function R_(t){if(t.colors!==void 0){if(t.colors.length<1||t.colors.length>sl)throw new l(`colors takes 1 to ${sl} colors.`);return t.colors.map((n,o)=>Ne(n,`colors[${o}]`))}let e=t.preset??__,r=ub[e];if(!r)throw new l(`Unknown backdrop preset "${e}".`);return[...r]}function cb(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 al(t,e,r,n,o,i=!1){let s=A_(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??T_,{canvasW:c,canvasH:u,contentW:d,contentH:p,x:f,y:m}=s,h=":r=1:d=1",g=[],w=[],b=`[${o}bg]`;if(t.image)w.push("-i",t.image),g.push(`[${n}:v]scale=${c}:${u}:force_original_aspect_ratio=increase,crop=${c}:${u},setsar=1,trim=end_frame=1,format=rgba${b}`);else{let j=R_(t);if(j.length===1)g.push(`color=c=${j[0]}:s=${c}x${u}${h},format=rgba${b}`);else{let X=j.map((N,se)=>`c${se}=${N}`).join(":");g.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${b}`)}}let y=b;if(s.shadow>0&&a>0){let j=`[${o}sa]`,X=`[${o}sc]`,N=`[${o}sh]`,se=`[${o}bs]`,ee=s.radius>0?`format=gray,geq=lum='${cb(s.radius)}'`:"format=gray";g.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}`),g.push(`color=c=black:s=${c}x${u}${h}${X}`),g.push(`${X}${j}alphamerge,format=rgba,colorchannelmixer=aa=${a}${N}`),g.push(`${y}${N}overlay=0:0:format=rgb${se}`),y=se}let $=`[${o}hole]`,S=`[${o}frame]`,C=s.radius>0?`format=gray,geq=lum='${cb(s.radius,!0)}'`:"format=gray";g.push(`color=c=black:s=${d}x${p}${h},${C},pad=${c}:${u}:${f}:${m}:color=white${$}`),g.push(`${y}${$}alphamerge,format=rgba${S}`);let M=`[${o}pad]`,R=`[${o}bd]`,P=s.scaled?`scale=${d}:${p},setsar=1,`:"";return g.push(`${r}${P}pad=${c}:${u}:${f}:${m}:color=black${M}`),g.push(`${M}${S}overlay=0:0${i?":format=rgb":""}${R}`),{steps:g,out:R,extraInputs:w,layout:s}}function lb(t,e,r,n,o=!1,i="standard"){let{steps:s,out:a,extraInputs:c,layout:u}=al(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 Na={preset:zt.enum(E_).optional(),colors:zt.array(zt.string()).min(1).max(sl).optional(),image:zt.string().min(1).optional(),padding:zt.number().int().nonnegative().max(2e3).optional(),radius:zt.number().int().nonnegative().max(1e3).optional(),shadow:zt.number().int().nonnegative().max(200).optional(),shadowOpacity:zt.number().min(0).max(1).optional(),aspect:zt.enum(Bn).optional()};var pb=/\.(png|jpe?g|bmp|tiff?|webp)$/i,$r=Na,P_={input:Yn.string().min(1).describe("Path to the source video or image (png/jpg)."),preset:$r.preset.describe("Gradient: desktop (default, dark slate), rec (red), amber, light."),colors:$r.colors.describe("Instead: 1 color = solid, 2-4 = diagonal gradient."),image:$r.image.describe("Instead: a wallpaper image, scaled to cover."),padding:$r.padding.describe("px around the content (default 6% of the longer side)."),radius:$r.radius.describe("Corner radius px (default ~1.2% of the longer side; 0 = square)."),shadow:$r.shadow.describe("Shadow blur px (default ~2.5%; 0 = none)."),shadowOpacity:$r.shadowOpacity.describe("Default 0.5."),aspect:$r.aspect.describe("Output on this aspect's canvas (1920x1080, ...), content scaled to fit."),output:Yn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits (screenshots for an image)."),overwrite:Yn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function db(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:P_,outputSchema:D({outputPath:Yn.string(),width:Yn.number().int(),height:Yn.number().int()}),annotations:I},async(e,r)=>{try{if(k(),F(e.input),e.image&&!M_(e.image))throw new l(`Background image not found: ${e.image}`);let n=pb.test(e.input);if(n&&e.output&&!pb.test(e.output))throw new l("An image input writes an image: give the output a .png or .jpg extension.");n||Dr(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)?C_(e.input).toLowerCase():".png":V(e.input),s=Zt(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}=lb(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 ei}from"zod";var I_={input:ei.string().min(1).describe("Path to the source video."),level:ei.enum(["light","medium","heavy"]).optional().describe("CRF 23 / 28 / 32 (default medium)."),maxWidth:ei.number().int().positive().optional().describe("Width cap in px (only downscales)."),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 mb(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:I_,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=Ap(e.input,o,{level:e.level,maxWidth:e.maxWidth});return await W(i,{output:o,durationSec:await ue(e.input),extra:r}),v({outputPath:o,level:e.level??"medium"})}catch(n){return E(n)}})}import{z as La}from"zod";var F_={mp3:"mp3",aac:"m4a",wav:"wav"},O_={input:La.string().min(1).describe("Path to the source media."),format:La.enum(["mp3","aac","wav","copy"]).describe("Audio output codec. copy keeps the source codec without re-encoding."),output:La.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:La.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function fb(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:O_,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=Rp(i)}else s=F_[o];let a=B(e.output,"audio",`.${s}`,{overwrite:e.overwrite,anyContainer:!0});return await W(Mp(e.input,a,o),{output:a,durationSec:await ue(e.input),extra:r}),v({outputPath:a,format:o,...i?{sourceAudioCodec:i}:{}})}catch(n){return E(n)}})}import{z as dl}from"zod";import{extname as D_}from"node:path";import{z as cl}from"zod";var N_=["youtube","podcast","broadcast"],Ba=cl.union([cl.enum(N_),cl.number().min(-70).max(-5)]),hb={youtube:{i:-14,tp:-1,lra:11},podcast:{i:-16,tp:-1.5,lra:11},broadcast:{i:-23,tp:-1,lra:7}};function Kn(t){if(t===void 0)return hb.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=hb[t];if(!e)throw new l(`Unknown loudness target "${t}".`);return e}var ul=t=>`I=${t.i}:TP=${t.tp}:LRA=${t.lra}`;function ti(t,e){return["-hide_banner","-nostats","-i",t,"-vn","-af",`loudnorm=${ul(e)}:print_format=json`,"-f","null","-"]}function ri(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 gb(t){return Ri(t)?["-map","0:a:0","-vn"]:["-map","0:v?","-map","0:a:0","-c:v","copy"]}function Wa(t){switch(D_(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 ll(t,e){if(!e)return`loudnorm=${ul(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=${ul(t)}:${r}:linear=true`}function bb(t,e,r,n){return["-y","-hide_banner","-i",t,...gb(e),"-af",`${ll(r,n)}:print_format=json`,"-ar","48000",...Wa(e),e]}var ja=["light","medium","strong"],L_={light:6,medium:12,strong:20};function Ua(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 za(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 B_(t){return t===null?-50:Math.max(-80,Math.min(-20,Math.round(t+5)))}function pl(t,e){let r=L_[t];if(r===void 0)throw new l(`Unknown denoise strength "${t}".`);return`afftdn=nr=${r}:nf=${B_(e)}`}function wb(t,e,r="medium",n=null){return["-y","-i",t,...gb(e),"-af",pl(r,n),...Wa(e),e]}var W_={input:dl.string().min(1).describe("Path to the source video or audio file."),target:Ba.optional().describe("youtube (-14 LUFS, default), podcast (-16), broadcast (-23), or a LUFS number (-70 to -5)."),output:dl.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:dl.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function yb(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:W_,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=Kn(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,ti(e.input,i),c,{signal:r.signal}),d=ri(u.stderr);await W(bb(e.input,a,i,d),{output:a,durationSec:o.durationSec,extra:r});let p=ri((await ne(n,ti(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 Ha}from"zod";var j_={input:Ha.string().min(1).describe("Path to the source video or audio file."),strength:Ha.enum(ja).optional().describe("How hard to reduce noise: light (6 dB), medium (12 dB, default), strong (20 dB)."),output:Ha.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ha.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function xb(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:j_,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,Ua(e.input),le(n.durationSec),{signal:r.signal}),c=za(a.stdout);return await W(wb(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 Ht}from"zod";import{existsSync as U_,readFileSync as z_,rmSync as H_,writeFileSync as G_}from"node:fs";var q_={input:Ht.string().min(1).describe("Path to the video or audio to transcribe."),model:Ht.string().optional().describe(`Path to a whisper.cpp model file (ggml-*.bin). Defaults to ${qs}.`),language:Ht.string().optional().describe("Spoken language code, e.g. 'en', or 'auto' (default)."),words:Ht.boolean().optional().describe("One word per cue, for word timing (cut_by_transcript)."),output:Ht.string().optional().describe("Optional output .srt path. Defaults under SCREENCAST_HOME/edits."),overwrite:Ht.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Sb(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:q_,outputSchema:D({srtPath:Ht.string(),cues:Ht.number().int(),text:Ht.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=gr(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(Fn(e.input,n,s,e.language??"auto",e.words),le(o.durationSec),{signal:r.signal});let a=U_(s)?ut(bh(We(z_(s,"utf8")))):[];G_(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{H_(s,{force:!0})}}catch(n){return E(n)}})}import{z as ni}from"zod";import{dirname as X_}from"node:path";import{existsSync as J_}from"node:fs";var Y_={input:ni.string().min(1).describe("Path to the source video."),subtitles:ni.string().min(1).describe("Path to an .srt (e.g. from transcribe) or .ass subtitle file."),style:ni.enum(Xs).optional().describe("clean (default for .srt): outlined line. social: big bold text on a dark box. .ass keeps its own styling unless set."),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("burn_subtitles",{title:"Burn In Subtitles",description:"Burn SRT/ASS subtitles (e.g. from transcribe) into a video in the bundled font.",inputSchema:Y_,outputSchema:Y,annotations:I},async(e,r)=>{try{k();for(let a of[e.input,e.subtitles])if(!J_(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=X_(Lt("regular")),s=e.style??(/\.(ass|ssa)$/i.test(e.subtitles)?null:"clean");return await W(wh(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 _t}from"zod";var K_={input:_t.string().min(1).describe("Path to the source video."),segments:_t.array(_t.object({start:_t.number().nonnegative(),end:_t.number().positive()})).min(1).describe("{start, end} segments in seconds; each becomes its own file."),output:_t.string().optional().describe("Optional output path. Only honored for a single segment; multi-segment output lands under SCREENCAST_HOME/edits."),overwrite:_t.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function $b(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:K_,outputSchema:D({outputs:_t.array(_t.string()),count:_t.number().int()}),annotations:I},async(e,r)=>{try{k(),F(e.input),Dr(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(Cp(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 Gt}from"zod";var V_={input:Gt.string().min(1).describe("Path to the source video."),minIdleSec:Gt.number().positive().optional().describe(`Only cut still stretches at least this long (default ${Yr}).`),keepSec:Gt.number().min(0).optional().describe(`Seconds kept at each edge of a cut (default ${Xo}).`),useAudio:Gt.boolean().optional().describe("Require silent audio too (default true when there is audio)."),action:Gt.enum(["cut","speed"]).optional().describe("cut (default), or speed: fast-forward them."),factor:Gt.number().gt(1).max(Jr).optional().describe(`speed: times faster (default ${Jo}).`),dryRun:Gt.boolean().optional().describe("Only report what would be cut."),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 kb(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:V_,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??Xo,c=o.audioCodec!==null,u=(e.useAudio??!0)&&c,d=await ne(n,ma(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=fa(d.stderr,i),f=u?ga(p,ha(d.stderr,i)):p,m=ba(f,s,a),h=e.action==="speed",g=e.factor??Jo,w=m.map(M=>({...M,factor:g})),b=Number((h?Kr(w):m.reduce((M,R)=>M+(R.end-R.start),0)).toFixed(2)),y={cuts:m,...h?{action:"speed",factor:g}:{},removedSec:b,originalSec:Number(i.toFixed(2)),newDurationSec:Number((i-b).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?Sa(e.input,S,w,{withAudio:c,fps:o.fps}):va(e.input,S,m,c);return await W(C,{output:S,durationSec:i-b,inputDurationSec:i,extra:r}),v({outputPath:S,...y})}catch(n){return E(n)}})}import{z as Qe}from"zod";import{existsSync as Cb,readFileSync as oT,writeFileSync as iT}from"node:fs";var Q_=["um","umm","uh","uhh","uhm","erm","er","ah","hmm","hm","mm","mhm"],Eb=.5,Tb=t=>t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),kr=t=>Number(t.toFixed(3));function Ab(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:Tb(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 Z_=t=>t.flatMap((e,r)=>e.norm?[r]:[]);function eT(t,e){let r=e.split(/\s+/).map(Tb).filter(Boolean);if(r.length===0)throw new l(`Quote "${e}" has no words to match.`);let n=Z_(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 tT(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:kr(o.start),end:kr(i.end),text:t.slice(e,n+1).map(s=>s.raw).join(" "),exact:o.first&&i.last}}function rT(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 nT(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 Rb(t,e){let r=Ab(t),n=[];for(let i of e.remove??[]){if(typeof i=="number"){let a=nT(t,i);n.push({start:kr(a.start),end:kr(a.end),text:a.text.replace(/\s+/g," "),exact:!0});continue}let s=eT(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(tT(r,...s[0]))}let o=0;if(e.fillers){let i=new Set(Q_);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-Eb),d=Math.min(t[s.cue+1]?.start??1/0,c.end+Eb);n.push({start:kr(Math.min(u,c.start)),end:kr(Math.max(d,c.end)),text:r.filter(p=>p.cue===s.cue).map(p=>p.raw).join(" "),exact:!0})})}return{cuts:rT(n),skippedFillers:o}}function _b(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 Mb(t,e){let r=Ab(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=kr(_b(i.start,e)),p=kr(_b(i.end,e));p>d&&o.push({start:d,end:p,text:u})}),o}var sT={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 Pb(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:sT,outputSchema:D({cuts:Qe.array(Qe.unknown()),removedSec:Qe.number()}),annotations:I},async(e,r)=>{try{k();for(let g of[e.input,e.srt])if(!Cb(g))throw new l(`File not found: ${g}`);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(oT(e.srt,"utf8"),{index:!0}));if(i.length===0)throw new l(`No cues in ${e.srt}.`);let{cuts:s,skippedFillers:a}=Rb(i,{remove:e.remove,fillers:e.fillers});if(s.length>zn)throw new l(`Too many cuts (${s.length}, max ${zn}); cut in batches.`);let c=Number(s.reduce((g,w)=>g+Math.min(w.end,o)-Math.min(w.start,o),0).toFixed(2)),u=Mb(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(g=>!g.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 g=u.map(w=>w.text.replace(/\n/g," ")).join(" ");return v({...p,...s.length?{dryRun:!0}:{},text:g.length>4e3?`${g.slice(0,4e3)}\u2026`:g})}let f=V(e.input),m=B(e.output,"cut-transcript",f,{overwrite:e.overwrite}),h=m.replace(/\.[^.\\/]+$/,"")+".srt";if(!e.overwrite&&Cb(h))throw new l(`Output already exists: ${h}. Pass overwrite: true to replace it.`);return await W(va(e.input,m,s,n.audioCodec!==null),{output:m,durationSec:o-c,inputDurationSec:o,extra:r}),iT(h,nt(u)),v({outputPath:m,srtPath:h,...p})}catch(n){return E(n)}})}import{z as Qr}from"zod";var aT={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(Ci).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 Ib(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:aT,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}=Pi(e.input,e.output),c=B(e.output,"redact",a,{overwrite:e.overwrite,anyContainer:!0}),u=Pp(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 Ga}from"zod";function Fb(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:D({devices:Ga.array(Ga.unknown()),loopbackDevice:Ga.string().nullable(),note:Ga.string()}),annotations:he},async()=>{try{k();let e=await Jc(!0),r=Xc(e);return v({devices:e,loopbackDevice:r,note:r?`Pass "${r}" as the audio device to capture system audio.`:`No loopback device detected. ${Ro}`})}catch(e){return E(e)}})}import{z as fe}from"zod";function Db(t){return t.hwnd!==void 0?`window:hwnd=${t.hwnd}`:`window:${t.title}`}function cT(t){let e=/^.*?[.!?](?=\s|$)/.exec(t);return e?e[0]:t}function Ob(t,e,r){try{return Cc(t,Db(e).slice(7),{allowCloaked:r,exactOnly:!0}),{ok:!0}}catch(n){return{ok:!1,reason:cT(U(n))}}}function Nb(t,e,r){let n=r.filter??{},o=n.exe?Mc(`exe=${n.exe}`):null,i=o?.kind==="exe"?o.exe:null,s=n.titleContains?.trim().toLowerCase()||null,a=bo(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=Ob(e,d,!1),f=r.wgcAvailable&&d.hwnd!==void 0?Ob(e,d,!0):{ok:!1};n.capturableOnly&&!p.ok&&!f.ok||u.push({target:Db(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 uT={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.")},ml=fe.object({x:fe.number(),y:fe.number(),width:fe.number(),height:fe.number()}),lT=D({full:fe.looseObject({target:fe.literal("full"),bounds:ml}),monitors:fe.array(fe.looseObject({target:fe.string(),index:fe.number(),primary:fe.boolean(),bounds:ml,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:ml,minimized:fe.boolean(),cloaked:fe.boolean(),capturable:fe.boolean(),wgcCapturable:fe.boolean()})),wgcAvailable:fe.boolean(),note:fe.string()});function Lb(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:uT,outputSchema:lT,annotations:he},async e=>{try{let[r,n]=await Promise.all([sr(),Pc()]),o=Nb(r,n,{wgcAvailable:or(),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 fl}from"node:fs";import{join as hl}from"node:path";import{z as pe}from"zod";var Bb=200,Wb=1e3,qa=.5,Xa=3,Zr=t=>Math.round(t*1e3)/1e3;function Ub(t,e){if(t.length===0)throw new l("lines is empty: give at least one { t | marker, text }.");if(t.length>Bb)throw new l(`At most ${Bb} 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>Wb)throw new l(`lines[${o}] is ${i.length} characters; at most ${Wb} 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 zb(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 Hb(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 Gb(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 qb(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,g)=>{let w=Math.round(h.t*1e3);return`[${g+1}:a]aresample=48000,aformat=channel_layouts=mono,adelay=${w}[l${g}]`}),u=n.map((h,g)=>`[l${g}]`).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=Ri(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),...Wa(r),.../\.(mp4|mov|m4a)$/i.test(r)?["-movflags","+faststart"]:[],r]}var pT=3e4,dT=1e4,jb=3e4,Xb=t=>Array.isArray(t)?t:t==null?[]:[t];function Jb(t){return Xb(t.voices).map(e=>({name:String(e.name??""),language:String(e.language??""),gender:String(e.gender??"")}))}function mT(t){return{script:hT,payload:JSON.stringify(t)}}async function Yb(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}=mT(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 fT(t){let e=await Yb({list:!0},ir(15e3),t);if(e.error)throw new l(`Windows speech is unavailable: ${e.error}`);return Jb(e)}async function Kb(){if(process.platform!=="win32")return{available:!1,voices:[],error:"Windows speech is available on Windows only."};try{let t=(await fT()).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 Vb(t,e){let r=e.rate??1;if(!Number.isFinite(r)||r<qa||r>Xa)throw new l(`rate must be between ${qa} and ${Xa} (1 is normal speed).`);let n=await Yb({voice:e.voice??null,rate:r,items:t},ir(pT+t.length*dT),e.signal);if(n.error){let o=Jb(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 Xb(n.results).forEach((o,i)=>{if(o.error)throw new l(`Could not synthesize line ${i+1}: ${o.error}`)}),String(n.voice??"")}var hT=`
|
|
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=`
|
|
354
342
|
$ErrorActionPreference = 'Stop'
|
|
355
343
|
function Out($o) { ConvertTo-Json -InputObject $o -Depth 5 -Compress }
|
|
356
344
|
try {
|
|
@@ -374,7 +362,7 @@ try {
|
|
|
374
362
|
$results = foreach ($item in @($req.items)) {
|
|
375
363
|
try {
|
|
376
364
|
$task = $asTask.MakeGenericMethod([Windows.Media.SpeechSynthesis.SpeechSynthesisStream]).Invoke($null, @($synth.SynthesizeTextToStreamAsync([string]$item.text)))
|
|
377
|
-
if (-not $task.Wait(${
|
|
365
|
+
if (-not $task.Wait(${uw})) { throw "The speech engine did not answer within ${uw/1e3} s." }
|
|
378
366
|
$stream = $task.Result
|
|
379
367
|
$in = [System.IO.WindowsRuntimeStreamExtensions]::AsStreamForRead($stream)
|
|
380
368
|
$fs = [System.IO.File]::Create([string]$item.path)
|
|
@@ -384,10 +372,10 @@ try {
|
|
|
384
372
|
}
|
|
385
373
|
Out ([pscustomobject]@{ voice = $synth.Voice.DisplayName; results = @($results) })
|
|
386
374
|
} catch { Out ([pscustomobject]@{ error = $_.Exception.Message }) }
|
|
387
|
-
`;var gT=bt(),Qb=pe.looseObject({found:pe.boolean(),path:pe.string().nullable(),version:pe.string().nullable(),major:pe.number().nullable()}),bT=D({ok:pe.boolean(),problems:pe.array(pe.string()),server:pe.looseObject({version:pe.string(),node:pe.string(),platform:pe.string(),arch:pe.string()}),ffmpeg:Qb.extend({meetsFfmpeg8:pe.boolean().nullable()}),ffprobe:Qb,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 wT(t){let e=E(t).content[0];return e?.type==="text"?e.text.replace(/\s*\n+\s*/g," "):String(t)}function Zb(t){let e=ia(t),r=oa(e??"");return{found:e!==null,path:e!==null?tg(t):null,version:r.version,major:r.major,...r.inferred?{majorInferred:!0}:{}}}function ew(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:bT,annotations:he},async()=>{try{let e=[],r=null;try{r=kc()}catch(g){e.push(wT(g))}let n=Zb(r?.ffmpeg??(process.env.FFMPEG_PATH?.trim()||"ffmpeg")),o=Zb(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 ng)s[w.filter]=w.filter==="gfxcapture"?or():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 g=Zh(eg(r.ffmpeg)??"");a={gdigrab:g.includes("gdigrab"),dshow:g.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 Nc(r.ffmpeg)}:null,[u,d]=await Promise.all([br(),Kb()]);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=rg(),f=p.SCREENCAST_WHISPER_MODEL;f&&!fl(f)&&e.push(`SCREENCAST_WHISPER_MODEL points at a missing file: ${f}`);let m=Ie();for(let g of fo())fl(g)||e.push(`SCREENCAST_ALLOWED_DIRS names a missing folder: ${g}`);let h=mi(p.SCREENCAST_TOOLSETS??void 0);return h.unknown.length>0&&e.push(`SCREENCAST_TOOLSETS names unknown toolsets (ignored): ${h.unknown.join(", ")}.`),v({ok:e.length===0,problems:e,server:{version:gT,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:fl(m),recordings:hl(m,"recordings"),screenshots:hl(m,"screenshots"),edits:hl(m,"edits"),allowedOutputDirs:Mr()},env:p,toolsets:{enabled:h.enabled,available:["all",...di]}})}catch(e){return E(e)}})}import{z as Vn}from"zod";var yT={inputA:Vn.string().min(1).describe("Outgoing video."),inputB:Vn.string().min(1).describe("Incoming video."),transition:Vn.string().optional().describe("xfade name (default fade): fade, wipeleft, slideup, circleopen, dissolve, ..."),duration:Vn.number().positive().optional().describe(`Transition length in seconds (default ${Ln}).`),output:Vn.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Vn.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function tw(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:yT,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=mg(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 qt}from"zod";var xT={clips:qt.array(qt.string().min(1)).min(2).describe("Clip paths, in order."),transition:qt.string().optional().describe("cut (default) or an xfade name (fade, wipeleft, slideup, ...)."),duration:qt.number().positive().optional().describe(`Transition seconds (default ${Ln}).`),width:qt.number().int().positive().optional().describe("Common output width (default 1920)."),height:qt.number().int().positive().optional().describe("Common output height (default 1080)."),fps:qt.number().int().positive().optional().describe("Common output fps (default 30)."),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 rw(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:xT,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=Go(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 ST,rmSync as vT}from"node:fs";var $T={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:Sr,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 nw(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:$T,outputSchema:Y,annotations:I},async(e,r)=>{try{k();let n=B(e.output,"title",".mp4",{overwrite:e.overwrite}),o=St(e.text,{weight:e.bold===!1?"regular":"bold",fontFile:e.fontFile}),i=Ue(".txt");ST(i,e.text);try{let s=fg(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??zu,extra:r})}finally{vT(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 Er}from"zod";var kT={video:Er.string().min(1).describe("Path to the video."),music:Er.string().min(1).describe("Music audio file."),musicVolume:Er.number().nonnegative().optional().describe("0..1 (default 0.25 over existing audio, 0.8 alone)."),fadeIn:Er.number().nonnegative().optional().describe("Fade-in seconds (default 1)."),fadeOut:Er.number().nonnegative().optional().describe("Fade-out seconds (default 2)."),duck:Er.boolean().optional().describe("Duck the music under the original audio (default false)."),output:Er.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:Er.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function ow(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:kT,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=hg(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 ET,mkdtempSync as _T,readFileSync as TT,rmSync as AT,writeFileSync as RT}from"node:fs";import{tmpdir as MT}from"node:os";import{join as iw}from"node:path";var CT={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(qa).max(Xa).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 sw(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:CT,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 dr(e.video,r.signal)).markers:[],a=Ub(e.lines,s),c=B(e.output,"narrated",V(e.video),{overwrite:e.overwrite}),u=c.replace(/\.[^./\\]+$/,"")+".srt";if(!e.overwrite&&ET(u))throw new l(`Output already exists: ${u}. Pass overwrite: true to replace it.`);n=_T(iw(MT(),"screencast-tts-"));let d=a.map((w,b)=>iw(n,`line-${b}.wav`)),p=await Vb(a.map((w,b)=>({text:w.text,path:d[b]})),{voice:e.voice,rate:e.rate,signal:r.signal}),f=a.map((w,b)=>({...w,durationSec:Gb(TT(d[b]))})),m=zb(f,o.durationSec),h=qb(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}),RT(u,nt(Hb(f,o.durationSec)));let g=Le(e.video);return g.length>0&&pr(c,g),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&&AT(n,{recursive:!0,force:!0})}})}import{z as oi}from"zod";var PT={input:oi.string().min(1).describe("Path to the source video."),aspect:oi.enum(Bn).describe("Target aspect ratio."),fit:oi.enum(sa).optional().describe("pad (default): letterbox, nothing lost. crop: fill and center-crop."),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 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:PT,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=gg(e.input,o,e.aspect,e.fit??"pad");return await W(i,{output:o,durationSec:await ue(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 IT,readFileSync as FT}from"node:fs";var Xt=.6,si=6,Ja=2.5;function Ya(t,e,r,n=si){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 gl(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 Et(i)}function yl(t,e,r=Xt){let{width:n,height:o,fps:i}=e,s=n<=1920?2:1,a=gl(t,"z",r),c=gl(t,"cx",r),u=gl(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 cw(t,e,r,n,o=Xt,i="standard",s){let{width:a,height:c,fps:u}=n,d=yl(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]",...NT(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 uw(t,e,r,n,o={}){let i=o.step??.25,s=o.holdSec??2,a=o.maxZoom??Ja,c=o.globalFraction??.3,u=o.transition??Xt,d=r/t,p=r/a,f=n/a,m=[],h=null,g=()=>{h&&m.push(h),h=null},w=null,b=0;return{push:S=>{let C=w;if(w=S,!C){b=1;return}let M=b++*i,R=$t(C,S,t,e,{scale:d});if(R.regions.length===0){h&&M-h.last>s&&g();return}if(R.changedFraction>c){g();return}let P=wl(R.regions);h&&M-h.last<=s&&OT(h.box,P,r,n)?(h.box=wl([h.box,P]),h.last=M):(g(),h={start:M,last:M,box:P})},finish:()=>{g();let S=[],C=0;for(let M of m){let R=lw(M.box,r,n,p,f),P=Math.max(M.start,C+u),j=Math.max(M.last+s,P+u);S.push({t:ii(P),...R},{t:ii(j),full:!0}),C=j}return S}}}var ii=t=>Math.round(t*100)/100;function wl(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 OT(t,e,r,n){let o=wl([t,e]);return o.width<=r/2&&o.height<=n/2}function lw(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 pw(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 Ka(t,e,r,n={}){let o=n.holdSec??2,i=n.maxZoom??Ja,s=n.transition??Xt,a=e/i,c=r/i,u=Math.min(e,r)*.05,d=[...t].sort((h,g)=>h.t-g.t),p=[],f=0,m=-1/0;for(let h of d){let g=lw({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&&DT(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:ii(y),full:!0}),f=y}let b=Math.max(h.t,f+s);p.push({t:ii(b),...g}),f=b,m=h.t}return p.length>0&&p.push({t:ii(Math.max(m+o,f+s)),full:!0}),p}function DT(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 bl=.6,Va="#FF4545";function xl(t,e){return Math.max(40,2*Math.round(Math.min(t,e)*.045))}function NT(t,e,r,n,o){let i=xl(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/${bl})),${a/2}),255*min(1,2-2*T/${bl}),0)`;d.push(`color=c=${o}:s=${i}x${i}:r=${Ze(n)}:d=${bl},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 g=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${g}`),p=`[r${m}]`}),d}function ai(t){return IT(t)?je(FT(t,"utf8")).filter(e=>e.type==="down"&&e.inFrame).map(e=>({t:e.t,x:e.x,y:e.y})):null}var Qa=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 dw=200,LT={input:Xe.string().min(1).describe("Path to the source video."),keyframes:Xe.array(Qa).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 ${Xt}).`),maxZoom:Xe.number().min(1).max(si).optional().describe(`Auto mode: the furthest it zooms in (default ${Ja}).`),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 mw(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:LT,outputSchema:D({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??Xt,u=e.events??$e(e.input).jsonl,d=ai(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=Ne(e.highlightColor??Va,"highlightColor"),f=e.keyframes,m=!f,h=e.follow==="clicks"||e.follow!=="changes"&&d&&d.length>0?"clicks":"changes";if(!f&&h==="clicks"&&(f=Ka(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 $=Wh(o,i),S=.25,C=uw($.width,$.height,o,i,{step:S,holdSec:e.holdSec,maxZoom:e.maxZoom,transition:c});if(await Ni(pw(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>dw)throw new l(`${d.length} clicks is more than ${dw} rings; trim the video or the event log first.`);let g=Ya(f,o,i),w=V(e.input),b=B(e.output,"zoom",w,{overwrite:e.overwrite}),y=e.highlightClicks?{clicks:d??[],color:p}:void 0;return await W(cw(e.input,b,g,{width:o,height:i,fps:a},c,"standard",y),{output:b,durationSec:s,extra:r}),v({outputPath:b,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 qT,join as tn}from"node:path";import{existsSync as ec,mkdtempSync as XT,readFileSync as vw,rmSync as JT,writeFileSync as ci}from"node:fs";import{tmpdir as YT}from"node:os";var Qn=30,Tt=t=>Math.round(t*1e3)/1e3;function Sl(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 fw(t,e,r){let n=e.slice(r);return n.length>0?ns(t,n):[...t]}function Za(t,e,r,n,o={},i="standard",s={}){if(r.length===0)throw new l("Give at least one step.");if(r.length>Qn)throw new l(`At most ${Qn} 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=[],g=[],w=1,b=[],y=[],$=!1,S="[0:v]",C=null,M,R=[],P=[],j=[],X=[],N={sx:1,sy:1,ox:0,oy:0},se=(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 ${Tt(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=>{b.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:_}=se(x,H);q===0?(h.push("-ss",String(T),"-t",String(Tt(_-T))),R.push(`trim ${T}-${Tt(_)}s: input seek`)):(Q(`trim=start=${T}:end=${Tt(_)},setpts=PTS-STARTPTS`),y.push(`atrim=start=${T}:end=${Tt(_)},asetpts=PTS-STARTPTS`),R.push(`trim ${T}-${Tt(_)}s: trim filter`)),$=!0,m=_-T,P.push({op:"trim",start:T,end:_});break}case"crop":Q(xc(x,{width:d,height:p})),N&&(N={...N,ox:N.ox-x.x,oy:N.oy-x.y}),d=x.width,p=x.height,R.push(`crop to ${d}x${p}`);break;case"scale":{let T=Sc(x),[_,A]=[d,p];({width:d,height:p}=kp(d,p,x)),N&&(N={sx:N.sx*d/_,sy:N.sy*p/A,ox:N.ox*d/_,oy:N.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 _=ya(x.segments,m),A=xa(_,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), ${Tt(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(vc(T)),$=!0,m!==null&&(m/=T),P.push({op:"speed",factor:T}),R.push(`speed x${T}`);break}case"redact":{let{steps:T,out:_}=$c(x.regions,x,{width:d,height:p},S,de);b.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}=Qu(x.items,T,S,w,de);b.push(..._),g.push(...z),w+=z.length/4,S=A,R.push(`callout ${x.items.length} item(s)`);break}case"reframe":{let T=Wn[x.aspect];if(!T)throw new l(`step ${H}: unknown aspect "${x.aspect}".`);Q(`${aa(T.w,T.h,x.fit??"pad")},format=yuv420p`),N=null,d=T.w,p=T.h,R.push(`reframe to ${x.aspect} (${x.fit??"pad"})`);break}case"zoom":{let T=x.transitionSec??Xt,_=x.keyframes,A="";if(x.follow==="clicks"){if(_)throw new l(`step ${H}: zoom takes keyframes or follow, not both.`);if(!N)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=N,K=s.clicks?.[q];if(!K)throw new l(`Internal: missing clicks for step ${H}.`);let ce=K.flatMap(me=>{let De=rs(me.t,P),At=me.x*z.sx+z.ox,co=me.y*z.sy+z.oy;return De!==null&&At>=0&&At<d&&co>=0&&co<p?[{t:De,x:At,y:co}]:[]});_=Ka(ce,d,p,{holdSec:x.holdSec,maxZoom:x.maxZoom,transition:T}),A=` from ${ce.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(yl(Ya(_,d,p),{width:d,height:p,fps:f},T)),N=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=ba(bm(s.idle,P),x.minIdleSec??Yr,x.keepSec??Xo);if(T.length===0){R.push("cut_idle: no idle stretches here; nothing cut");break}if(x.action==="speed"){let z=x.factor??Jo,K=T.map(De=>({...De,factor:z})),ce=xa(K,f);Q(ce.video),y.push(ce.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}, ${Tt(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), ${Tt(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(pl(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=Kn(x.normalize);T?.loudness||te("loudness"),y.push(ll(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(Fu(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:ce}=al(_,{width:d,height:p},S,w,de);N=null,b.push(...A),g.push(...K),w+=K.length/2,S=z,d=ce.canvasW,p=ce.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 _=Qg(T.badges,P);if(_.length===0){R.push("keystroke_overlay: no badges in this part of the video");break}let{steps:A,out:z}=tl(Ra(_),T,x,{height:p},S,de);b.push(...A),S=z,R.push(`keystroke_overlay ${_.length} badge(s)`);break}case"cursor":{if(!N)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 _=Ia(T.plan,P,N);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:ce}=ol(_,x,{width:d,height:p},S,w,de,T.sprite,T.commandsFile);b.push(...A),g.push(...K),w+=K.length/2,S=z,X.push({path:T.commandsFile,content:ce}),R.push(`cursor ${_.path.length} segment(s), ${_.clicks.length} click(s)${x.spotlight?", spotlight":""}`);break}case"export_preset":{let T=Gu(x.platform,x.fit??"pad",de);N=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,...g],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&&b.push(`[0:a]${y.join(",")}[aout]`),b.length>0&&ee.push("-filter_complex",b.join(";")),ee.push("-map",S==="[0:v]"?"0:v":S),n.hasAudio&&ee.push("-map",ie?"[aout]":"0:a");let ae=C;return ae?ee.push(...ae):(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:Tt(m),gif:M,summary:R,timeOps:P,pending:j,files:X}}var gw=["pr_demo","tutorial","social_reel"],BT=1e7,hw=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:BT});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 WT=new Set(["redact","crop","cursor"]);function vl(t,e){let r=[...t],o=r.at(-1)&&hw.has(r.at(-1).op)?r.pop():null,i=r.length,s=new Set,a=[],c=[];for(let u of e){if(hw.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&&WT.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 jT,statSync as UT,writeFileSync as zT}from"node:fs";var ww=1;function HT(t){return`${t}.edit.json`}function GT(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 yw(t){let e;try{e=jT(t,"utf8")}catch{throw new l(`Edit spec not found: ${t}`)}return GT(e,t)}function $l(t){let e=UT(t);return{path:t,size:e.size,mtimeMs:Math.round(e.mtimeMs)}}function xw(t){let e;try{e=$l(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 Sw(t,e){let r=HT(t),n={version:ww,tool:"pipeline",createdAt:new Date().toISOString(),output:t,...e};return zT(r,JSON.stringify(n,null,2)+`
|
|
388
|
-
`),r}function KT(){if(!Ye("whisper"))return"this ffmpeg has no whisper filter (FFmpeg 8 with whisper.cpp).";try{return gr(void 0),null}catch{return"no whisper model (set SCREENCAST_WHISPER_MODEL)."}}var VT=O.enum(Bn),$w=O.enum(sa).optional(),QT=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(wa).min(1).optional()}),O.object({op:O.literal("redact"),regions:O.array(gn).min(1),style:O.enum(Ci).optional(),pad:O.number().int().nonnegative().optional(),color:O.string().optional()}),O.object({op:O.literal("callout"),items:O.array(Ea).min(1).max(50),fontFile:Sr}),O.object({op:O.literal("reframe"),aspect:VT,fit:$w}),O.object({op:O.literal("zoom"),keyframes:O.array(Qa).min(1).max(100).optional(),follow:O.literal("clicks").optional(),maxZoom:O.number().min(1).max(si).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:Ba.optional(),denoise:O.enum(ja).optional()}),O.object({op:O.literal("burn_subtitles"),subtitles:O.string().min(1).optional(),transcribe:O.boolean().optional(),style:O.enum(Xs).optional()}),O.object({op:O.literal("backdrop"),...Na}),O.object({op:O.literal("keystroke_overlay"),...Ma}),O.object({op:O.literal("cursor"),...Fa}),O.object({op:O.literal("export_preset"),platform:O.enum(ca),fit:$w}),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()})]),ZT={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(QT).max(Qn).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(gw).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 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:ZT,outputSchema:D({processes:O.number().int(),steps:O.array(O.string())}),annotations:I},async(e,r)=>{try{let{ffmpeg:n}=k(),o=e.fromEdit?yw(e.fromEdit):null;if(o){if(e.recipe)throw new l("fromEdit already has its steps; leave recipe out.");if(e.input&&!Lo(e.input,o.source.path))throw new l(`The spec is for ${o.source.path}, not ${e.input}.`);let P=xw(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=vl(o.steps,p)),e.recipe){let P=ai($e(i).jsonl),j=bw(e.recipe,{hasAudio:u,hasClicks:!!P&&P.length>0,transcribeBlocker:u?KT():null});p=vl(j.steps,p),d.push(...j.notes)}if(p.length===0)throw new l("Give steps, a recipe, or both.");if(p.length>Qn)throw new l(`At most ${Qn} 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 g=h.op==="export_gif"?`.${h.format??"gif"}`:".mp4",w=B(e.output,"pipeline",g,{overwrite:e.overwrite,anyContainer:h.op==="export_gif"}),b=h.op!=="export_gif"&&p.some(P=>P.op==="burn_subtitles"&&P.transcribe),y=w.replace(/\.[^./\\]+$/,"")+".srt";if(b&&!e.overwrite&&ec(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&&!ec(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).`);gr(void 0)}}let $={};for(let[P,j]of p.entries()){if(j.op!=="zoom"||j.follow!=="clicks")continue;let X=$e(i).jsonl,N=ai(X);if(!N)throw new l(`step ${P+1}: no event log at ${X}; record with start_recording events: true.`);$[P]=N}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,N=await ne(n,ma(i,(M.minIdleSec??Yr)*j,X),m,{signal:r.signal});if(N.code!==0)throw new l(`Idle scan failed (exit ${N.code}): ${N.stderr.trim().slice(-400)}`);let se=fa(N.stderr,P);S=X?ga(se,ha(N.stderr,P)):se}let R=XT(tn(YT(),"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),...Zu(A.items,A.fontFile)}:await _a(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&&!ec(A.image))throw new l(`step ${_+1}: background image not found: ${A.image}`);if(A.op!=="keystroke_overlay")continue;let{badges:z}=Ca(i,A.events,A),K=[...new Set(z.map(me=>me.label))],ce=Ko(K,e.dryRun?null:R,`s${_}_`,A.fontFile);X[_]={badges:z,fontFile:ce.fontFile,textFiles:ce.textFiles},d.push(...ce.warnings.map(me=>`Step ${_}, ${me.charAt(0).toLowerCase()}${me.slice(1)}`))}let N={};for(let[_,A]of p.entries())A.op==="cursor"&&(N[_]={plan:Oa(i,A.events,A,c.durationSec),sprite:Pa(),commandsFile:e.dryRun?`<cursor ${_}.cmd>`:tn(R,`s${_}_cursor.cmd`)});let se=h.op==="export_gif"?e.dryRun?"<temporary stage1.mp4>":tn(R,"stage1.mp4"):w,ee={},J={},ie=qT(Lt("regular")),ae=_=>Za(i,se,p,f,P,s,{keystrokes:X,cursor:N,idle:S,clicks:$,audio:ee,subtitles:J,fontsDir:ie,chaptersFile:_}),x=ae(),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 ce=>{let me=Di(Sl(ce,A));try{let De=await ne(n,me.args,m,{signal:r.signal});if(De.code!==0)throw new l(`step ${A.step+1} ${A.kind} scan failed (exit ${De.code}): ${De.stderr.trim().slice(-400)}`);return De}finally{me.cleanup()}};if(A.kind==="noisefloor")ee[A.step]={...ee[A.step],floorDb:za((await K(Ua(i))).stdout)};else if(A.kind==="loudness"&&z.op==="audio"){let ce=await K(ti(i,Kn(z.normalize)));try{ee[A.step]={...ee[A.step],loudness:ri(ce.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 ce=tn(R,`s${A.step}_raw.srt`);await Z(Sl(Fn(i,gr(void 0),ce),A),m,{signal:r.signal});let me=ec(ce)?ut(We(vw(ce,"utf8"))):[];J[A.step]=me.length>0?tn(R,`s${A.step}.srt`):"",me.length>0?(q={cues:me,opsBefore:A.ops.length},ci(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 ce=vw(z.subtitles,"utf8"),me=/\.(ass|ssa)$/i.test(z.subtitles),De=me?wm(ce,A.ops):nt(ns(ut(We(ce)),A.ops)),At=tn(R,`s${A.step}${me?".ass":".srt"}`);ci(At,De),J[A.step]=me||De.trim()?At:""}else throw new l(`Internal: step ${A.step+1} cannot resolve ${A.kind}.`);x=ae()}let H=[],de=[];if(a){let _=x.gif?null:await dr(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=vm(_.markers,x.timeOps),H=x.durationSec?ss(cs(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||ci(A,as(H)),x=ae(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:Sw(w,{serverVersion:bt(),source:$l(i),steps:p,..._?{recipe:_}:{},quality:s,chapters:a})}}catch{return{}}};for(let _ of x.files)ci(_.path,_.content);if(await W(x.args,{output:se,durationSec:x.durationSec,inputDurationSec:c.durationSec,extra:r}),x.gif){let _=await Un(se,w,x.gif,r);return v({outputPath:w,...G,animation:_,...Q()})}let te;if(q)try{let _=fw(q.cues,x.timeOps,q.opsBefore);_.length>0&&(ci(y,nt(_)),te=y)}catch{te=void 0}let T;if(H.length>0)try{T=pr(w,de.filter(_=>_.t<(x.durationSec??1/0)))}catch{}return v({outputPath:w,...G,...T&&{markersPath:T},...te&&{subtitlesPath:te},...Q()})}finally{JT(R,{recursive:!0,force:!0})}}catch(n){return E(n)}})}import{z as ui}from"zod";var eA={input:ui.string().min(1).describe("Path to the source video."),platform:ui.enum(ca).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:ui.enum(["pad","crop"]).optional().describe("Fit to the platform aspect: pad (default) or crop."),output:ui.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),overwrite:ui.boolean().optional().describe("Allow replacing an existing file at the output path (default false).")};function Ew(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:eA,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=bg(e.input,o,n,e.fit??"pad");await W(i,{output:o,durationSec:await ue(e.input),extra:r});let s=Hu[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 tc,mkdirSync as tA,mkdtempSync as rA,readFileSync as kl,rmSync as El,writeFileSync as _w}from"node:fs";import{tmpdir as nA,release as oA,version as iA}from"node:os";import{join as rn}from"node:path";var sA=bt(),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(Rs).optional().describe(`Clip length without start (default ${Eu}).`),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 ${_u}).`),maxFrames:ke.number().int().min(1).max(ws).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 ${xr}).`),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.")},li=t=>Math.round(t*1e3)/1e3;async function cA(){if(process.platform!=="win32")return null;try{return(await sr()).map(e=>`${e.width}x${e.height}${e.dpi?` @${Math.round(e.dpi/96*100)}%`:""}${e.primary?" (primary)":""}`).join(", ")}catch{return null}}function Tw(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:D({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 Ps(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=$f(c,e),d=li(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()}`),g={markdown:rn(h,Bt.markdown),json:rn(h,Bt.json),clip:rn(h,Bt.clip),gif:rn(h,Bt.gif(m)),sheet:rn(h,Bt.contactSheet)},w=Object.values(g).filter($=>tc($));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.`);tc(h)||(tA(h,{recursive:!0}),n=h);let b=[],y=rA(rn(nA(),"screencast-bug-"));try{let $="unavailable",S=null,C=await br();if(C.available)S=await bs(s.path,{everySec:e.scanEverySec??_u,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.");b.push("Windows OCR is unavailable, so no error text was read.")}let M=S&&p?kf(kn(S,f,!0,"line").redactRegions):[],R=[...M,...e.regions??[]],P=S?Ef(S.frames,e.errorPattern??Cs,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=Za(s.path,g.clip,j,{width:a.width,height:a.height,fps:a.fps??30,durationSec:a.durationSec,hasAudio:a.audioCodec!==null});await W(X.args,{output:g.clip,durationSec:X.durationSec,inputDurationSec:d,extra:r}),o.push(g.clip);let N=null;e.gif!==!1&&(N=await Un(g.clip,g.gif,{format:m,maxBytes:e.maxBytes??xr},r),o.push(g.gif),N.note&&b.push(N.note)),await Ts(g.clip,_s(d,Fo),g.sheet,{tileWidth:Oo},r.signal),o.push(g.sheet);let se=(s.eventsPath?ku(je(kl(s.eventsPath,"utf8"))):[]).map(_=>p?{..._,text:Oe([_.text],f)[0]??_.text}:_),ee=s.eventsPath?se.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=Nt(s.path),ie=tc(J)?Tf(vs(kl(J,"utf8")),u,p?f:null):void 0,ae=yt(s.path),x=tc(ae)?Af(Tn(kl(ae,"utf8")),u,s.record?.perf?.summary?.process):[],q=oa(ia(i)??""),H=await cA(),de=s.record,G=_=>p?Oe([_],f)[0]??_:_,Q=[["OS",`${iA()} (${oA()}), ${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`:""}, ${li(c)} s${a.videoCodec?`, ${a.videoCodec}`:""}`],["ffmpeg",q.version??"unknown"],["screencast-mcp",`${sA} (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:li(c),width:a.width,height:a.height},files:{clip:Bt.clip,...N?{gif:Bt.gif(m)}:{},contactSheet:Bt.contactSheet},...N?{gif:{format:m,sizeBytes:N.sizeBytes,withinBudget:N.withinBudget}}:{},steps:se.slice(0,Ms),...se.length>Ms?{stepsOmitted:se.length-Ms}:{},...ee?{stepsNote:ee}:{},errors:P,...ie?{logs:ie}:{},...x.length?{perf:x}:{},ocr:$,redaction:{scanned:S!==null&&p,...S&&p?{everySec:li(S.step),framesScanned:S.frames.length}:{},found:M.length,manual:e.regions?.length??0},environment:Q};_w(g.markdown,_f(te)),o.push(g.markdown),_w(g.json,JSON.stringify({...te,steps:se,redaction:{...te.redaction,regions:R}},null,2)+`
|
|
389
|
-
`),o.push(
|
|
390
|
-
`)}var
|
|
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(` `,"")}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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),JR=`:root{--bg:#f6f5f2;--card:#fff;--ink:#16161a;--dim:#6b6b74;--line:#e2e0da;--rec:#e5383b}
|
|
391
379
|
@media (prefers-color-scheme:dark){:root{--bg:#121214;--card:#1b1b1f;--ink:#ececf1;--dim:#9a9aa6;--line:#2c2c33}}
|
|
392
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}
|
|
393
381
|
main{max-width:920px;margin:0 auto;padding:40px 16px 64px}
|
|
@@ -402,8 +390,8 @@ li{background:var(--card);border:1px solid var(--line);border-radius:10px;margin
|
|
|
402
390
|
.t{margin-left:auto;font:12px/1 ui-monospace,Consolas,monospace;color:var(--dim)}
|
|
403
391
|
li img{display:block;width:100%;height:auto;border-top:1px solid var(--line)}
|
|
404
392
|
.note{color:var(--dim);font-style:italic;margin:0 0 18px;padding-left:18px;border-left:3px solid var(--line)}
|
|
405
|
-
footer{color:var(--dim);font-size:13px;margin-top:40px;border-top:1px solid var(--line);padding-top:16px}`;function
|
|
406
|
-
`)}var
|
|
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}.`:""}
|
|
407
395
|
|
|
408
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.
|
|
409
397
|
2. sample_frames { input: <recording>, mode: "scenes" } to see what happened, and describe the moment the bug appears.
|
|
@@ -440,63 +428,63 @@ Give a timestamped summary of the main steps and anything that looks wrong.`,doc
|
|
|
440
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.
|
|
441
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.
|
|
442
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.
|
|
443
|
-
Report the guide paths, the steps, and anything you would check before sharing it.`};function
|
|
444
|
-
`)}},n=e.oninitialized;e.oninitialized=()=>{n?.(),r(!0)},e.setNotificationHandler(
|
|
445
|
-
--yes
|
|
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:
|
|
433
|
+
--yes, -y answer yes: install FFmpeg and write client configs without asking
|
|
446
434
|
--dry-run print the checks and the config changes; change nothing
|
|
447
|
-
--clients <list> detected (default) | none | a comma list of
|
|
448
|
-
${
|
|
435
|
+
--clients <list> (or --clients=<list>) detected (default) | none | a comma list of
|
|
436
|
+
${lc.join(", ")}
|
|
449
437
|
--no-install never offer to install FFmpeg
|
|
450
438
|
--force replace an existing, different "screencast" server entry
|
|
451
439
|
--test record a 3 s test clip and export a GIF
|
|
452
440
|
|
|
453
441
|
setup exits 0 when the doctor checks pass, 1 when something still needs fixing.
|
|
454
|
-
`,
|
|
455
|
-
`}}function
|
|
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(`
|
|
456
444
|
`),n=e===""?[]:e.replace(/\n$/,"").split(`
|
|
457
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(`
|
|
458
446
|
`)+`
|
|
459
|
-
`}function
|
|
460
|
-
`),!1}let s=
|
|
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})
|
|
461
449
|
`),!0;case"invalid":return r.out(` ${t.name}: left ${t.path} alone: ${s.reason}. Add the server by hand (see docs/connect.html).
|
|
462
|
-
`),!1;case"conflict":return r.out(` ${t.name}: ${t.path} already has a different "${
|
|
450
|
+
`),!1;case"conflict":return r.out(` ${t.name}: ${t.path} already has a different "${ao}" entry; kept it (pass --force to replace).
|
|
463
451
|
`),!1}if(e.dryRun)return r.out(` ${t.name}: would ${o?"update":"create"} ${t.path}:
|
|
464
|
-
`),r.out(
|
|
465
|
-
`),!1;try{let a=null;return o?(a
|
|
466
|
-
`),!0}catch(a){return r.out(` ${t.name}: could not write ${t.path}: ${
|
|
467
|
-
`),!1}}async function
|
|
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}).
|
|
468
456
|
`),!0;if(t.dryRun)return e.out(` Claude Code: would run: claude ${r.join(" ")}
|
|
469
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(" ")}
|
|
470
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}`}).
|
|
471
459
|
`),!1):(e.out(` Claude Code: added (user scope). Check it with claude mcp list.
|
|
472
|
-
`),!0)}async function
|
|
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)":""}
|
|
473
461
|
|
|
474
|
-
`);let n;try{n=await e.doctor()}catch(c){return e.err(`screencast-mcp: the doctor checks failed to run: ${
|
|
475
|
-
`),1}for(let c of
|
|
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}
|
|
476
464
|
`);let o=n.problems??[];if(o.length>0){r(`
|
|
477
465
|
What doctor says to fix:
|
|
478
466
|
`);for(let c of o)r(` - ${c}
|
|
479
|
-
`)}let i=n.ffmpeg??{};if((!i.found||i.meetsFfmpeg8===!1)&&t.install&&e.platform==="win32"){let c=`winget ${
|
|
467
|
+
`)}let i=n.ffmpeg??{};if((!i.found||i.meetsFfmpeg8===!1)&&t.install&&e.platform==="win32"){let c=`winget ${_y.join(" ")}`;if(r(`
|
|
480
468
|
FFmpeg 8 ${i.found?"is not installed (found an older one)":"is missing"}.
|
|
481
469
|
`),t.dryRun)r(` would run: ${c}
|
|
482
470
|
`);else if(t.yes||await e.confirm("Install FFmpeg 8 with winget now?")){r(` running: ${c}
|
|
483
|
-
`);let u=await e.exec("winget",
|
|
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.
|
|
484
472
|
`):r(` winget failed (${(u.stderr||u.stdout).trim().split(`
|
|
485
473
|
`).pop()||`exit ${u.code}`}). Install it yourself: ${c}
|
|
486
474
|
`)}else r(` skipped. Install it yourself: ${c}
|
|
487
|
-
`)}if(t.clients!=="none"){let c=t.clients==="detected"?await
|
|
475
|
+
`)}if(t.clients!=="none"){let c=t.clients==="detected"?await RA(e):t.clients;r(`
|
|
488
476
|
MCP clients:
|
|
489
477
|
`),c.length===0&&r(` none found (Claude Desktop, Claude Code, Cursor, VS Code). Name one with --clients, or see docs/connect.html.
|
|
490
|
-
`);let u=new Map(
|
|
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(`
|
|
491
479
|
Test clip:
|
|
492
480
|
`),t.dryRun)r(` would record 3 s of the screen and export a GIF.
|
|
493
481
|
`);else try{let c=await e.testClip();r(` recorded 3 s and exported ${c}
|
|
494
|
-
`),await e.open(c).catch(()=>{})}catch(c){return r(` the test clip failed: ${
|
|
482
|
+
`),await e.open(c).catch(()=>{})}catch(c){return r(` the test clip failed: ${z(c)}
|
|
495
483
|
`),1}let a=n.ok??o.length===0;return r(a?`
|
|
496
484
|
All checks passed.
|
|
497
485
|
`:`
|
|
498
486
|
Some checks need attention (above). Run setup again after fixing them.
|
|
499
|
-
`),a?0:1}function
|
|
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.
|
|
500
488
|
|
|
501
489
|
Usage:
|
|
502
490
|
screencast-mcp run the MCP server over stdio (default)
|
|
@@ -521,37 +509,40 @@ record options:
|
|
|
521
509
|
--redact-secrets OCR the recording and blur on-screen secrets (API keys, tokens,
|
|
522
510
|
password: values) in the GIF and contact sheet (Windows OCR)
|
|
523
511
|
--secret-pattern <re> with --redact-secrets, the regex to blur instead of the default
|
|
524
|
-
--max-duration <sec> stop recording after <sec> seconds, an integer 0-${
|
|
512
|
+
--max-duration <sec> stop recording after <sec> seconds, an integer 0-${It}
|
|
525
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)
|
|
526
517
|
--command-env <NAME> run the command line in environment variable NAME instead of
|
|
527
518
|
the arguments after --, so quotes and & survive any shell
|
|
528
519
|
|
|
529
520
|
record exits with the command's exit code and writes <out>/evidence.json.
|
|
530
521
|
|
|
531
|
-
${
|
|
532
|
-
`);return{isError:i.isError===!0,text:s,structured:i.structuredContent}},close:()=>r.close()}}async function
|
|
533
|
-
`),s(127)}),r.on("exit",(a,c)=>s(a??(c?1:0)))})}function
|
|
534
|
-
`)},s=await r.connect();try{let a=null;try{let p=await
|
|
535
|
-
`)}catch(p){i(`recording did not start, running the command without it: ${
|
|
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)+`
|
|
536
527
|
`),e.err(`screencast-mcp: command exited ${o.exitCode}; evidence in ${n}`+(o.gif?` (gif: ${o.gif})`:"")+`
|
|
537
|
-
`),o.exitCode}var
|
|
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}
|
|
538
529
|
`),1):(r.out((i.structured?JSON.stringify(i.structured,null,2):i.text)+`
|
|
539
|
-
`),0)}finally{await o.close()}}async function
|
|
540
|
-
`),2;throw n}switch(r.kind){case"help":return e.out(
|
|
541
|
-
`),0;case"record":return
|
|
542
|
-
`),2;throw n}}}import{readdir as
|
|
543
|
-
`)}catch(n){process.stderr.write(`Orphan reaping skipped: ${
|
|
544
|
-
`)}try{let n=
|
|
545
|
-
`)}catch(n){process.stderr.write(`Replay buffer cleanup skipped: ${
|
|
546
|
-
`)}let e=new
|
|
547
|
-
`)},n=>{process.stderr.write(`Retention prune failed: ${
|
|
548
|
-
`)}),process.stdin.on("end",()=>{
|
|
549
|
-
`),
|
|
550
|
-
`),
|
|
551
|
-
`)})}async function
|
|
552
|
-
`),
|
|
553
|
-
`)}}catch(o){process.stderr.write(`Shutdown cleanup failed: ${
|
|
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)}
|
|
554
545
|
`)}let n=await r;n>0&&process.stderr.write(`Shutdown (${t}): cancelled ${n} edit job(s).
|
|
555
|
-
`),process.exit(e)}var
|
|
556
|
-
`),process.exit(1)},
|
|
557
|
-
`)}),
|
|
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);
|